var Hk = Object.defineProperty;
var vp = (n) => {
  throw TypeError(n);
};
var Vk = (n, e, t) => e in n ? Hk(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
var pe = (n, e, t) => Vk(n, typeof e != "symbol" ? e + "" : e, t), Uk = (n, e, t) => e.has(n) || vp("Cannot " + t);
var Cp = (n, e, t) => e.has(n) ? vp("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(n) : e.set(n, t);
var rl = (n, e, t) => (Uk(n, e, "access private method"), t);
const {
  SvelteComponent: qk,
  append_hydration: nu,
  assign: jk,
  attr: et,
  binding_callbacks: Wk,
  children: jo,
  claim_element: mb,
  claim_space: gb,
  claim_svg_element: Zc,
  create_slot: Gk,
  detach: Cn,
  element: bb,
  empty: Sp,
  get_all_dirty_from_scope: Kk,
  get_slot_changes: Jk,
  get_spread_update: Yk,
  init: Xk,
  insert_hydration: ds,
  listen: Zk,
  noop: Qk,
  safe_not_equal: ev,
  set_dynamic_element_data: Ep,
  set_style: re,
  space: yb,
  svg_element: Qc,
  toggle_class: Re,
  transition_in: _b,
  transition_out: wb,
  update_slot_base: tv
} = window.__gradio__svelte__internal;
function xp(n) {
  let e, t, r, i, o;
  return {
    c() {
      e = Qc("svg"), t = Qc("line"), r = Qc("line"), this.h();
    },
    l(s) {
      e = Zc(s, "svg", { class: !0, xmlns: !0, viewBox: !0 });
      var l = jo(e);
      t = Zc(l, "line", {
        x1: !0,
        y1: !0,
        x2: !0,
        y2: !0,
        stroke: !0,
        "stroke-width": !0
      }), jo(t).forEach(Cn), r = Zc(l, "line", {
        x1: !0,
        y1: !0,
        x2: !0,
        y2: !0,
        stroke: !0,
        "stroke-width": !0
      }), jo(r).forEach(Cn), l.forEach(Cn), this.h();
    },
    h() {
      et(t, "x1", "1"), et(t, "y1", "9"), et(t, "x2", "9"), et(t, "y2", "1"), et(t, "stroke", "gray"), et(t, "stroke-width", "0.5"), et(r, "x1", "5"), et(r, "y1", "9"), et(r, "x2", "9"), et(r, "y2", "5"), et(r, "stroke", "gray"), et(r, "stroke-width", "0.5"), et(e, "class", "resize-handle svelte-239wnu"), et(e, "xmlns", "http://www.w3.org/2000/svg"), et(e, "viewBox", "0 0 10 10");
    },
    m(s, l) {
      ds(s, e, l), nu(e, t), nu(e, r), i || (o = Zk(
        e,
        "mousedown",
        /*resize*/
        n[27]
      ), i = !0);
    },
    p: Qk,
    d(s) {
      s && Cn(e), i = !1, o();
    }
  };
}
function nv(n) {
  var u;
  let e, t, r, i, o;
  const s = (
    /*#slots*/
    n[31].default
  ), l = Gk(
    s,
    n,
    /*$$scope*/
    n[30],
    null
  );
  let a = (
    /*resizable*/
    n[19] && xp(n)
  ), c = [
    { "data-testid": (
      /*test_id*/
      n[11]
    ) },
    { id: (
      /*elem_id*/
      n[6]
    ) },
    {
      class: r = "block " + /*elem_classes*/
      (((u = n[7]) == null ? void 0 : u.join(" ")) || "") + " svelte-239wnu"
    },
    {
      dir: i = /*rtl*/
      n[20] ? "rtl" : "ltr"
    }
  ], d = {};
  for (let h = 0; h < c.length; h += 1)
    d = jk(d, c[h]);
  return {
    c() {
      e = bb(
        /*tag*/
        n[25]
      ), l && l.c(), t = yb(), a && a.c(), this.h();
    },
    l(h) {
      e = mb(
        h,
        /*tag*/
        (n[25] || "null").toUpperCase(),
        {
          "data-testid": !0,
          id: !0,
          class: !0,
          dir: !0
        }
      );
      var f = jo(e);
      l && l.l(f), t = gb(f), a && a.l(f), f.forEach(Cn), this.h();
    },
    h() {
      Ep(
        /*tag*/
        n[25]
      )(e, d), Re(
        e,
        "hidden",
        /*visible*/
        n[14] === !1
      ), Re(
        e,
        "padded",
        /*padding*/
        n[10]
      ), Re(
        e,
        "flex",
        /*flex*/
        n[1]
      ), Re(
        e,
        "border_focus",
        /*border_mode*/
        n[9] === "focus"
      ), Re(
        e,
        "border_contrast",
        /*border_mode*/
        n[9] === "contrast"
      ), Re(e, "hide-container", !/*explicit_call*/
      n[12] && !/*container*/
      n[13]), Re(
        e,
        "fullscreen",
        /*fullscreen*/
        n[0]
      ), Re(
        e,
        "animating",
        /*fullscreen*/
        n[0] && /*preexpansionBoundingRect*/
        n[24] !== null
      ), Re(
        e,
        "auto-margin",
        /*scale*/
        n[17] === null
      ), re(
        e,
        "height",
        /*fullscreen*/
        n[0] ? void 0 : (
          /*get_dimension*/
          n[26](
            /*height*/
            n[2]
          )
        )
      ), re(
        e,
        "min-height",
        /*fullscreen*/
        n[0] ? void 0 : (
          /*get_dimension*/
          n[26](
            /*min_height*/
            n[3]
          )
        )
      ), re(
        e,
        "max-height",
        /*fullscreen*/
        n[0] ? void 0 : (
          /*get_dimension*/
          n[26](
            /*max_height*/
            n[4]
          )
        )
      ), re(
        e,
        "--start-top",
        /*preexpansionBoundingRect*/
        n[24] ? `${/*preexpansionBoundingRect*/
        n[24].top}px` : "0px"
      ), re(
        e,
        "--start-left",
        /*preexpansionBoundingRect*/
        n[24] ? `${/*preexpansionBoundingRect*/
        n[24].left}px` : "0px"
      ), re(
        e,
        "--start-width",
        /*preexpansionBoundingRect*/
        n[24] ? `${/*preexpansionBoundingRect*/
        n[24].width}px` : "0px"
      ), re(
        e,
        "--start-height",
        /*preexpansionBoundingRect*/
        n[24] ? `${/*preexpansionBoundingRect*/
        n[24].height}px` : "0px"
      ), re(
        e,
        "width",
        /*fullscreen*/
        n[0] ? void 0 : typeof /*width*/
        n[5] == "number" ? `calc(min(${/*width*/
        n[5]}px, 100%))` : (
          /*get_dimension*/
          n[26](
            /*width*/
            n[5]
          )
        )
      ), re(
        e,
        "border-style",
        /*variant*/
        n[8]
      ), re(
        e,
        "overflow",
        /*allow_overflow*/
        n[15] ? (
          /*overflow_behavior*/
          n[16]
        ) : "hidden"
      ), re(
        e,
        "flex-grow",
        /*scale*/
        n[17]
      ), re(e, "min-width", `calc(min(${/*min_width*/
      n[18]}px, 100%))`), re(e, "border-width", "var(--block-border-width)");
    },
    m(h, f) {
      ds(h, e, f), l && l.m(e, null), nu(e, t), a && a.m(e, null), n[32](e), o = !0;
    },
    p(h, f) {
      var p;
      l && l.p && (!o || f[0] & /*$$scope*/
      1073741824) && tv(
        l,
        s,
        h,
        /*$$scope*/
        h[30],
        o ? Jk(
          s,
          /*$$scope*/
          h[30],
          f,
          null
        ) : Kk(
          /*$$scope*/
          h[30]
        ),
        null
      ), /*resizable*/
      h[19] ? a ? a.p(h, f) : (a = xp(h), a.c(), a.m(e, null)) : a && (a.d(1), a = null), Ep(
        /*tag*/
        h[25]
      )(e, d = Yk(c, [
        (!o || f[0] & /*test_id*/
        2048) && { "data-testid": (
          /*test_id*/
          h[11]
        ) },
        (!o || f[0] & /*elem_id*/
        64) && { id: (
          /*elem_id*/
          h[6]
        ) },
        (!o || f[0] & /*elem_classes*/
        128 && r !== (r = "block " + /*elem_classes*/
        (((p = h[7]) == null ? void 0 : p.join(" ")) || "") + " svelte-239wnu")) && { class: r },
        (!o || f[0] & /*rtl*/
        1048576 && i !== (i = /*rtl*/
        h[20] ? "rtl" : "ltr")) && { dir: i }
      ])), Re(
        e,
        "hidden",
        /*visible*/
        h[14] === !1
      ), Re(
        e,
        "padded",
        /*padding*/
        h[10]
      ), Re(
        e,
        "flex",
        /*flex*/
        h[1]
      ), Re(
        e,
        "border_focus",
        /*border_mode*/
        h[9] === "focus"
      ), Re(
        e,
        "border_contrast",
        /*border_mode*/
        h[9] === "contrast"
      ), Re(e, "hide-container", !/*explicit_call*/
      h[12] && !/*container*/
      h[13]), Re(
        e,
        "fullscreen",
        /*fullscreen*/
        h[0]
      ), Re(
        e,
        "animating",
        /*fullscreen*/
        h[0] && /*preexpansionBoundingRect*/
        h[24] !== null
      ), Re(
        e,
        "auto-margin",
        /*scale*/
        h[17] === null
      ), f[0] & /*fullscreen, height*/
      5 && re(
        e,
        "height",
        /*fullscreen*/
        h[0] ? void 0 : (
          /*get_dimension*/
          h[26](
            /*height*/
            h[2]
          )
        )
      ), f[0] & /*fullscreen, min_height*/
      9 && re(
        e,
        "min-height",
        /*fullscreen*/
        h[0] ? void 0 : (
          /*get_dimension*/
          h[26](
            /*min_height*/
            h[3]
          )
        )
      ), f[0] & /*fullscreen, max_height*/
      17 && re(
        e,
        "max-height",
        /*fullscreen*/
        h[0] ? void 0 : (
          /*get_dimension*/
          h[26](
            /*max_height*/
            h[4]
          )
        )
      ), f[0] & /*preexpansionBoundingRect*/
      16777216 && re(
        e,
        "--start-top",
        /*preexpansionBoundingRect*/
        h[24] ? `${/*preexpansionBoundingRect*/
        h[24].top}px` : "0px"
      ), f[0] & /*preexpansionBoundingRect*/
      16777216 && re(
        e,
        "--start-left",
        /*preexpansionBoundingRect*/
        h[24] ? `${/*preexpansionBoundingRect*/
        h[24].left}px` : "0px"
      ), f[0] & /*preexpansionBoundingRect*/
      16777216 && re(
        e,
        "--start-width",
        /*preexpansionBoundingRect*/
        h[24] ? `${/*preexpansionBoundingRect*/
        h[24].width}px` : "0px"
      ), f[0] & /*preexpansionBoundingRect*/
      16777216 && re(
        e,
        "--start-height",
        /*preexpansionBoundingRect*/
        h[24] ? `${/*preexpansionBoundingRect*/
        h[24].height}px` : "0px"
      ), f[0] & /*fullscreen, width*/
      33 && re(
        e,
        "width",
        /*fullscreen*/
        h[0] ? void 0 : typeof /*width*/
        h[5] == "number" ? `calc(min(${/*width*/
        h[5]}px, 100%))` : (
          /*get_dimension*/
          h[26](
            /*width*/
            h[5]
          )
        )
      ), f[0] & /*variant*/
      256 && re(
        e,
        "border-style",
        /*variant*/
        h[8]
      ), f[0] & /*allow_overflow, overflow_behavior*/
      98304 && re(
        e,
        "overflow",
        /*allow_overflow*/
        h[15] ? (
          /*overflow_behavior*/
          h[16]
        ) : "hidden"
      ), f[0] & /*scale*/
      131072 && re(
        e,
        "flex-grow",
        /*scale*/
        h[17]
      ), f[0] & /*min_width*/
      262144 && re(e, "min-width", `calc(min(${/*min_width*/
      h[18]}px, 100%))`);
    },
    i(h) {
      o || (_b(l, h), o = !0);
    },
    o(h) {
      wb(l, h), o = !1;
    },
    d(h) {
      h && Cn(e), l && l.d(h), a && a.d(), n[32](null);
    }
  };
}
function Dp(n) {
  let e;
  return {
    c() {
      e = bb("div"), this.h();
    },
    l(t) {
      e = mb(t, "DIV", { class: !0 }), jo(e).forEach(Cn), this.h();
    },
    h() {
      et(e, "class", "placeholder svelte-239wnu"), re(
        e,
        "height",
        /*placeholder_height*/
        n[22] + "px"
      ), re(
        e,
        "width",
        /*placeholder_width*/
        n[23] + "px"
      );
    },
    m(t, r) {
      ds(t, e, r);
    },
    p(t, r) {
      r[0] & /*placeholder_height*/
      4194304 && re(
        e,
        "height",
        /*placeholder_height*/
        t[22] + "px"
      ), r[0] & /*placeholder_width*/
      8388608 && re(
        e,
        "width",
        /*placeholder_width*/
        t[23] + "px"
      );
    },
    d(t) {
      t && Cn(e);
    }
  };
}
function rv(n) {
  let e, t, r, i = (
    /*tag*/
    n[25] && nv(n)
  ), o = (
    /*fullscreen*/
    n[0] && Dp(n)
  );
  return {
    c() {
      i && i.c(), e = yb(), o && o.c(), t = Sp();
    },
    l(s) {
      i && i.l(s), e = gb(s), o && o.l(s), t = Sp();
    },
    m(s, l) {
      i && i.m(s, l), ds(s, e, l), o && o.m(s, l), ds(s, t, l), r = !0;
    },
    p(s, l) {
      /*tag*/
      s[25] && i.p(s, l), /*fullscreen*/
      s[0] ? o ? o.p(s, l) : (o = Dp(s), o.c(), o.m(t.parentNode, t)) : o && (o.d(1), o = null);
    },
    i(s) {
      r || (_b(i, s), r = !0);
    },
    o(s) {
      wb(i, s), r = !1;
    },
    d(s) {
      s && (Cn(e), Cn(t)), i && i.d(s), o && o.d(s);
    }
  };
}
function iv(n, e, t) {
  let { $$slots: r = {}, $$scope: i } = e, { height: o = void 0 } = e, { min_height: s = void 0 } = e, { max_height: l = void 0 } = e, { width: a = void 0 } = e, { elem_id: c = "" } = e, { elem_classes: d = [] } = e, { variant: u = "solid" } = e, { border_mode: h = "base" } = e, { padding: f = !0 } = e, { type: p = "normal" } = e, { test_id: m = void 0 } = e, { explicit_call: g = !1 } = e, { container: y = !0 } = e, { visible: _ = !0 } = e, { allow_overflow: b = !0 } = e, { overflow_behavior: k = "auto" } = e, { scale: C = null } = e, { min_width: w = 0 } = e, { flex: x = !1 } = e, { resizable: S = !1 } = e, { rtl: D = !1 } = e, { fullscreen: T = !1 } = e, I = T, U, Te = p === "fieldset" ? "fieldset" : "div", ce = 0, fe = 0, K = null;
  function be(N) {
    T && N.key === "Escape" && t(0, T = !1);
  }
  const ke = (N) => {
    if (N !== void 0) {
      if (typeof N == "number")
        return N + "px";
      if (typeof N == "string")
        return N;
    }
  }, qe = (N) => {
    let $e = N.clientY;
    const ye = ($) => {
      const $t = $.clientY - $e;
      $e = $.clientY, t(21, U.style.height = `${U.offsetHeight + $t}px`, U);
    }, Ye = () => {
      window.removeEventListener("mousemove", ye), window.removeEventListener("mouseup", Ye);
    };
    window.addEventListener("mousemove", ye), window.addEventListener("mouseup", Ye);
  };
  function mt(N) {
    Wk[N ? "unshift" : "push"](() => {
      U = N, t(21, U);
    });
  }
  return n.$$set = (N) => {
    "height" in N && t(2, o = N.height), "min_height" in N && t(3, s = N.min_height), "max_height" in N && t(4, l = N.max_height), "width" in N && t(5, a = N.width), "elem_id" in N && t(6, c = N.elem_id), "elem_classes" in N && t(7, d = N.elem_classes), "variant" in N && t(8, u = N.variant), "border_mode" in N && t(9, h = N.border_mode), "padding" in N && t(10, f = N.padding), "type" in N && t(28, p = N.type), "test_id" in N && t(11, m = N.test_id), "explicit_call" in N && t(12, g = N.explicit_call), "container" in N && t(13, y = N.container), "visible" in N && t(14, _ = N.visible), "allow_overflow" in N && t(15, b = N.allow_overflow), "overflow_behavior" in N && t(16, k = N.overflow_behavior), "scale" in N && t(17, C = N.scale), "min_width" in N && t(18, w = N.min_width), "flex" in N && t(1, x = N.flex), "resizable" in N && t(19, S = N.resizable), "rtl" in N && t(20, D = N.rtl), "fullscreen" in N && t(0, T = N.fullscreen), "$$scope" in N && t(30, i = N.$$scope);
  }, n.$$.update = () => {
    n.$$.dirty[0] & /*fullscreen, old_fullscreen, element*/
    538968065 && T !== I && (t(29, I = T), T ? (t(24, K = U.getBoundingClientRect()), t(22, ce = U.offsetHeight), t(23, fe = U.offsetWidth), window.addEventListener("keydown", be)) : (t(24, K = null), window.removeEventListener("keydown", be))), n.$$.dirty[0] & /*visible*/
    16384 && (_ || t(1, x = !1));
  }, [
    T,
    x,
    o,
    s,
    l,
    a,
    c,
    d,
    u,
    h,
    f,
    m,
    g,
    y,
    _,
    b,
    k,
    C,
    w,
    S,
    D,
    U,
    ce,
    fe,
    K,
    Te,
    ke,
    qe,
    p,
    I,
    i,
    r,
    mt
  ];
}
class ov extends qk {
  constructor(e) {
    super(), Xk(
      this,
      e,
      iv,
      rv,
      ev,
      {
        height: 2,
        min_height: 3,
        max_height: 4,
        width: 5,
        elem_id: 6,
        elem_classes: 7,
        variant: 8,
        border_mode: 9,
        padding: 10,
        type: 28,
        test_id: 11,
        explicit_call: 12,
        container: 13,
        visible: 14,
        allow_overflow: 15,
        overflow_behavior: 16,
        scale: 17,
        min_width: 18,
        flex: 1,
        resizable: 19,
        rtl: 20,
        fullscreen: 0
      },
      null,
      [-1, -1]
    );
  }
}
function kh() {
  return {
    async: !1,
    breaks: !1,
    extensions: null,
    gfm: !0,
    hooks: null,
    pedantic: !1,
    renderer: null,
    silent: !1,
    tokenizer: null,
    walkTokens: null
  };
}
let Si = kh();
function kb(n) {
  Si = n;
}
const vb = /[&<>"']/, sv = new RegExp(vb.source, "g"), Cb = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, lv = new RegExp(Cb.source, "g"), av = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
}, Ap = (n) => av[n];
function Et(n, e) {
  if (e) {
    if (vb.test(n))
      return n.replace(sv, Ap);
  } else if (Cb.test(n))
    return n.replace(lv, Ap);
  return n;
}
const cv = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
function dv(n) {
  return n.replace(cv, (e, t) => (t = t.toLowerCase(), t === "colon" ? ":" : t.charAt(0) === "#" ? t.charAt(1) === "x" ? String.fromCharCode(parseInt(t.substring(2), 16)) : String.fromCharCode(+t.substring(1)) : ""));
}
const uv = /(^|[^\[])\^/g;
function ae(n, e) {
  let t = typeof n == "string" ? n : n.source;
  e = e || "";
  const r = {
    replace: (i, o) => {
      let s = typeof o == "string" ? o : o.source;
      return s = s.replace(uv, "$1"), t = t.replace(i, s), r;
    },
    getRegex: () => new RegExp(t, e)
  };
  return r;
}
function Tp(n) {
  try {
    n = encodeURI(n).replace(/%25/g, "%");
  } catch {
    return null;
  }
  return n;
}
const Wo = { exec: () => null };
function Mp(n, e) {
  const t = n.replace(/\|/g, (o, s, l) => {
    let a = !1, c = s;
    for (; --c >= 0 && l[c] === "\\"; )
      a = !a;
    return a ? "|" : " |";
  }), r = t.split(/ \|/);
  let i = 0;
  if (r[0].trim() || r.shift(), r.length > 0 && !r[r.length - 1].trim() && r.pop(), e)
    if (r.length > e)
      r.splice(e);
    else
      for (; r.length < e; )
        r.push("");
  for (; i < r.length; i++)
    r[i] = r[i].trim().replace(/\\\|/g, "|");
  return r;
}
function il(n, e, t) {
  const r = n.length;
  if (r === 0)
    return "";
  let i = 0;
  for (; i < r && n.charAt(r - i - 1) === e; )
    i++;
  return n.slice(0, r - i);
}
function hv(n, e) {
  if (n.indexOf(e[1]) === -1)
    return -1;
  let t = 0;
  for (let r = 0; r < n.length; r++)
    if (n[r] === "\\")
      r++;
    else if (n[r] === e[0])
      t++;
    else if (n[r] === e[1] && (t--, t < 0))
      return r;
  return -1;
}
function Op(n, e, t, r) {
  const i = e.href, o = e.title ? Et(e.title) : null, s = n[1].replace(/\\([\[\]])/g, "$1");
  if (n[0].charAt(0) !== "!") {
    r.state.inLink = !0;
    const l = {
      type: "link",
      raw: t,
      href: i,
      title: o,
      text: s,
      tokens: r.inlineTokens(s)
    };
    return r.state.inLink = !1, l;
  }
  return {
    type: "image",
    raw: t,
    href: i,
    title: o,
    text: Et(s)
  };
}
function fv(n, e) {
  const t = n.match(/^(\s+)(?:```)/);
  if (t === null)
    return e;
  const r = t[1];
  return e.split(`
`).map((i) => {
    const o = i.match(/^\s+/);
    if (o === null)
      return i;
    const [s] = o;
    return s.length >= r.length ? i.slice(r.length) : i;
  }).join(`
`);
}
class la {
  // set by the lexer
  constructor(e) {
    pe(this, "options");
    pe(this, "rules");
    // set by the lexer
    pe(this, "lexer");
    this.options = e || Si;
  }
  space(e) {
    const t = this.rules.block.newline.exec(e);
    if (t && t[0].length > 0)
      return {
        type: "space",
        raw: t[0]
      };
  }
  code(e) {
    const t = this.rules.block.code.exec(e);
    if (t) {
      const r = t[0].replace(/^ {1,4}/gm, "");
      return {
        type: "code",
        raw: t[0],
        codeBlockStyle: "indented",
        text: this.options.pedantic ? r : il(r, `
`)
      };
    }
  }
  fences(e) {
    const t = this.rules.block.fences.exec(e);
    if (t) {
      const r = t[0], i = fv(r, t[3] || "");
      return {
        type: "code",
        raw: r,
        lang: t[2] ? t[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t[2],
        text: i
      };
    }
  }
  heading(e) {
    const t = this.rules.block.heading.exec(e);
    if (t) {
      let r = t[2].trim();
      if (/#$/.test(r)) {
        const i = il(r, "#");
        (this.options.pedantic || !i || / $/.test(i)) && (r = i.trim());
      }
      return {
        type: "heading",
        raw: t[0],
        depth: t[1].length,
        text: r,
        tokens: this.lexer.inline(r)
      };
    }
  }
  hr(e) {
    const t = this.rules.block.hr.exec(e);
    if (t)
      return {
        type: "hr",
        raw: t[0]
      };
  }
  blockquote(e) {
    const t = this.rules.block.blockquote.exec(e);
    if (t) {
      let r = t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, `
    $1`);
      r = il(r.replace(/^ *>[ \t]?/gm, ""), `
`);
      const i = this.lexer.state.top;
      this.lexer.state.top = !0;
      const o = this.lexer.blockTokens(r);
      return this.lexer.state.top = i, {
        type: "blockquote",
        raw: t[0],
        tokens: o,
        text: r
      };
    }
  }
  list(e) {
    let t = this.rules.block.list.exec(e);
    if (t) {
      let r = t[1].trim();
      const i = r.length > 1, o = {
        type: "list",
        raw: "",
        ordered: i,
        start: i ? +r.slice(0, -1) : "",
        loose: !1,
        items: []
      };
      r = i ? `\\d{1,9}\\${r.slice(-1)}` : `\\${r}`, this.options.pedantic && (r = i ? r : "[*+-]");
      const s = new RegExp(`^( {0,3}${r})((?:[	 ][^\\n]*)?(?:\\n|$))`);
      let l = "", a = "", c = !1;
      for (; e; ) {
        let d = !1;
        if (!(t = s.exec(e)) || this.rules.block.hr.test(e))
          break;
        l = t[0], e = e.substring(l.length);
        let u = t[2].split(`
`, 1)[0].replace(/^\t+/, (y) => " ".repeat(3 * y.length)), h = e.split(`
`, 1)[0], f = 0;
        this.options.pedantic ? (f = 2, a = u.trimStart()) : (f = t[2].search(/[^ ]/), f = f > 4 ? 1 : f, a = u.slice(f), f += t[1].length);
        let p = !1;
        if (!u && /^ *$/.test(h) && (l += h + `
`, e = e.substring(h.length + 1), d = !0), !d) {
          const y = new RegExp(`^ {0,${Math.min(3, f - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`), _ = new RegExp(`^ {0,${Math.min(3, f - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), b = new RegExp(`^ {0,${Math.min(3, f - 1)}}(?:\`\`\`|~~~)`), k = new RegExp(`^ {0,${Math.min(3, f - 1)}}#`);
          for (; e; ) {
            const C = e.split(`
`, 1)[0];
            if (h = C, this.options.pedantic && (h = h.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ")), b.test(h) || k.test(h) || y.test(h) || _.test(e))
              break;
            if (h.search(/[^ ]/) >= f || !h.trim())
              a += `
` + h.slice(f);
            else {
              if (p || u.search(/[^ ]/) >= 4 || b.test(u) || k.test(u) || _.test(u))
                break;
              a += `
` + h;
            }
            !p && !h.trim() && (p = !0), l += C + `
`, e = e.substring(C.length + 1), u = h.slice(f);
          }
        }
        o.loose || (c ? o.loose = !0 : /\n *\n *$/.test(l) && (c = !0));
        let m = null, g;
        this.options.gfm && (m = /^\[[ xX]\] /.exec(a), m && (g = m[0] !== "[ ] ", a = a.replace(/^\[[ xX]\] +/, ""))), o.items.push({
          type: "list_item",
          raw: l,
          task: !!m,
          checked: g,
          loose: !1,
          text: a,
          tokens: []
        }), o.raw += l;
      }
      o.items[o.items.length - 1].raw = l.trimEnd(), o.items[o.items.length - 1].text = a.trimEnd(), o.raw = o.raw.trimEnd();
      for (let d = 0; d < o.items.length; d++)
        if (this.lexer.state.top = !1, o.items[d].tokens = this.lexer.blockTokens(o.items[d].text, []), !o.loose) {
          const u = o.items[d].tokens.filter((f) => f.type === "space"), h = u.length > 0 && u.some((f) => /\n.*\n/.test(f.raw));
          o.loose = h;
        }
      if (o.loose)
        for (let d = 0; d < o.items.length; d++)
          o.items[d].loose = !0;
      return o;
    }
  }
  html(e) {
    const t = this.rules.block.html.exec(e);
    if (t)
      return {
        type: "html",
        block: !0,
        raw: t[0],
        pre: t[1] === "pre" || t[1] === "script" || t[1] === "style",
        text: t[0]
      };
  }
  def(e) {
    const t = this.rules.block.def.exec(e);
    if (t) {
      const r = t[1].toLowerCase().replace(/\s+/g, " "), i = t[2] ? t[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", o = t[3] ? t[3].substring(1, t[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t[3];
      return {
        type: "def",
        tag: r,
        raw: t[0],
        href: i,
        title: o
      };
    }
  }
  table(e) {
    const t = this.rules.block.table.exec(e);
    if (!t || !/[:|]/.test(t[2]))
      return;
    const r = Mp(t[1]), i = t[2].replace(/^\||\| *$/g, "").split("|"), o = t[3] && t[3].trim() ? t[3].replace(/\n[ \t]*$/, "").split(`
`) : [], s = {
      type: "table",
      raw: t[0],
      header: [],
      align: [],
      rows: []
    };
    if (r.length === i.length) {
      for (const l of i)
        /^ *-+: *$/.test(l) ? s.align.push("right") : /^ *:-+: *$/.test(l) ? s.align.push("center") : /^ *:-+ *$/.test(l) ? s.align.push("left") : s.align.push(null);
      for (const l of r)
        s.header.push({
          text: l,
          tokens: this.lexer.inline(l)
        });
      for (const l of o)
        s.rows.push(Mp(l, s.header.length).map((a) => ({
          text: a,
          tokens: this.lexer.inline(a)
        })));
      return s;
    }
  }
  lheading(e) {
    const t = this.rules.block.lheading.exec(e);
    if (t)
      return {
        type: "heading",
        raw: t[0],
        depth: t[2].charAt(0) === "=" ? 1 : 2,
        text: t[1],
        tokens: this.lexer.inline(t[1])
      };
  }
  paragraph(e) {
    const t = this.rules.block.paragraph.exec(e);
    if (t) {
      const r = t[1].charAt(t[1].length - 1) === `
` ? t[1].slice(0, -1) : t[1];
      return {
        type: "paragraph",
        raw: t[0],
        text: r,
        tokens: this.lexer.inline(r)
      };
    }
  }
  text(e) {
    const t = this.rules.block.text.exec(e);
    if (t)
      return {
        type: "text",
        raw: t[0],
        text: t[0],
        tokens: this.lexer.inline(t[0])
      };
  }
  escape(e) {
    const t = this.rules.inline.escape.exec(e);
    if (t)
      return {
        type: "escape",
        raw: t[0],
        text: Et(t[1])
      };
  }
  tag(e) {
    const t = this.rules.inline.tag.exec(e);
    if (t)
      return !this.lexer.state.inLink && /^<a /i.test(t[0]) ? this.lexer.state.inLink = !0 : this.lexer.state.inLink && /^<\/a>/i.test(t[0]) && (this.lexer.state.inLink = !1), !this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(t[0]) ? this.lexer.state.inRawBlock = !0 : this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0]) && (this.lexer.state.inRawBlock = !1), {
        type: "html",
        raw: t[0],
        inLink: this.lexer.state.inLink,
        inRawBlock: this.lexer.state.inRawBlock,
        block: !1,
        text: t[0]
      };
  }
  link(e) {
    const t = this.rules.inline.link.exec(e);
    if (t) {
      const r = t[2].trim();
      if (!this.options.pedantic && /^</.test(r)) {
        if (!/>$/.test(r))
          return;
        const s = il(r.slice(0, -1), "\\");
        if ((r.length - s.length) % 2 === 0)
          return;
      } else {
        const s = hv(t[2], "()");
        if (s > -1) {
          const a = (t[0].indexOf("!") === 0 ? 5 : 4) + t[1].length + s;
          t[2] = t[2].substring(0, s), t[0] = t[0].substring(0, a).trim(), t[3] = "";
        }
      }
      let i = t[2], o = "";
      if (this.options.pedantic) {
        const s = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(i);
        s && (i = s[1], o = s[3]);
      } else
        o = t[3] ? t[3].slice(1, -1) : "";
      return i = i.trim(), /^</.test(i) && (this.options.pedantic && !/>$/.test(r) ? i = i.slice(1) : i = i.slice(1, -1)), Op(t, {
        href: i && i.replace(this.rules.inline.anyPunctuation, "$1"),
        title: o && o.replace(this.rules.inline.anyPunctuation, "$1")
      }, t[0], this.lexer);
    }
  }
  reflink(e, t) {
    let r;
    if ((r = this.rules.inline.reflink.exec(e)) || (r = this.rules.inline.nolink.exec(e))) {
      const i = (r[2] || r[1]).replace(/\s+/g, " "), o = t[i.toLowerCase()];
      if (!o) {
        const s = r[0].charAt(0);
        return {
          type: "text",
          raw: s,
          text: s
        };
      }
      return Op(r, o, r[0], this.lexer);
    }
  }
  emStrong(e, t, r = "") {
    let i = this.rules.inline.emStrongLDelim.exec(e);
    if (!i || i[3] && r.match(/[\p{L}\p{N}]/u))
      return;
    if (!(i[1] || i[2] || "") || !r || this.rules.inline.punctuation.exec(r)) {
      const s = [...i[0]].length - 1;
      let l, a, c = s, d = 0;
      const u = i[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      for (u.lastIndex = 0, t = t.slice(-1 * e.length + s); (i = u.exec(t)) != null; ) {
        if (l = i[1] || i[2] || i[3] || i[4] || i[5] || i[6], !l)
          continue;
        if (a = [...l].length, i[3] || i[4]) {
          c += a;
          continue;
        } else if ((i[5] || i[6]) && s % 3 && !((s + a) % 3)) {
          d += a;
          continue;
        }
        if (c -= a, c > 0)
          continue;
        a = Math.min(a, a + c + d);
        const h = [...i[0]][0].length, f = e.slice(0, s + i.index + h + a);
        if (Math.min(s, a) % 2) {
          const m = f.slice(1, -1);
          return {
            type: "em",
            raw: f,
            text: m,
            tokens: this.lexer.inlineTokens(m)
          };
        }
        const p = f.slice(2, -2);
        return {
          type: "strong",
          raw: f,
          text: p,
          tokens: this.lexer.inlineTokens(p)
        };
      }
    }
  }
  codespan(e) {
    const t = this.rules.inline.code.exec(e);
    if (t) {
      let r = t[2].replace(/\n/g, " ");
      const i = /[^ ]/.test(r), o = /^ /.test(r) && / $/.test(r);
      return i && o && (r = r.substring(1, r.length - 1)), r = Et(r, !0), {
        type: "codespan",
        raw: t[0],
        text: r
      };
    }
  }
  br(e) {
    const t = this.rules.inline.br.exec(e);
    if (t)
      return {
        type: "br",
        raw: t[0]
      };
  }
  del(e) {
    const t = this.rules.inline.del.exec(e);
    if (t)
      return {
        type: "del",
        raw: t[0],
        text: t[2],
        tokens: this.lexer.inlineTokens(t[2])
      };
  }
  autolink(e) {
    const t = this.rules.inline.autolink.exec(e);
    if (t) {
      let r, i;
      return t[2] === "@" ? (r = Et(t[1]), i = "mailto:" + r) : (r = Et(t[1]), i = r), {
        type: "link",
        raw: t[0],
        text: r,
        href: i,
        tokens: [
          {
            type: "text",
            raw: r,
            text: r
          }
        ]
      };
    }
  }
  url(e) {
    var r;
    let t;
    if (t = this.rules.inline.url.exec(e)) {
      let i, o;
      if (t[2] === "@")
        i = Et(t[0]), o = "mailto:" + i;
      else {
        let s;
        do
          s = t[0], t[0] = ((r = this.rules.inline._backpedal.exec(t[0])) == null ? void 0 : r[0]) ?? "";
        while (s !== t[0]);
        i = Et(t[0]), t[1] === "www." ? o = "http://" + t[0] : o = t[0];
      }
      return {
        type: "link",
        raw: t[0],
        text: i,
        href: o,
        tokens: [
          {
            type: "text",
            raw: i,
            text: i
          }
        ]
      };
    }
  }
  inlineText(e) {
    const t = this.rules.inline.text.exec(e);
    if (t) {
      let r;
      return this.lexer.state.inRawBlock ? r = t[0] : r = Et(t[0]), {
        type: "text",
        raw: t[0],
        text: r
      };
    }
  }
}
const pv = /^(?: *(?:\n|$))+/, mv = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/, gv = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/, Rs = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/, bv = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, Sb = /(?:[*+-]|\d{1,9}[.)])/, Eb = ae(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, Sb).replace(/blockCode/g, / {4}/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).getRegex(), vh = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/, yv = /^[^\n]+/, Ch = /(?!\s*\])(?:\\.|[^\[\]\\])+/, _v = ae(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label", Ch).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(), wv = ae(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, Sb).getRegex(), dc = "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|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul", Sh = /<!--(?:-?>|[\s\S]*?(?:-->|$))/, kv = ae("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))", "i").replace("comment", Sh).replace("tag", dc).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(), xb = ae(vh).replace("hr", Rs).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", dc).getRegex(), vv = ae(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", xb).getRegex(), Eh = {
  blockquote: vv,
  code: mv,
  def: _v,
  fences: gv,
  heading: bv,
  hr: Rs,
  html: kv,
  lheading: Eb,
  list: wv,
  newline: pv,
  paragraph: xb,
  table: Wo,
  text: yv
}, Fp = ae("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", Rs).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", dc).getRegex(), Cv = {
  ...Eh,
  table: Fp,
  paragraph: ae(vh).replace("hr", Rs).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", Fp).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", dc).getRegex()
}, Sv = {
  ...Eh,
  html: ae(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", Sh).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
  heading: /^(#{1,6})(.*)(?:\n+|$)/,
  fences: Wo,
  // fences not supported
  lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  paragraph: ae(vh).replace("hr", Rs).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", Eb).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
}, Db = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, Ev = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, Ab = /^( {2,}|\\)\n(?!\s*$)/, xv = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/, Bs = "\\p{P}\\p{S}", Dv = ae(/^((?![*_])[\spunctuation])/, "u").replace(/punctuation/g, Bs).getRegex(), Av = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g, Tv = ae(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, "u").replace(/punct/g, Bs).getRegex(), Mv = ae("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])", "gu").replace(/punct/g, Bs).getRegex(), Ov = ae("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])", "gu").replace(/punct/g, Bs).getRegex(), Fv = ae(/\\([punct])/, "gu").replace(/punct/g, Bs).getRegex(), Nv = ae(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(), $v = ae(Sh).replace("(?:-->|$)", "-->").getRegex(), Iv = ae("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", $v).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(), aa = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/, Lv = ae(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label", aa).replace("href", /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(), Tb = ae(/^!?\[(label)\]\[(ref)\]/).replace("label", aa).replace("ref", Ch).getRegex(), Mb = ae(/^!?\[(ref)\](?:\[\])?/).replace("ref", Ch).getRegex(), Rv = ae("reflink|nolink(?!\\()", "g").replace("reflink", Tb).replace("nolink", Mb).getRegex(), xh = {
  _backpedal: Wo,
  // only used for GFM url
  anyPunctuation: Fv,
  autolink: Nv,
  blockSkip: Av,
  br: Ab,
  code: Ev,
  del: Wo,
  emStrongLDelim: Tv,
  emStrongRDelimAst: Mv,
  emStrongRDelimUnd: Ov,
  escape: Db,
  link: Lv,
  nolink: Mb,
  punctuation: Dv,
  reflink: Tb,
  reflinkSearch: Rv,
  tag: Iv,
  text: xv,
  url: Wo
}, Bv = {
  ...xh,
  link: ae(/^!?\[(label)\]\((.*?)\)/).replace("label", aa).getRegex(),
  reflink: ae(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", aa).getRegex()
}, ru = {
  ...xh,
  escape: ae(Db).replace("])", "~|])").getRegex(),
  url: ae(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
  _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
  del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
  text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
}, Pv = {
  ...ru,
  br: ae(Ab).replace("{2,}", "*").getRegex(),
  text: ae(ru.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
}, ol = {
  normal: Eh,
  gfm: Cv,
  pedantic: Sv
}, Do = {
  normal: xh,
  gfm: ru,
  breaks: Pv,
  pedantic: Bv
};
class Sn {
  constructor(e) {
    pe(this, "tokens");
    pe(this, "options");
    pe(this, "state");
    pe(this, "tokenizer");
    pe(this, "inlineQueue");
    this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e || Si, this.options.tokenizer = this.options.tokenizer || new la(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = {
      inLink: !1,
      inRawBlock: !1,
      top: !0
    };
    const t = {
      block: ol.normal,
      inline: Do.normal
    };
    this.options.pedantic ? (t.block = ol.pedantic, t.inline = Do.pedantic) : this.options.gfm && (t.block = ol.gfm, this.options.breaks ? t.inline = Do.breaks : t.inline = Do.gfm), this.tokenizer.rules = t;
  }
  /**
   * Expose Rules
   */
  static get rules() {
    return {
      block: ol,
      inline: Do
    };
  }
  /**
   * Static Lex Method
   */
  static lex(e, t) {
    return new Sn(t).lex(e);
  }
  /**
   * Static Lex Inline Method
   */
  static lexInline(e, t) {
    return new Sn(t).inlineTokens(e);
  }
  /**
   * Preprocessing
   */
  lex(e) {
    e = e.replace(/\r\n|\r/g, `
`), this.blockTokens(e, this.tokens);
    for (let t = 0; t < this.inlineQueue.length; t++) {
      const r = this.inlineQueue[t];
      this.inlineTokens(r.src, r.tokens);
    }
    return this.inlineQueue = [], this.tokens;
  }
  blockTokens(e, t = []) {
    this.options.pedantic ? e = e.replace(/\t/g, "    ").replace(/^ +$/gm, "") : e = e.replace(/^( *)(\t+)/gm, (l, a, c) => a + "    ".repeat(c.length));
    let r, i, o, s;
    for (; e; )
      if (!(this.options.extensions && this.options.extensions.block && this.options.extensions.block.some((l) => (r = l.call({ lexer: this }, e, t)) ? (e = e.substring(r.raw.length), t.push(r), !0) : !1))) {
        if (r = this.tokenizer.space(e)) {
          e = e.substring(r.raw.length), r.raw.length === 1 && t.length > 0 ? t[t.length - 1].raw += `
` : t.push(r);
          continue;
        }
        if (r = this.tokenizer.code(e)) {
          e = e.substring(r.raw.length), i = t[t.length - 1], i && (i.type === "paragraph" || i.type === "text") ? (i.raw += `
` + r.raw, i.text += `
` + r.text, this.inlineQueue[this.inlineQueue.length - 1].src = i.text) : t.push(r);
          continue;
        }
        if (r = this.tokenizer.fences(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.heading(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.hr(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.blockquote(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.list(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.html(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.def(e)) {
          e = e.substring(r.raw.length), i = t[t.length - 1], i && (i.type === "paragraph" || i.type === "text") ? (i.raw += `
` + r.raw, i.text += `
` + r.raw, this.inlineQueue[this.inlineQueue.length - 1].src = i.text) : this.tokens.links[r.tag] || (this.tokens.links[r.tag] = {
            href: r.href,
            title: r.title
          });
          continue;
        }
        if (r = this.tokenizer.table(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.lheading(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (o = e, this.options.extensions && this.options.extensions.startBlock) {
          let l = 1 / 0;
          const a = e.slice(1);
          let c;
          this.options.extensions.startBlock.forEach((d) => {
            c = d.call({ lexer: this }, a), typeof c == "number" && c >= 0 && (l = Math.min(l, c));
          }), l < 1 / 0 && l >= 0 && (o = e.substring(0, l + 1));
        }
        if (this.state.top && (r = this.tokenizer.paragraph(o))) {
          i = t[t.length - 1], s && i.type === "paragraph" ? (i.raw += `
` + r.raw, i.text += `
` + r.text, this.inlineQueue.pop(), this.inlineQueue[this.inlineQueue.length - 1].src = i.text) : t.push(r), s = o.length !== e.length, e = e.substring(r.raw.length);
          continue;
        }
        if (r = this.tokenizer.text(e)) {
          e = e.substring(r.raw.length), i = t[t.length - 1], i && i.type === "text" ? (i.raw += `
` + r.raw, i.text += `
` + r.text, this.inlineQueue.pop(), this.inlineQueue[this.inlineQueue.length - 1].src = i.text) : t.push(r);
          continue;
        }
        if (e) {
          const l = "Infinite loop on byte: " + e.charCodeAt(0);
          if (this.options.silent) {
            console.error(l);
            break;
          } else
            throw new Error(l);
        }
      }
    return this.state.top = !0, t;
  }
  inline(e, t = []) {
    return this.inlineQueue.push({ src: e, tokens: t }), t;
  }
  /**
   * Lexing/Compiling
   */
  inlineTokens(e, t = []) {
    let r, i, o, s = e, l, a, c;
    if (this.tokens.links) {
      const d = Object.keys(this.tokens.links);
      if (d.length > 0)
        for (; (l = this.tokenizer.rules.inline.reflinkSearch.exec(s)) != null; )
          d.includes(l[0].slice(l[0].lastIndexOf("[") + 1, -1)) && (s = s.slice(0, l.index) + "[" + "a".repeat(l[0].length - 2) + "]" + s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
    }
    for (; (l = this.tokenizer.rules.inline.blockSkip.exec(s)) != null; )
      s = s.slice(0, l.index) + "[" + "a".repeat(l[0].length - 2) + "]" + s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    for (; (l = this.tokenizer.rules.inline.anyPunctuation.exec(s)) != null; )
      s = s.slice(0, l.index) + "++" + s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    for (; e; )
      if (a || (c = ""), a = !1, !(this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some((d) => (r = d.call({ lexer: this }, e, t)) ? (e = e.substring(r.raw.length), t.push(r), !0) : !1))) {
        if (r = this.tokenizer.escape(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.tag(e)) {
          e = e.substring(r.raw.length), i = t[t.length - 1], i && r.type === "text" && i.type === "text" ? (i.raw += r.raw, i.text += r.text) : t.push(r);
          continue;
        }
        if (r = this.tokenizer.link(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.reflink(e, this.tokens.links)) {
          e = e.substring(r.raw.length), i = t[t.length - 1], i && r.type === "text" && i.type === "text" ? (i.raw += r.raw, i.text += r.text) : t.push(r);
          continue;
        }
        if (r = this.tokenizer.emStrong(e, s, c)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.codespan(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.br(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.del(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (r = this.tokenizer.autolink(e)) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (!this.state.inLink && (r = this.tokenizer.url(e))) {
          e = e.substring(r.raw.length), t.push(r);
          continue;
        }
        if (o = e, this.options.extensions && this.options.extensions.startInline) {
          let d = 1 / 0;
          const u = e.slice(1);
          let h;
          this.options.extensions.startInline.forEach((f) => {
            h = f.call({ lexer: this }, u), typeof h == "number" && h >= 0 && (d = Math.min(d, h));
          }), d < 1 / 0 && d >= 0 && (o = e.substring(0, d + 1));
        }
        if (r = this.tokenizer.inlineText(o)) {
          e = e.substring(r.raw.length), r.raw.slice(-1) !== "_" && (c = r.raw.slice(-1)), a = !0, i = t[t.length - 1], i && i.type === "text" ? (i.raw += r.raw, i.text += r.text) : t.push(r);
          continue;
        }
        if (e) {
          const d = "Infinite loop on byte: " + e.charCodeAt(0);
          if (this.options.silent) {
            console.error(d);
            break;
          } else
            throw new Error(d);
        }
      }
    return t;
  }
}
class ca {
  constructor(e) {
    pe(this, "options");
    this.options = e || Si;
  }
  code(e, t, r) {
    var o;
    const i = (o = (t || "").match(/^\S*/)) == null ? void 0 : o[0];
    return e = e.replace(/\n$/, "") + `
`, i ? '<pre><code class="language-' + Et(i) + '">' + (r ? e : Et(e, !0)) + `</code></pre>
` : "<pre><code>" + (r ? e : Et(e, !0)) + `</code></pre>
`;
  }
  blockquote(e) {
    return `<blockquote>
${e}</blockquote>
`;
  }
  html(e, t) {
    return e;
  }
  heading(e, t, r) {
    return `<h${t}>${e}</h${t}>
`;
  }
  hr() {
    return `<hr>
`;
  }
  list(e, t, r) {
    const i = t ? "ol" : "ul", o = t && r !== 1 ? ' start="' + r + '"' : "";
    return "<" + i + o + `>
` + e + "</" + i + `>
`;
  }
  listitem(e, t, r) {
    return `<li>${e}</li>
`;
  }
  checkbox(e) {
    return "<input " + (e ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
  }
  paragraph(e) {
    return `<p>${e}</p>
`;
  }
  table(e, t) {
    return t && (t = `<tbody>${t}</tbody>`), `<table>
<thead>
` + e + `</thead>
` + t + `</table>
`;
  }
  tablerow(e) {
    return `<tr>
${e}</tr>
`;
  }
  tablecell(e, t) {
    const r = t.header ? "th" : "td";
    return (t.align ? `<${r} align="${t.align}">` : `<${r}>`) + e + `</${r}>
`;
  }
  /**
   * span level renderer
   */
  strong(e) {
    return `<strong>${e}</strong>`;
  }
  em(e) {
    return `<em>${e}</em>`;
  }
  codespan(e) {
    return `<code>${e}</code>`;
  }
  br() {
    return "<br>";
  }
  del(e) {
    return `<del>${e}</del>`;
  }
  link(e, t, r) {
    const i = Tp(e);
    if (i === null)
      return r;
    e = i;
    let o = '<a href="' + e + '"';
    return t && (o += ' title="' + t + '"'), o += ">" + r + "</a>", o;
  }
  image(e, t, r) {
    const i = Tp(e);
    if (i === null)
      return r;
    e = i;
    let o = `<img src="${e}" alt="${r}"`;
    return t && (o += ` title="${t}"`), o += ">", o;
  }
  text(e) {
    return e;
  }
}
class Dh {
  // no need for block level renderers
  strong(e) {
    return e;
  }
  em(e) {
    return e;
  }
  codespan(e) {
    return e;
  }
  del(e) {
    return e;
  }
  html(e) {
    return e;
  }
  text(e) {
    return e;
  }
  link(e, t, r) {
    return "" + r;
  }
  image(e, t, r) {
    return "" + r;
  }
  br() {
    return "";
  }
}
class En {
  constructor(e) {
    pe(this, "options");
    pe(this, "renderer");
    pe(this, "textRenderer");
    this.options = e || Si, this.options.renderer = this.options.renderer || new ca(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.textRenderer = new Dh();
  }
  /**
   * Static Parse Method
   */
  static parse(e, t) {
    return new En(t).parse(e);
  }
  /**
   * Static Parse Inline Method
   */
  static parseInline(e, t) {
    return new En(t).parseInline(e);
  }
  /**
   * Parse Loop
   */
  parse(e, t = !0) {
    let r = "";
    for (let i = 0; i < e.length; i++) {
      const o = e[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[o.type]) {
        const s = o, l = this.options.extensions.renderers[s.type].call({ parser: this }, s);
        if (l !== !1 || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(s.type)) {
          r += l || "";
          continue;
        }
      }
      switch (o.type) {
        case "space":
          continue;
        case "hr": {
          r += this.renderer.hr();
          continue;
        }
        case "heading": {
          const s = o;
          r += this.renderer.heading(this.parseInline(s.tokens), s.depth, dv(this.parseInline(s.tokens, this.textRenderer)));
          continue;
        }
        case "code": {
          const s = o;
          r += this.renderer.code(s.text, s.lang, !!s.escaped);
          continue;
        }
        case "table": {
          const s = o;
          let l = "", a = "";
          for (let d = 0; d < s.header.length; d++)
            a += this.renderer.tablecell(this.parseInline(s.header[d].tokens), { header: !0, align: s.align[d] });
          l += this.renderer.tablerow(a);
          let c = "";
          for (let d = 0; d < s.rows.length; d++) {
            const u = s.rows[d];
            a = "";
            for (let h = 0; h < u.length; h++)
              a += this.renderer.tablecell(this.parseInline(u[h].tokens), { header: !1, align: s.align[h] });
            c += this.renderer.tablerow(a);
          }
          r += this.renderer.table(l, c);
          continue;
        }
        case "blockquote": {
          const s = o, l = this.parse(s.tokens);
          r += this.renderer.blockquote(l);
          continue;
        }
        case "list": {
          const s = o, l = s.ordered, a = s.start, c = s.loose;
          let d = "";
          for (let u = 0; u < s.items.length; u++) {
            const h = s.items[u], f = h.checked, p = h.task;
            let m = "";
            if (h.task) {
              const g = this.renderer.checkbox(!!f);
              c ? h.tokens.length > 0 && h.tokens[0].type === "paragraph" ? (h.tokens[0].text = g + " " + h.tokens[0].text, h.tokens[0].tokens && h.tokens[0].tokens.length > 0 && h.tokens[0].tokens[0].type === "text" && (h.tokens[0].tokens[0].text = g + " " + h.tokens[0].tokens[0].text)) : h.tokens.unshift({
                type: "text",
                text: g + " "
              }) : m += g + " ";
            }
            m += this.parse(h.tokens, c), d += this.renderer.listitem(m, p, !!f);
          }
          r += this.renderer.list(d, l, a);
          continue;
        }
        case "html": {
          const s = o;
          r += this.renderer.html(s.text, s.block);
          continue;
        }
        case "paragraph": {
          const s = o;
          r += this.renderer.paragraph(this.parseInline(s.tokens));
          continue;
        }
        case "text": {
          let s = o, l = s.tokens ? this.parseInline(s.tokens) : s.text;
          for (; i + 1 < e.length && e[i + 1].type === "text"; )
            s = e[++i], l += `
` + (s.tokens ? this.parseInline(s.tokens) : s.text);
          r += t ? this.renderer.paragraph(l) : l;
          continue;
        }
        default: {
          const s = 'Token with "' + o.type + '" type was not found.';
          if (this.options.silent)
            return console.error(s), "";
          throw new Error(s);
        }
      }
    }
    return r;
  }
  /**
   * Parse Inline Tokens
   */
  parseInline(e, t) {
    t = t || this.renderer;
    let r = "";
    for (let i = 0; i < e.length; i++) {
      const o = e[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[o.type]) {
        const s = this.options.extensions.renderers[o.type].call({ parser: this }, o);
        if (s !== !1 || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(o.type)) {
          r += s || "";
          continue;
        }
      }
      switch (o.type) {
        case "escape": {
          const s = o;
          r += t.text(s.text);
          break;
        }
        case "html": {
          const s = o;
          r += t.html(s.text);
          break;
        }
        case "link": {
          const s = o;
          r += t.link(s.href, s.title, this.parseInline(s.tokens, t));
          break;
        }
        case "image": {
          const s = o;
          r += t.image(s.href, s.title, s.text);
          break;
        }
        case "strong": {
          const s = o;
          r += t.strong(this.parseInline(s.tokens, t));
          break;
        }
        case "em": {
          const s = o;
          r += t.em(this.parseInline(s.tokens, t));
          break;
        }
        case "codespan": {
          const s = o;
          r += t.codespan(s.text);
          break;
        }
        case "br": {
          r += t.br();
          break;
        }
        case "del": {
          const s = o;
          r += t.del(this.parseInline(s.tokens, t));
          break;
        }
        case "text": {
          const s = o;
          r += t.text(s.text);
          break;
        }
        default: {
          const s = 'Token with "' + o.type + '" type was not found.';
          if (this.options.silent)
            return console.error(s), "";
          throw new Error(s);
        }
      }
    }
    return r;
  }
}
class Go {
  constructor(e) {
    pe(this, "options");
    this.options = e || Si;
  }
  /**
   * Process markdown before marked
   */
  preprocess(e) {
    return e;
  }
  /**
   * Process HTML after marked is finished
   */
  postprocess(e) {
    return e;
  }
  /**
   * Process all tokens before walk tokens
   */
  processAllTokens(e) {
    return e;
  }
}
pe(Go, "passThroughHooks", /* @__PURE__ */ new Set([
  "preprocess",
  "postprocess",
  "processAllTokens"
]));
var Ci, iu, Fb;
class Ob {
  constructor(...e) {
    Cp(this, Ci);
    pe(this, "defaults", kh());
    pe(this, "options", this.setOptions);
    pe(this, "parse", rl(this, Ci, iu).call(this, Sn.lex, En.parse));
    pe(this, "parseInline", rl(this, Ci, iu).call(this, Sn.lexInline, En.parseInline));
    pe(this, "Parser", En);
    pe(this, "Renderer", ca);
    pe(this, "TextRenderer", Dh);
    pe(this, "Lexer", Sn);
    pe(this, "Tokenizer", la);
    pe(this, "Hooks", Go);
    this.use(...e);
  }
  /**
   * Run callback for every token
   */
  walkTokens(e, t) {
    var i, o;
    let r = [];
    for (const s of e)
      switch (r = r.concat(t.call(this, s)), s.type) {
        case "table": {
          const l = s;
          for (const a of l.header)
            r = r.concat(this.walkTokens(a.tokens, t));
          for (const a of l.rows)
            for (const c of a)
              r = r.concat(this.walkTokens(c.tokens, t));
          break;
        }
        case "list": {
          const l = s;
          r = r.concat(this.walkTokens(l.items, t));
          break;
        }
        default: {
          const l = s;
          (o = (i = this.defaults.extensions) == null ? void 0 : i.childTokens) != null && o[l.type] ? this.defaults.extensions.childTokens[l.type].forEach((a) => {
            const c = l[a].flat(1 / 0);
            r = r.concat(this.walkTokens(c, t));
          }) : l.tokens && (r = r.concat(this.walkTokens(l.tokens, t)));
        }
      }
    return r;
  }
  use(...e) {
    const t = this.defaults.extensions || { renderers: {}, childTokens: {} };
    return e.forEach((r) => {
      const i = { ...r };
      if (i.async = this.defaults.async || i.async || !1, r.extensions && (r.extensions.forEach((o) => {
        if (!o.name)
          throw new Error("extension name required");
        if ("renderer" in o) {
          const s = t.renderers[o.name];
          s ? t.renderers[o.name] = function(...l) {
            let a = o.renderer.apply(this, l);
            return a === !1 && (a = s.apply(this, l)), a;
          } : t.renderers[o.name] = o.renderer;
        }
        if ("tokenizer" in o) {
          if (!o.level || o.level !== "block" && o.level !== "inline")
            throw new Error("extension level must be 'block' or 'inline'");
          const s = t[o.level];
          s ? s.unshift(o.tokenizer) : t[o.level] = [o.tokenizer], o.start && (o.level === "block" ? t.startBlock ? t.startBlock.push(o.start) : t.startBlock = [o.start] : o.level === "inline" && (t.startInline ? t.startInline.push(o.start) : t.startInline = [o.start]));
        }
        "childTokens" in o && o.childTokens && (t.childTokens[o.name] = o.childTokens);
      }), i.extensions = t), r.renderer) {
        const o = this.defaults.renderer || new ca(this.defaults);
        for (const s in r.renderer) {
          if (!(s in o))
            throw new Error(`renderer '${s}' does not exist`);
          if (s === "options")
            continue;
          const l = s, a = r.renderer[l], c = o[l];
          o[l] = (...d) => {
            let u = a.apply(o, d);
            return u === !1 && (u = c.apply(o, d)), u || "";
          };
        }
        i.renderer = o;
      }
      if (r.tokenizer) {
        const o = this.defaults.tokenizer || new la(this.defaults);
        for (const s in r.tokenizer) {
          if (!(s in o))
            throw new Error(`tokenizer '${s}' does not exist`);
          if (["options", "rules", "lexer"].includes(s))
            continue;
          const l = s, a = r.tokenizer[l], c = o[l];
          o[l] = (...d) => {
            let u = a.apply(o, d);
            return u === !1 && (u = c.apply(o, d)), u;
          };
        }
        i.tokenizer = o;
      }
      if (r.hooks) {
        const o = this.defaults.hooks || new Go();
        for (const s in r.hooks) {
          if (!(s in o))
            throw new Error(`hook '${s}' does not exist`);
          if (s === "options")
            continue;
          const l = s, a = r.hooks[l], c = o[l];
          Go.passThroughHooks.has(s) ? o[l] = (d) => {
            if (this.defaults.async)
              return Promise.resolve(a.call(o, d)).then((h) => c.call(o, h));
            const u = a.call(o, d);
            return c.call(o, u);
          } : o[l] = (...d) => {
            let u = a.apply(o, d);
            return u === !1 && (u = c.apply(o, d)), u;
          };
        }
        i.hooks = o;
      }
      if (r.walkTokens) {
        const o = this.defaults.walkTokens, s = r.walkTokens;
        i.walkTokens = function(l) {
          let a = [];
          return a.push(s.call(this, l)), o && (a = a.concat(o.call(this, l))), a;
        };
      }
      this.defaults = { ...this.defaults, ...i };
    }), this;
  }
  setOptions(e) {
    return this.defaults = { ...this.defaults, ...e }, this;
  }
  lexer(e, t) {
    return Sn.lex(e, t ?? this.defaults);
  }
  parser(e, t) {
    return En.parse(e, t ?? this.defaults);
  }
}
Ci = new WeakSet(), iu = function(e, t) {
  return (r, i) => {
    const o = { ...i }, s = { ...this.defaults, ...o };
    this.defaults.async === !0 && o.async === !1 && (s.silent || console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."), s.async = !0);
    const l = rl(this, Ci, Fb).call(this, !!s.silent, !!s.async);
    if (typeof r > "u" || r === null)
      return l(new Error("marked(): input parameter is undefined or null"));
    if (typeof r != "string")
      return l(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(r) + ", string expected"));
    if (s.hooks && (s.hooks.options = s), s.async)
      return Promise.resolve(s.hooks ? s.hooks.preprocess(r) : r).then((a) => e(a, s)).then((a) => s.hooks ? s.hooks.processAllTokens(a) : a).then((a) => s.walkTokens ? Promise.all(this.walkTokens(a, s.walkTokens)).then(() => a) : a).then((a) => t(a, s)).then((a) => s.hooks ? s.hooks.postprocess(a) : a).catch(l);
    try {
      s.hooks && (r = s.hooks.preprocess(r));
      let a = e(r, s);
      s.hooks && (a = s.hooks.processAllTokens(a)), s.walkTokens && this.walkTokens(a, s.walkTokens);
      let c = t(a, s);
      return s.hooks && (c = s.hooks.postprocess(c)), c;
    } catch (a) {
      return l(a);
    }
  };
}, Fb = function(e, t) {
  return (r) => {
    if (r.message += `
Please report this to https://github.com/markedjs/marked.`, e) {
      const i = "<p>An error occurred:</p><pre>" + Et(r.message + "", !0) + "</pre>";
      return t ? Promise.resolve(i) : i;
    }
    if (t)
      return Promise.reject(r);
    throw r;
  };
};
const ui = new Ob();
function oe(n, e) {
  return ui.parse(n, e);
}
oe.options = oe.setOptions = function(n) {
  return ui.setOptions(n), oe.defaults = ui.defaults, kb(oe.defaults), oe;
};
oe.getDefaults = kh;
oe.defaults = Si;
oe.use = function(...n) {
  return ui.use(...n), oe.defaults = ui.defaults, kb(oe.defaults), oe;
};
oe.walkTokens = function(n, e) {
  return ui.walkTokens(n, e);
};
oe.parseInline = ui.parseInline;
oe.Parser = En;
oe.parser = En.parse;
oe.Renderer = ca;
oe.TextRenderer = Dh;
oe.Lexer = Sn;
oe.lexer = Sn.lex;
oe.Tokenizer = la;
oe.Hooks = Go;
oe.parse = oe;
oe.options;
oe.setOptions;
oe.use;
oe.walkTokens;
oe.parseInline;
En.parse;
Sn.lex;
function zv(n) {
  if (typeof n == "function" && (n = {
    highlight: n
  }), !n || typeof n.highlight != "function")
    throw new Error("Must provide highlight function");
  return typeof n.langPrefix != "string" && (n.langPrefix = "language-"), typeof n.emptyLangClass != "string" && (n.emptyLangClass = ""), {
    async: !!n.async,
    walkTokens(e) {
      if (e.type !== "code")
        return;
      const t = Np(e.lang);
      if (n.async)
        return Promise.resolve(n.highlight(e.text, t, e.lang || "")).then($p(e));
      const r = n.highlight(e.text, t, e.lang || "");
      if (r instanceof Promise)
        throw new Error("markedHighlight is not set to async but the highlight function is async. Set the async option to true on markedHighlight to await the async highlight function.");
      $p(e)(r);
    },
    useNewRenderer: !0,
    renderer: {
      code(e, t, r) {
        typeof e == "object" && (r = e.escaped, t = e.lang, e = e.text);
        const i = Np(t), o = i ? n.langPrefix + Lp(i) : n.emptyLangClass, s = o ? ` class="${o}"` : "";
        return e = e.replace(/\n$/, ""), `<pre><code${s}>${r ? e : Lp(e, !0)}
</code></pre>`;
      }
    }
  };
}
function Np(n) {
  return (n || "").match(/\S*/)[0];
}
function $p(n) {
  return (e) => {
    typeof e == "string" && e !== n.text && (n.escaped = !0, n.text = e);
  };
}
const Nb = /[&<>"']/, Hv = new RegExp(Nb.source, "g"), $b = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, Vv = new RegExp($b.source, "g"), Uv = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
}, Ip = (n) => Uv[n];
function Lp(n, e) {
  if (e) {
    if (Nb.test(n))
      return n.replace(Hv, Ip);
  } else if ($b.test(n))
    return n.replace(Vv, Ip);
  return n;
}
const qv = /[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uDE7D-\uDE7F\uDE9D-\uDEBF\uDEC8\uDEE7-\uDEFF\uDF36-\uDF3F\uDF56-\uDF5F\uDF73-\uDF7F\uDF92-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCFF\uDD28-\uDD2F\uDD3A-\uDE7F\uDEAA\uDEAD-\uDEAF\uDEB2-\uDEFF\uDF1D-\uDF26\uDF28-\uDF2F\uDF51-\uDFAF\uDFC5-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC47-\uDC65\uDC70-\uDC7E\uDCBB-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD40-\uDD43\uDD48-\uDD4F\uDD74\uDD75\uDD77-\uDD7F\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDFF\uDE12\uDE38-\uDE3D\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC4B-\uDC4F\uDC5A-\uDC5D\uDC62-\uDC7F\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDC1-\uDDD7\uDDDE-\uDDFF\uDE41-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEB9-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF3A-\uDFFF]|\uD806[\uDC3B-\uDC9F\uDCEA-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD44-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE2\uDDE5-\uDDFF\uDE3F-\uDE46\uDE48-\uDE4F\uDE9A-\uDE9C\uDE9E-\uDEBF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC41-\uDC4F\uDC5A-\uDC71\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF7-\uDFAF\uDFB1-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80B\uD80E-\uD810\uD812-\uD819\uD824-\uD82B\uD82D\uD82E\uD830-\uD833\uD837\uD839\uD83D\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDECF\uDEEE\uDEEF\uDEF5-\uDEFF\uDF37-\uDF3F\uDF44-\uDF4F\uDF5A-\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE80-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE2\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82C[\uDD1F-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDC9C\uDC9F-\uDFFF]|\uD834[\uDC00-\uDD64\uDD6A-\uDD6C\uDD73-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDE41\uDE45-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g, jv = Object.hasOwnProperty;
class Ah {
  /**
   * Create a new slug class.
   */
  constructor() {
    this.occurrences, this.reset();
  }
  /**
   * Generate a unique slug.
  *
  * Tracks previously generated slugs: repeated calls with the same value
  * will result in different slugs.
  * Use the `slug` function to get same slugs.
   *
   * @param  {string} value
   *   String of text to slugify
   * @param  {boolean} [maintainCase=false]
   *   Keep the current case, otherwise make all lowercase
   * @return {string}
   *   A unique slug string
   */
  slug(e, t) {
    const r = this;
    let i = Wv(e, t === !0);
    const o = i;
    for (; jv.call(r.occurrences, i); )
      r.occurrences[o]++, i = o + "-" + r.occurrences[o];
    return r.occurrences[i] = 0, i;
  }
  /**
   * Reset - Forget all previous slugs
   *
   * @return void
   */
  reset() {
    this.occurrences = /* @__PURE__ */ Object.create(null);
  }
}
function Wv(n, e) {
  return typeof n != "string" ? "" : (e || (n = n.toLowerCase()), n.replace(qv, "").replace(/ /g, "-"));
}
let Ib = new Ah(), Lb = [];
function Gv({ prefix: n = "", globalSlugs: e = !1 } = {}) {
  return {
    headerIds: !1,
    // prevent deprecation warning; remove this once headerIds option is removed
    hooks: {
      preprocess(t) {
        return e || Kv(), t;
      }
    },
    renderer: {
      heading(t, r, i) {
        i = i.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi, "");
        const o = `${n}${Ib.slug(i)}`, s = { level: r, text: t, id: o };
        return Lb.push(s), `<h${r} id="${o}">${t}</h${r}>
`;
      }
    }
  };
}
function Kv() {
  Lb = [], Ib = new Ah();
}
var Rp = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
function WP(n) {
  return n && n.__esModule && Object.prototype.hasOwnProperty.call(n, "default") ? n.default : n;
}
var Rb = { exports: {} };
(function(n) {
  var e = typeof window < "u" ? window : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? self : {};
  /**
   * Prism: Lightweight, robust, elegant syntax highlighting
   *
   * @license MIT <https://opensource.org/licenses/MIT>
   * @author Lea Verou <https://lea.verou.me>
   * @namespace
   * @public
   */
  var t = function(r) {
    var i = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i, o = 0, s = {}, l = {
      /**
       * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
       * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
       * additional languages or plugins yourself.
       *
       * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
       *
       * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
       * empty Prism object into the global scope before loading the Prism script like this:
       *
       * ```js
       * window.Prism = window.Prism || {};
       * Prism.manual = true;
       * // add a new <script> to load Prism's script
       * ```
       *
       * @default false
       * @type {boolean}
       * @memberof Prism
       * @public
       */
      manual: r.Prism && r.Prism.manual,
      /**
       * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
       * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
       * own worker, you don't want it to do this.
       *
       * By setting this value to `true`, Prism will not add its own listeners to the worker.
       *
       * You obviously have to change this value before Prism executes. To do this, you can add an
       * empty Prism object into the global scope before loading the Prism script like this:
       *
       * ```js
       * window.Prism = window.Prism || {};
       * Prism.disableWorkerMessageHandler = true;
       * // Load Prism's script
       * ```
       *
       * @default false
       * @type {boolean}
       * @memberof Prism
       * @public
       */
      disableWorkerMessageHandler: r.Prism && r.Prism.disableWorkerMessageHandler,
      /**
       * A namespace for utility methods.
       *
       * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
       * change or disappear at any time.
       *
       * @namespace
       * @memberof Prism
       */
      util: {
        encode: function _(b) {
          return b instanceof a ? new a(b.type, _(b.content), b.alias) : Array.isArray(b) ? b.map(_) : b.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\u00a0/g, " ");
        },
        /**
         * Returns the name of the type of the given value.
         *
         * @param {any} o
         * @returns {string}
         * @example
         * type(null)      === 'Null'
         * type(undefined) === 'Undefined'
         * type(123)       === 'Number'
         * type('foo')     === 'String'
         * type(true)      === 'Boolean'
         * type([1, 2])    === 'Array'
         * type({})        === 'Object'
         * type(String)    === 'Function'
         * type(/abc+/)    === 'RegExp'
         */
        type: function(_) {
          return Object.prototype.toString.call(_).slice(8, -1);
        },
        /**
         * Returns a unique number for the given object. Later calls will still return the same number.
         *
         * @param {Object} obj
         * @returns {number}
         */
        objId: function(_) {
          return _.__id || Object.defineProperty(_, "__id", { value: ++o }), _.__id;
        },
        /**
         * Creates a deep clone of the given object.
         *
         * The main intended use of this function is to clone language definitions.
         *
         * @param {T} o
         * @param {Record<number, any>} [visited]
         * @returns {T}
         * @template T
         */
        clone: function _(b, k) {
          k = k || {};
          var C, w;
          switch (l.util.type(b)) {
            case "Object":
              if (w = l.util.objId(b), k[w])
                return k[w];
              C = /** @type {Record<string, any>} */
              {}, k[w] = C;
              for (var x in b)
                b.hasOwnProperty(x) && (C[x] = _(b[x], k));
              return (
                /** @type {any} */
                C
              );
            case "Array":
              return w = l.util.objId(b), k[w] ? k[w] : (C = [], k[w] = C, /** @type {Array} */
              /** @type {any} */
              b.forEach(function(S, D) {
                C[D] = _(S, k);
              }), /** @type {any} */
              C);
            default:
              return b;
          }
        },
        /**
         * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
         *
         * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
         *
         * @param {Element} element
         * @returns {string}
         */
        getLanguage: function(_) {
          for (; _; ) {
            var b = i.exec(_.className);
            if (b)
              return b[1].toLowerCase();
            _ = _.parentElement;
          }
          return "none";
        },
        /**
         * Sets the Prism `language-xxxx` class of the given element.
         *
         * @param {Element} element
         * @param {string} language
         * @returns {void}
         */
        setLanguage: function(_, b) {
          _.className = _.className.replace(RegExp(i, "gi"), ""), _.classList.add("language-" + b);
        },
        /**
         * Returns the script element that is currently executing.
         *
         * This does __not__ work for line script element.
         *
         * @returns {HTMLScriptElement | null}
         */
        currentScript: function() {
          if (typeof document > "u")
            return null;
          if ("currentScript" in document)
            return (
              /** @type {any} */
              document.currentScript
            );
          try {
            throw new Error();
          } catch (C) {
            var _ = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(C.stack) || [])[1];
            if (_) {
              var b = document.getElementsByTagName("script");
              for (var k in b)
                if (b[k].src == _)
                  return b[k];
            }
            return null;
          }
        },
        /**
         * Returns whether a given class is active for `element`.
         *
         * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
         * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
         * given class is just the given class with a `no-` prefix.
         *
         * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
         * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
         * ancestors have the given class or the negated version of it, then the default activation will be returned.
         *
         * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
         * version of it, the class is considered active.
         *
         * @param {Element} element
         * @param {string} className
         * @param {boolean} [defaultActivation=false]
         * @returns {boolean}
         */
        isActive: function(_, b, k) {
          for (var C = "no-" + b; _; ) {
            var w = _.classList;
            if (w.contains(b))
              return !0;
            if (w.contains(C))
              return !1;
            _ = _.parentElement;
          }
          return !!k;
        }
      },
      /**
       * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
       *
       * @namespace
       * @memberof Prism
       * @public
       */
      languages: {
        /**
         * The grammar for plain, unformatted text.
         */
        plain: s,
        plaintext: s,
        text: s,
        txt: s,
        /**
         * Creates a deep copy of the language with the given id and appends the given tokens.
         *
         * If a token in `redef` also appears in the copied language, then the existing token in the copied language
         * will be overwritten at its original position.
         *
         * ## Best practices
         *
         * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
         * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
         * understand the language definition because, normally, the order of tokens matters in Prism grammars.
         *
         * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
         * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
         *
         * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
         * @param {Grammar} redef The new tokens to append.
         * @returns {Grammar} The new language created.
         * @public
         * @example
         * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
         *     // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
         *     // at its original position
         *     'comment': { ... },
         *     // CSS doesn't have a 'color' token, so this token will be appended
         *     'color': /\b(?:red|green|blue)\b/
         * });
         */
        extend: function(_, b) {
          var k = l.util.clone(l.languages[_]);
          for (var C in b)
            k[C] = b[C];
          return k;
        },
        /**
         * Inserts tokens _before_ another token in a language definition or any other grammar.
         *
         * ## Usage
         *
         * This helper method makes it easy to modify existing languages. For example, the CSS language definition
         * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
         * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
         * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
         * this:
         *
         * ```js
         * Prism.languages.markup.style = {
         *     // token
         * };
         * ```
         *
         * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
         * before existing tokens. For the CSS example above, you would use it like this:
         *
         * ```js
         * Prism.languages.insertBefore('markup', 'cdata', {
         *     'style': {
         *         // token
         *     }
         * });
         * ```
         *
         * ## Special cases
         *
         * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
         * will be ignored.
         *
         * This behavior can be used to insert tokens after `before`:
         *
         * ```js
         * Prism.languages.insertBefore('markup', 'comment', {
         *     'comment': Prism.languages.markup.comment,
         *     // tokens after 'comment'
         * });
         * ```
         *
         * ## Limitations
         *
         * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
         * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
         * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
         * deleting properties which is necessary to insert at arbitrary positions.
         *
         * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
         * Instead, it will create a new object and replace all references to the target object with the new one. This
         * can be done without temporarily deleting properties, so the iteration order is well-defined.
         *
         * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
         * you hold the target object in a variable, then the value of the variable will not change.
         *
         * ```js
         * var oldMarkup = Prism.languages.markup;
         * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
         *
         * assert(oldMarkup !== Prism.languages.markup);
         * assert(newMarkup === Prism.languages.markup);
         * ```
         *
         * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
         * object to be modified.
         * @param {string} before The key to insert before.
         * @param {Grammar} insert An object containing the key-value pairs to be inserted.
         * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
         * object to be modified.
         *
         * Defaults to `Prism.languages`.
         * @returns {Grammar} The new grammar object.
         * @public
         */
        insertBefore: function(_, b, k, C) {
          C = C || /** @type {any} */
          l.languages;
          var w = C[_], x = {};
          for (var S in w)
            if (w.hasOwnProperty(S)) {
              if (S == b)
                for (var D in k)
                  k.hasOwnProperty(D) && (x[D] = k[D]);
              k.hasOwnProperty(S) || (x[S] = w[S]);
            }
          var T = C[_];
          return C[_] = x, l.languages.DFS(l.languages, function(I, U) {
            U === T && I != _ && (this[I] = x);
          }), x;
        },
        // Traverse a language definition with Depth First Search
        DFS: function _(b, k, C, w) {
          w = w || {};
          var x = l.util.objId;
          for (var S in b)
            if (b.hasOwnProperty(S)) {
              k.call(b, S, b[S], C || S);
              var D = b[S], T = l.util.type(D);
              T === "Object" && !w[x(D)] ? (w[x(D)] = !0, _(D, k, null, w)) : T === "Array" && !w[x(D)] && (w[x(D)] = !0, _(D, k, S, w));
            }
        }
      },
      plugins: {},
      /**
       * This is the most high-level function in Prism’s API.
       * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
       * each one of them.
       *
       * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
       *
       * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
       * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
       * @memberof Prism
       * @public
       */
      highlightAll: function(_, b) {
        l.highlightAllUnder(document, _, b);
      },
      /**
       * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
       * {@link Prism.highlightElement} on each one of them.
       *
       * The following hooks will be run:
       * 1. `before-highlightall`
       * 2. `before-all-elements-highlight`
       * 3. All hooks of {@link Prism.highlightElement} for each element.
       *
       * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
       * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
       * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
       * @memberof Prism
       * @public
       */
      highlightAllUnder: function(_, b, k) {
        var C = {
          callback: k,
          container: _,
          selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
        };
        l.hooks.run("before-highlightall", C), C.elements = Array.prototype.slice.apply(C.container.querySelectorAll(C.selector)), l.hooks.run("before-all-elements-highlight", C);
        for (var w = 0, x; x = C.elements[w++]; )
          l.highlightElement(x, b === !0, C.callback);
      },
      /**
       * Highlights the code inside a single element.
       *
       * The following hooks will be run:
       * 1. `before-sanity-check`
       * 2. `before-highlight`
       * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
       * 4. `before-insert`
       * 5. `after-highlight`
       * 6. `complete`
       *
       * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
       * the element's language.
       *
       * @param {Element} element The element containing the code.
       * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
       * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
       * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
       * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
       *
       * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
       * asynchronous highlighting to work. You can build your own bundle on the
       * [Download page](https://prismjs.com/download.html).
       * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
       * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
       * @memberof Prism
       * @public
       */
      highlightElement: function(_, b, k) {
        var C = l.util.getLanguage(_), w = l.languages[C];
        l.util.setLanguage(_, C);
        var x = _.parentElement;
        x && x.nodeName.toLowerCase() === "pre" && l.util.setLanguage(x, C);
        var S = _.textContent, D = {
          element: _,
          language: C,
          grammar: w,
          code: S
        };
        function T(U) {
          D.highlightedCode = U, l.hooks.run("before-insert", D), D.element.innerHTML = D.highlightedCode, l.hooks.run("after-highlight", D), l.hooks.run("complete", D), k && k.call(D.element);
        }
        if (l.hooks.run("before-sanity-check", D), x = D.element.parentElement, x && x.nodeName.toLowerCase() === "pre" && !x.hasAttribute("tabindex") && x.setAttribute("tabindex", "0"), !D.code) {
          l.hooks.run("complete", D), k && k.call(D.element);
          return;
        }
        if (l.hooks.run("before-highlight", D), !D.grammar) {
          T(l.util.encode(D.code));
          return;
        }
        if (b && r.Worker) {
          var I = new Worker(l.filename);
          I.onmessage = function(U) {
            T(U.data);
          }, I.postMessage(JSON.stringify({
            language: D.language,
            code: D.code,
            immediateClose: !0
          }));
        } else
          T(l.highlight(D.code, D.grammar, D.language));
      },
      /**
       * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
       * and the language definitions to use, and returns a string with the HTML produced.
       *
       * The following hooks will be run:
       * 1. `before-tokenize`
       * 2. `after-tokenize`
       * 3. `wrap`: On each {@link Token}.
       *
       * @param {string} text A string with the code to be highlighted.
       * @param {Grammar} grammar An object containing the tokens to use.
       *
       * Usually a language definition like `Prism.languages.markup`.
       * @param {string} language The name of the language definition passed to `grammar`.
       * @returns {string} The highlighted HTML.
       * @memberof Prism
       * @public
       * @example
       * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
       */
      highlight: function(_, b, k) {
        var C = {
          code: _,
          grammar: b,
          language: k
        };
        if (l.hooks.run("before-tokenize", C), !C.grammar)
          throw new Error('The language "' + C.language + '" has no grammar.');
        return C.tokens = l.tokenize(C.code, C.grammar), l.hooks.run("after-tokenize", C), a.stringify(l.util.encode(C.tokens), C.language);
      },
      /**
       * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
       * and the language definitions to use, and returns an array with the tokenized code.
       *
       * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
       *
       * This method could be useful in other contexts as well, as a very crude parser.
       *
       * @param {string} text A string with the code to be highlighted.
       * @param {Grammar} grammar An object containing the tokens to use.
       *
       * Usually a language definition like `Prism.languages.markup`.
       * @returns {TokenStream} An array of strings and tokens, a token stream.
       * @memberof Prism
       * @public
       * @example
       * let code = `var foo = 0;`;
       * let tokens = Prism.tokenize(code, Prism.languages.javascript);
       * tokens.forEach(token => {
       *     if (token instanceof Prism.Token && token.type === 'number') {
       *         console.log(`Found numeric literal: ${token.content}`);
       *     }
       * });
       */
      tokenize: function(_, b) {
        var k = b.rest;
        if (k) {
          for (var C in k)
            b[C] = k[C];
          delete b.rest;
        }
        var w = new u();
        return h(w, w.head, _), d(_, w, b, w.head, 0), p(w);
      },
      /**
       * @namespace
       * @memberof Prism
       * @public
       */
      hooks: {
        all: {},
        /**
         * Adds the given callback to the list of callbacks for the given hook.
         *
         * The callback will be invoked when the hook it is registered for is run.
         * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
         *
         * One callback function can be registered to multiple hooks and the same hook multiple times.
         *
         * @param {string} name The name of the hook.
         * @param {HookCallback} callback The callback function which is given environment variables.
         * @public
         */
        add: function(_, b) {
          var k = l.hooks.all;
          k[_] = k[_] || [], k[_].push(b);
        },
        /**
         * Runs a hook invoking all registered callbacks with the given environment variables.
         *
         * Callbacks will be invoked synchronously and in the order in which they were registered.
         *
         * @param {string} name The name of the hook.
         * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
         * @public
         */
        run: function(_, b) {
          var k = l.hooks.all[_];
          if (!(!k || !k.length))
            for (var C = 0, w; w = k[C++]; )
              w(b);
        }
      },
      Token: a
    };
    r.Prism = l;
    function a(_, b, k, C) {
      this.type = _, this.content = b, this.alias = k, this.length = (C || "").length | 0;
    }
    a.stringify = function _(b, k) {
      if (typeof b == "string")
        return b;
      if (Array.isArray(b)) {
        var C = "";
        return b.forEach(function(T) {
          C += _(T, k);
        }), C;
      }
      var w = {
        type: b.type,
        content: _(b.content, k),
        tag: "span",
        classes: ["token", b.type],
        attributes: {},
        language: k
      }, x = b.alias;
      x && (Array.isArray(x) ? Array.prototype.push.apply(w.classes, x) : w.classes.push(x)), l.hooks.run("wrap", w);
      var S = "";
      for (var D in w.attributes)
        S += " " + D + '="' + (w.attributes[D] || "").replace(/"/g, "&quot;") + '"';
      return "<" + w.tag + ' class="' + w.classes.join(" ") + '"' + S + ">" + w.content + "</" + w.tag + ">";
    };
    function c(_, b, k, C) {
      _.lastIndex = b;
      var w = _.exec(k);
      if (w && C && w[1]) {
        var x = w[1].length;
        w.index += x, w[0] = w[0].slice(x);
      }
      return w;
    }
    function d(_, b, k, C, w, x) {
      for (var S in k)
        if (!(!k.hasOwnProperty(S) || !k[S])) {
          var D = k[S];
          D = Array.isArray(D) ? D : [D];
          for (var T = 0; T < D.length; ++T) {
            if (x && x.cause == S + "," + T)
              return;
            var I = D[T], U = I.inside, Te = !!I.lookbehind, ce = !!I.greedy, fe = I.alias;
            if (ce && !I.pattern.global) {
              var K = I.pattern.toString().match(/[imsuy]*$/)[0];
              I.pattern = RegExp(I.pattern.source, K + "g");
            }
            for (var be = I.pattern || I, ke = C.next, qe = w; ke !== b.tail && !(x && qe >= x.reach); qe += ke.value.length, ke = ke.next) {
              var mt = ke.value;
              if (b.length > _.length)
                return;
              if (!(mt instanceof a)) {
                var N = 1, $e;
                if (ce) {
                  if ($e = c(be, qe, _, Te), !$e || $e.index >= _.length)
                    break;
                  var $t = $e.index, ye = $e.index + $e[0].length, Ye = qe;
                  for (Ye += ke.value.length; $t >= Ye; )
                    ke = ke.next, Ye += ke.value.length;
                  if (Ye -= ke.value.length, qe = Ye, ke.value instanceof a)
                    continue;
                  for (var $ = ke; $ !== b.tail && (Ye < ye || typeof $.value == "string"); $ = $.next)
                    N++, Ye += $.value.length;
                  N--, mt = _.slice(qe, Ye), $e.index -= qe;
                } else if ($e = c(be, 0, mt, Te), !$e)
                  continue;
                var $t = $e.index, cr = $e[0], Ai = mt.slice(0, $t), Ti = mt.slice($t + cr.length), Mi = qe + mt.length;
                x && Mi > x.reach && (x.reach = Mi);
                var Ur = ke.prev;
                Ai && (Ur = h(b, Ur, Ai), qe += Ai.length), f(b, Ur, N);
                var dr = new a(S, U ? l.tokenize(cr, U) : cr, fe, cr);
                if (ke = h(b, Ur, dr), Ti && h(b, ke, Ti), N > 1) {
                  var ur = {
                    cause: S + "," + T,
                    reach: Mi
                  };
                  d(_, b, k, ke.prev, qe, ur), x && ur.reach > x.reach && (x.reach = ur.reach);
                }
              }
            }
          }
        }
    }
    function u() {
      var _ = { value: null, prev: null, next: null }, b = { value: null, prev: _, next: null };
      _.next = b, this.head = _, this.tail = b, this.length = 0;
    }
    function h(_, b, k) {
      var C = b.next, w = { value: k, prev: b, next: C };
      return b.next = w, C.prev = w, _.length++, w;
    }
    function f(_, b, k) {
      for (var C = b.next, w = 0; w < k && C !== _.tail; w++)
        C = C.next;
      b.next = C, C.prev = b, _.length -= w;
    }
    function p(_) {
      for (var b = [], k = _.head.next; k !== _.tail; )
        b.push(k.value), k = k.next;
      return b;
    }
    if (!r.document)
      return r.addEventListener && (l.disableWorkerMessageHandler || r.addEventListener("message", function(_) {
        var b = JSON.parse(_.data), k = b.language, C = b.code, w = b.immediateClose;
        r.postMessage(l.highlight(C, l.languages[k], k)), w && r.close();
      }, !1)), l;
    var m = l.util.currentScript();
    m && (l.filename = m.src, m.hasAttribute("data-manual") && (l.manual = !0));
    function g() {
      l.manual || l.highlightAll();
    }
    if (!l.manual) {
      var y = document.readyState;
      y === "loading" || y === "interactive" && m && m.defer ? document.addEventListener("DOMContentLoaded", g) : window.requestAnimationFrame ? window.requestAnimationFrame(g) : window.setTimeout(g, 16);
    }
    return l;
  }(e);
  n.exports && (n.exports = t), typeof Rp < "u" && (Rp.Prism = t), t.languages.markup = {
    comment: {
      pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
      greedy: !0
    },
    prolog: {
      pattern: /<\?[\s\S]+?\?>/,
      greedy: !0
    },
    doctype: {
      // https://www.w3.org/TR/xml/#NT-doctypedecl
      pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
      greedy: !0,
      inside: {
        "internal-subset": {
          pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
          lookbehind: !0,
          greedy: !0,
          inside: null
          // see below
        },
        string: {
          pattern: /"[^"]*"|'[^']*'/,
          greedy: !0
        },
        punctuation: /^<!|>$|[[\]]/,
        "doctype-tag": /^DOCTYPE/i,
        name: /[^\s<>'"]+/
      }
    },
    cdata: {
      pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
      greedy: !0
    },
    tag: {
      pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
      greedy: !0,
      inside: {
        tag: {
          pattern: /^<\/?[^\s>\/]+/,
          inside: {
            punctuation: /^<\/?/,
            namespace: /^[^\s>\/:]+:/
          }
        },
        "special-attr": [],
        "attr-value": {
          pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
          inside: {
            punctuation: [
              {
                pattern: /^=/,
                alias: "attr-equals"
              },
              {
                pattern: /^(\s*)["']|["']$/,
                lookbehind: !0
              }
            ]
          }
        },
        punctuation: /\/?>/,
        "attr-name": {
          pattern: /[^\s>\/]+/,
          inside: {
            namespace: /^[^\s>\/:]+:/
          }
        }
      }
    },
    entity: [
      {
        pattern: /&[\da-z]{1,8};/i,
        alias: "named-entity"
      },
      /&#x?[\da-f]{1,8};/i
    ]
  }, t.languages.markup.tag.inside["attr-value"].inside.entity = t.languages.markup.entity, t.languages.markup.doctype.inside["internal-subset"].inside = t.languages.markup, t.hooks.add("wrap", function(r) {
    r.type === "entity" && (r.attributes.title = r.content.replace(/&amp;/, "&"));
  }), Object.defineProperty(t.languages.markup.tag, "addInlined", {
    /**
     * Adds an inlined language to markup.
     *
     * An example of an inlined language is CSS with `<style>` tags.
     *
     * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
     * case insensitive.
     * @param {string} lang The language key.
     * @example
     * addInlined('style', 'css');
     */
    value: function(i, o) {
      var s = {};
      s["language-" + o] = {
        pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
        lookbehind: !0,
        inside: t.languages[o]
      }, s.cdata = /^<!\[CDATA\[|\]\]>$/i;
      var l = {
        "included-cdata": {
          pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
          inside: s
        }
      };
      l["language-" + o] = {
        pattern: /[\s\S]+/,
        inside: t.languages[o]
      };
      var a = {};
      a[i] = {
        pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function() {
          return i;
        }), "i"),
        lookbehind: !0,
        greedy: !0,
        inside: l
      }, t.languages.insertBefore("markup", "cdata", a);
    }
  }), Object.defineProperty(t.languages.markup.tag, "addAttribute", {
    /**
     * Adds an pattern to highlight languages embedded in HTML attributes.
     *
     * An example of an inlined language is CSS with `style` attributes.
     *
     * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
     * case insensitive.
     * @param {string} lang The language key.
     * @example
     * addAttribute('style', 'css');
     */
    value: function(r, i) {
      t.languages.markup.tag.inside["special-attr"].push({
        pattern: RegExp(
          /(^|["'\s])/.source + "(?:" + r + ")" + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
          "i"
        ),
        lookbehind: !0,
        inside: {
          "attr-name": /^[^\s=]+/,
          "attr-value": {
            pattern: /=[\s\S]+/,
            inside: {
              value: {
                pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
                lookbehind: !0,
                alias: [i, "language-" + i],
                inside: t.languages[i]
              },
              punctuation: [
                {
                  pattern: /^=/,
                  alias: "attr-equals"
                },
                /"|'/
              ]
            }
          }
        }
      });
    }
  }), t.languages.html = t.languages.markup, t.languages.mathml = t.languages.markup, t.languages.svg = t.languages.markup, t.languages.xml = t.languages.extend("markup", {}), t.languages.ssml = t.languages.xml, t.languages.atom = t.languages.xml, t.languages.rss = t.languages.xml, function(r) {
    var i = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
    r.languages.css = {
      comment: /\/\*[\s\S]*?\*\//,
      atrule: {
        pattern: RegExp("@[\\w-](?:" + /[^;{\s"']|\s+(?!\s)/.source + "|" + i.source + ")*?" + /(?:;|(?=\s*\{))/.source),
        inside: {
          rule: /^@[\w-]+/,
          "selector-function-argument": {
            pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
            lookbehind: !0,
            alias: "selector"
          },
          keyword: {
            pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
            lookbehind: !0
          }
          // See rest below
        }
      },
      url: {
        // https://drafts.csswg.org/css-values-3/#urls
        pattern: RegExp("\\burl\\((?:" + i.source + "|" + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ")\\)", "i"),
        greedy: !0,
        inside: {
          function: /^url/i,
          punctuation: /^\(|\)$/,
          string: {
            pattern: RegExp("^" + i.source + "$"),
            alias: "url"
          }
        }
      },
      selector: {
        pattern: RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|` + i.source + ")*(?=\\s*\\{)"),
        lookbehind: !0
      },
      string: {
        pattern: i,
        greedy: !0
      },
      property: {
        pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
        lookbehind: !0
      },
      important: /!important\b/i,
      function: {
        pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
        lookbehind: !0
      },
      punctuation: /[(){};:,]/
    }, r.languages.css.atrule.inside.rest = r.languages.css;
    var o = r.languages.markup;
    o && (o.tag.addInlined("style", "css"), o.tag.addAttribute("style", "css"));
  }(t), t.languages.clike = {
    comment: [
      {
        pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
        lookbehind: !0,
        greedy: !0
      },
      {
        pattern: /(^|[^\\:])\/\/.*/,
        lookbehind: !0,
        greedy: !0
      }
    ],
    string: {
      pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
      greedy: !0
    },
    "class-name": {
      pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
      lookbehind: !0,
      inside: {
        punctuation: /[.\\]/
      }
    },
    keyword: /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
    boolean: /\b(?:false|true)\b/,
    function: /\b\w+(?=\()/,
    number: /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
    operator: /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
    punctuation: /[{}[\];(),.:]/
  }, t.languages.javascript = t.languages.extend("clike", {
    "class-name": [
      t.languages.clike["class-name"],
      {
        pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
        lookbehind: !0
      }
    ],
    keyword: [
      {
        pattern: /((?:^|\})\s*)catch\b/,
        lookbehind: !0
      },
      {
        pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
        lookbehind: !0
      }
    ],
    // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
    function: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
    number: {
      pattern: RegExp(
        /(^|[^\w$])/.source + "(?:" + // constant
        (/NaN|Infinity/.source + "|" + // binary integer
        /0[bB][01]+(?:_[01]+)*n?/.source + "|" + // octal integer
        /0[oO][0-7]+(?:_[0-7]+)*n?/.source + "|" + // hexadecimal integer
        /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + "|" + // decimal bigint
        /\d+(?:_\d+)*n/.source + "|" + // decimal number (integer or float) but no bigint
        /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ")" + /(?![\w$])/.source
      ),
      lookbehind: !0
    },
    operator: /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
  }), t.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/, t.languages.insertBefore("javascript", "keyword", {
    regex: {
      pattern: RegExp(
        // lookbehind
        // eslint-disable-next-line regexp/no-dupe-characters-character-class
        /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source + // Regex pattern:
        // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
        // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
        // with the only syntax, so we have to define 2 different regex patterns.
        /\//.source + "(?:" + /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source + "|" + // `v` flag syntax. This supports 3 levels of nested character classes.
        /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source + ")" + // lookahead
        /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
      ),
      lookbehind: !0,
      greedy: !0,
      inside: {
        "regex-source": {
          pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
          lookbehind: !0,
          alias: "language-regex",
          inside: t.languages.regex
        },
        "regex-delimiter": /^\/|\/$/,
        "regex-flags": /^[a-z]+$/
      }
    },
    // This must be declared before keyword because we use "function" inside the look-forward
    "function-variable": {
      pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
      alias: "function"
    },
    parameter: [
      {
        pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
        lookbehind: !0,
        inside: t.languages.javascript
      },
      {
        pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
        lookbehind: !0,
        inside: t.languages.javascript
      },
      {
        pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
        lookbehind: !0,
        inside: t.languages.javascript
      },
      {
        pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
        lookbehind: !0,
        inside: t.languages.javascript
      }
    ],
    constant: /\b[A-Z](?:[A-Z_]|\dx?)*\b/
  }), t.languages.insertBefore("javascript", "string", {
    hashbang: {
      pattern: /^#!.*/,
      greedy: !0,
      alias: "comment"
    },
    "template-string": {
      pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
      greedy: !0,
      inside: {
        "template-punctuation": {
          pattern: /^`|`$/,
          alias: "string"
        },
        interpolation: {
          pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
          lookbehind: !0,
          inside: {
            "interpolation-punctuation": {
              pattern: /^\$\{|\}$/,
              alias: "punctuation"
            },
            rest: t.languages.javascript
          }
        },
        string: /[\s\S]+/
      }
    },
    "string-property": {
      pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
      lookbehind: !0,
      greedy: !0,
      alias: "property"
    }
  }), t.languages.insertBefore("javascript", "operator", {
    "literal-property": {
      pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
      lookbehind: !0,
      alias: "property"
    }
  }), t.languages.markup && (t.languages.markup.tag.addInlined("script", "javascript"), t.languages.markup.tag.addAttribute(
    /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
    "javascript"
  )), t.languages.js = t.languages.javascript, function() {
    if (typeof t > "u" || typeof document > "u")
      return;
    Element.prototype.matches || (Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector);
    var r = "Loading…", i = function(m, g) {
      return "✖ Error " + m + " while fetching file: " + g;
    }, o = "✖ Error: File does not exist or is empty", s = {
      js: "javascript",
      py: "python",
      rb: "ruby",
      ps1: "powershell",
      psm1: "powershell",
      sh: "bash",
      bat: "batch",
      h: "c",
      tex: "latex"
    }, l = "data-src-status", a = "loading", c = "loaded", d = "failed", u = "pre[data-src]:not([" + l + '="' + c + '"]):not([' + l + '="' + a + '"])';
    function h(m, g, y) {
      var _ = new XMLHttpRequest();
      _.open("GET", m, !0), _.onreadystatechange = function() {
        _.readyState == 4 && (_.status < 400 && _.responseText ? g(_.responseText) : _.status >= 400 ? y(i(_.status, _.statusText)) : y(o));
      }, _.send(null);
    }
    function f(m) {
      var g = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(m || "");
      if (g) {
        var y = Number(g[1]), _ = g[2], b = g[3];
        return _ ? b ? [y, Number(b)] : [y, void 0] : [y, y];
      }
    }
    t.hooks.add("before-highlightall", function(m) {
      m.selector += ", " + u;
    }), t.hooks.add("before-sanity-check", function(m) {
      var g = (
        /** @type {HTMLPreElement} */
        m.element
      );
      if (g.matches(u)) {
        m.code = "", g.setAttribute(l, a);
        var y = g.appendChild(document.createElement("CODE"));
        y.textContent = r;
        var _ = g.getAttribute("data-src"), b = m.language;
        if (b === "none") {
          var k = (/\.(\w+)$/.exec(_) || [, "none"])[1];
          b = s[k] || k;
        }
        t.util.setLanguage(y, b), t.util.setLanguage(g, b);
        var C = t.plugins.autoloader;
        C && C.loadLanguages(b), h(
          _,
          function(w) {
            g.setAttribute(l, c);
            var x = f(g.getAttribute("data-range"));
            if (x) {
              var S = w.split(/\r\n?|\n/g), D = x[0], T = x[1] == null ? S.length : x[1];
              D < 0 && (D += S.length), D = Math.max(0, Math.min(D - 1, S.length)), T < 0 && (T += S.length), T = Math.max(0, Math.min(T, S.length)), w = S.slice(D, T).join(`
`), g.hasAttribute("data-start") || g.setAttribute("data-start", String(D + 1));
            }
            y.textContent = w, t.highlightElement(y);
          },
          function(w) {
            g.setAttribute(l, d), y.textContent = w;
          }
        );
      }
    }), t.plugins.fileHighlight = {
      /**
       * Executes the File Highlight plugin for all matching `pre` elements under the given container.
       *
       * Note: Elements which are already loaded or currently loading will not be touched by this method.
       *
       * @param {ParentNode} [container=document]
       */
      highlight: function(g) {
        for (var y = (g || document).querySelectorAll(u), _ = 0, b; b = y[_++]; )
          t.highlightElement(b);
      }
    };
    var p = !1;
    t.fileHighlight = function() {
      p || (console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead."), p = !0), t.plugins.fileHighlight.highlight.apply(this, arguments);
    };
  }();
})(Rb);
var ed = Rb.exports;
Prism.languages.python = {
  comment: {
    pattern: /(^|[^\\])#.*/,
    lookbehind: !0,
    greedy: !0
  },
  "string-interpolation": {
    pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
    greedy: !0,
    inside: {
      interpolation: {
        // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
        pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
        lookbehind: !0,
        inside: {
          "format-spec": {
            pattern: /(:)[^:(){}]+(?=\}$)/,
            lookbehind: !0
          },
          "conversion-option": {
            pattern: /![sra](?=[:}]$)/,
            alias: "punctuation"
          },
          rest: null
        }
      },
      string: /[\s\S]+/
    }
  },
  "triple-quoted-string": {
    pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
    greedy: !0,
    alias: "string"
  },
  string: {
    pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
    greedy: !0
  },
  function: {
    pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
    lookbehind: !0
  },
  "class-name": {
    pattern: /(\bclass\s+)\w+/i,
    lookbehind: !0
  },
  decorator: {
    pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
    lookbehind: !0,
    alias: ["annotation", "punctuation"],
    inside: {
      punctuation: /\./
    }
  },
  keyword: /\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,
  builtin: /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,
  boolean: /\b(?:False|None|True)\b/,
  number: /\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,
  operator: /[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
  punctuation: /[{}[\];(),.:]/
};
Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest = Prism.languages.python;
Prism.languages.py = Prism.languages.python;
(function(n) {
  var e = /\\(?:[^a-z()[\]]|[a-z*]+)/i, t = {
    "equation-command": {
      pattern: e,
      alias: "regex"
    }
  };
  n.languages.latex = {
    comment: /%.*/,
    // the verbatim environment prints whitespace to the document
    cdata: {
      pattern: /(\\begin\{((?:lstlisting|verbatim)\*?)\})[\s\S]*?(?=\\end\{\2\})/,
      lookbehind: !0
    },
    /*
     * equations can be between $$ $$ or $ $ or \( \) or \[ \]
     * (all are multiline)
     */
    equation: [
      {
        pattern: /\$\$(?:\\[\s\S]|[^\\$])+\$\$|\$(?:\\[\s\S]|[^\\$])+\$|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]/,
        inside: t,
        alias: "string"
      },
      {
        pattern: /(\\begin\{((?:align|eqnarray|equation|gather|math|multline)\*?)\})[\s\S]*?(?=\\end\{\2\})/,
        lookbehind: !0,
        inside: t,
        alias: "string"
      }
    ],
    /*
     * arguments which are keywords or references are highlighted
     * as keywords
     */
    keyword: {
      pattern: /(\\(?:begin|cite|documentclass|end|label|ref|usepackage)(?:\[[^\]]+\])?\{)[^}]+(?=\})/,
      lookbehind: !0
    },
    url: {
      pattern: /(\\url\{)[^}]+(?=\})/,
      lookbehind: !0
    },
    /*
     * section or chapter headlines are highlighted as bold so that
     * they stand out more
     */
    headline: {
      pattern: /(\\(?:chapter|frametitle|paragraph|part|section|subparagraph|subsection|subsubparagraph|subsubsection|subsubsubparagraph)\*?(?:\[[^\]]+\])?\{)[^}]+(?=\})/,
      lookbehind: !0,
      alias: "class-name"
    },
    function: {
      pattern: e,
      alias: "selector"
    },
    punctuation: /[[\]{}&]/
  }, n.languages.tex = n.languages.latex, n.languages.context = n.languages.latex;
})(Prism);
(function(n) {
  var e = "\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b", t = {
    pattern: /(^(["']?)\w+\2)[ \t]+\S.*/,
    lookbehind: !0,
    alias: "punctuation",
    // this looks reasonably well in all themes
    inside: null
    // see below
  }, r = {
    bash: t,
    environment: {
      pattern: RegExp("\\$" + e),
      alias: "constant"
    },
    variable: [
      // [0]: Arithmetic Environment
      {
        pattern: /\$?\(\([\s\S]+?\)\)/,
        greedy: !0,
        inside: {
          // If there is a $ sign at the beginning highlight $(( and )) as variable
          variable: [
            {
              pattern: /(^\$\(\([\s\S]+)\)\)/,
              lookbehind: !0
            },
            /^\$\(\(/
          ],
          number: /\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,
          // Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
          operator: /--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,
          // If there is no $ sign at the beginning highlight (( and )) as punctuation
          punctuation: /\(\(?|\)\)?|,|;/
        }
      },
      // [1]: Command Substitution
      {
        pattern: /\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,
        greedy: !0,
        inside: {
          variable: /^\$\(|^`|\)$|`$/
        }
      },
      // [2]: Brace expansion
      {
        pattern: /\$\{[^}]+\}/,
        greedy: !0,
        inside: {
          operator: /:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,
          punctuation: /[\[\]]/,
          environment: {
            pattern: RegExp("(\\{)" + e),
            lookbehind: !0,
            alias: "constant"
          }
        }
      },
      /\$(?:\w+|[#?*!@$])/
    ],
    // Escape sequences from echo and printf's manuals, and escaped quotes.
    entity: /\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/
  };
  n.languages.bash = {
    shebang: {
      pattern: /^#!\s*\/.*/,
      alias: "important"
    },
    comment: {
      pattern: /(^|[^"{\\$])#.*/,
      lookbehind: !0
    },
    "function-name": [
      // a) function foo {
      // b) foo() {
      // c) function foo() {
      // but not “foo {”
      {
        // a) and c)
        pattern: /(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,
        lookbehind: !0,
        alias: "function"
      },
      {
        // b)
        pattern: /\b[\w-]+(?=\s*\(\s*\)\s*\{)/,
        alias: "function"
      }
    ],
    // Highlight variable names as variables in for and select beginnings.
    "for-or-select": {
      pattern: /(\b(?:for|select)\s+)\w+(?=\s+in\s)/,
      alias: "variable",
      lookbehind: !0
    },
    // Highlight variable names as variables in the left-hand part
    // of assignments (“=” and “+=”).
    "assign-left": {
      pattern: /(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,
      inside: {
        environment: {
          pattern: RegExp("(^|[\\s;|&]|[<>]\\()" + e),
          lookbehind: !0,
          alias: "constant"
        }
      },
      alias: "variable",
      lookbehind: !0
    },
    // Highlight parameter names as variables
    parameter: {
      pattern: /(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,
      alias: "variable",
      lookbehind: !0
    },
    string: [
      // Support for Here-documents https://en.wikipedia.org/wiki/Here_document
      {
        pattern: /((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,
        lookbehind: !0,
        greedy: !0,
        inside: r
      },
      // Here-document with quotes around the tag
      // → No expansion (so no “inside”).
      {
        pattern: /((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,
        lookbehind: !0,
        greedy: !0,
        inside: {
          bash: t
        }
      },
      // “Normal” string
      {
        // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
        pattern: /(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,
        lookbehind: !0,
        greedy: !0,
        inside: r
      },
      {
        // https://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html
        pattern: /(^|[^$\\])'[^']*'/,
        lookbehind: !0,
        greedy: !0
      },
      {
        // https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
        pattern: /\$'(?:[^'\\]|\\[\s\S])*'/,
        greedy: !0,
        inside: {
          entity: r.entity
        }
      }
    ],
    environment: {
      pattern: RegExp("\\$?" + e),
      alias: "constant"
    },
    variable: r.variable,
    function: {
      pattern: /(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,
      lookbehind: !0
    },
    keyword: {
      pattern: /(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,
      lookbehind: !0
    },
    // https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
    builtin: {
      pattern: /(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,
      lookbehind: !0,
      // Alias added to make those easier to distinguish from strings.
      alias: "class-name"
    },
    boolean: {
      pattern: /(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,
      lookbehind: !0
    },
    "file-descriptor": {
      pattern: /\B&\d\b/,
      alias: "important"
    },
    operator: {
      // Lots of redirections here, but not just that.
      pattern: /\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,
      inside: {
        "file-descriptor": {
          pattern: /^\d/,
          alias: "important"
        }
      }
    },
    punctuation: /\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,
    number: {
      pattern: /(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,
      lookbehind: !0
    }
  }, t.inside = n.languages.bash;
  for (var i = [
    "comment",
    "function-name",
    "for-or-select",
    "assign-left",
    "parameter",
    "string",
    "environment",
    "function",
    "keyword",
    "builtin",
    "boolean",
    "file-descriptor",
    "operator",
    "punctuation",
    "number"
  ], o = r.variable[1].inside, s = 0; s < i.length; s++)
    o[i[s]] = n.languages.bash[i[s]];
  n.languages.sh = n.languages.bash, n.languages.shell = n.languages.bash;
})(Prism);
const Jv = '<svg class="md-link-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true" fill="currentColor"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg>', Yv = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15" color="currentColor" aria-hidden="true" aria-label="Copy" stroke-width="1.3" width="15" height="15">
  <path fill="currentColor" d="M12.728 4.545v8.182H4.545V4.545zm0 -0.909H4.545a0.909 0.909 0 0 0 -0.909 0.909v8.182a0.909 0.909 0 0 0 0.909 0.909h8.182a0.909 0.909 0 0 0 0.909 -0.909V4.545a0.909 0.909 0 0 0 -0.909 -0.909"/>
  <path fill="currentColor" d="M1.818 8.182H0.909V1.818a0.909 0.909 0 0 1 0.909 -0.909h6.364v0.909H1.818Z"/>
</svg>

`, Xv = `<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 17 17" aria-hidden="true" aria-label="Copied" fill="none" stroke="currentColor" stroke-width="1.3">
  <path d="m13.813 4.781 -7.438 7.438 -3.188 -3.188"/>
</svg>
`, Bp = `<button title="copy" class="copy_code_button">
  <span class="copy-text">${Yv}</span>
  <span class="check">${Xv}</span>
</button>`, Bb = /[&<>"']/, Zv = new RegExp(Bb.source, "g"), Pb = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, Qv = new RegExp(Pb.source, "g"), eC = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
}, Pp = (n) => eC[n] || "";
function td(n, e) {
  if (e) {
    if (Bb.test(n))
      return n.replace(Zv, Pp);
  } else if (Pb.test(n))
    return n.replace(Qv, Pp);
  return n;
}
function tC(n) {
  const e = n.map((t) => ({
    start: new RegExp(t.left.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")),
    end: new RegExp(t.right.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"))
  }));
  return {
    name: "latex",
    level: "block",
    start(t) {
      for (const r of e) {
        const i = t.match(r.start);
        if (i)
          return i.index;
      }
      return -1;
    },
    tokenizer(t, r) {
      for (const i of e) {
        const o = new RegExp(
          `${i.start.source}([\\s\\S]+?)${i.end.source}`
        ).exec(t);
        if (o)
          return {
            type: "latex",
            raw: o[0],
            text: o[1].trim()
          };
      }
    },
    renderer(t) {
      return `<div class="latex-block">${t.text}</div>`;
    }
  };
}
function nC() {
  return {
    name: "mermaid",
    level: "block",
    start(n) {
      var e;
      return (e = n.match(/^```mermaid\s*\n/)) == null ? void 0 : e.index;
    },
    tokenizer(n) {
      const e = /^```mermaid\s*\n([\s\S]*?)```\s*(?:\n|$)/.exec(n);
      if (e)
        return {
          type: "mermaid",
          raw: e[0],
          text: e[1].trim()
        };
    },
    renderer(n) {
      return `<div class="mermaid">${n.text}</div>
`;
    }
  };
}
const rC = {
  code(n, e, t) {
    var i;
    const r = ((i = (e ?? "").match(/\S*/)) == null ? void 0 : i[0]) ?? "";
    return n = n.replace(/\n$/, "") + `
`, !r || r === "mermaid" ? '<div class="code_wrap">' + Bp + "<pre><code>" + (t ? n : td(n, !0)) + `</code></pre></div>
` : '<div class="code_wrap">' + Bp + '<pre><code class="language-' + td(r) + '">' + (t ? n : td(n, !0)) + `</code></pre></div>
`;
  }
}, iC = new Ah();
function oC({
  header_links: n,
  line_breaks: e,
  latex_delimiters: t
}) {
  const r = new Ob();
  r.use(
    {
      gfm: !0,
      pedantic: !1,
      breaks: e
    },
    zv({
      highlight: (s, l) => {
        var a;
        return (a = ed.languages) != null && a[l] ? ed.highlight(s, ed.languages[l], l) : s;
      }
    }),
    { renderer: rC }
  ), n && (r.use(Gv()), r.use({
    extensions: [
      {
        name: "heading",
        level: "block",
        renderer(s) {
          const l = s.raw.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi, ""), a = "h" + iC.slug(l), c = s.depth, d = this.parser.parseInline(s.tokens);
          return `<h${c} id="${a}"><a class="md-header-anchor" href="#${a}">${Jv}</a>${d}</h${c}>
`;
        }
      }
    ]
  }));
  const i = nC(), o = tC(t);
  return r.use({
    extensions: [i, o]
  }), r;
}
const ou = (n) => JSON.parse(JSON.stringify(n)), sC = (n) => n.nodeType === 1, lC = (n) => AC.has(n.tagName), aC = (n) => "action" in n, cC = (n) => n.tagName === "IFRAME", dC = (n) => "formAction" in n, uC = (n) => "protocol" in n, sl = /* @__PURE__ */ (() => {
  const n = /^(?:\w+script|data):/i;
  return (e) => n.test(e);
})(), hC = /* @__PURE__ */ (() => {
  const n = /(?:script|data):/i;
  return (e) => n.test(e);
})(), fC = (n) => {
  const e = {};
  for (let t = 0, r = n.length; t < r; t++) {
    const i = n[t];
    for (const o in i)
      e[o] ? e[o] = e[o].concat(i[o]) : e[o] = i[o];
  }
  return e;
}, zb = (n, e) => {
  let t = n.firstChild;
  for (; t; ) {
    const r = t.nextSibling;
    sC(t) && (e(t, n), t.parentNode && zb(t, e)), t = r;
  }
}, pC = (n, e) => {
  const t = document.createNodeIterator(n, NodeFilter.SHOW_ELEMENT);
  let r;
  for (; r = t.nextNode(); ) {
    const i = r.parentNode;
    i && e(r, i);
  }
}, mC = (n, e) => !!globalThis.document && !!globalThis.document.createNodeIterator ? pC(n, e) : zb(n, e), Hb = [
  "a",
  "abbr",
  "acronym",
  "address",
  "area",
  "article",
  "aside",
  "audio",
  "b",
  "bdi",
  "bdo",
  "bgsound",
  "big",
  "blockquote",
  "body",
  "br",
  "button",
  "canvas",
  "caption",
  "center",
  "cite",
  "code",
  "col",
  "colgroup",
  "datalist",
  "dd",
  "del",
  "details",
  "dfn",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "font",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hgroup",
  "hr",
  "html",
  "i",
  "img",
  "input",
  "ins",
  "kbd",
  "keygen",
  "label",
  "layer",
  "legend",
  "li",
  "link",
  "listing",
  "main",
  "map",
  "mark",
  "marquee",
  "menu",
  "meta",
  "meter",
  "nav",
  "nobr",
  "ol",
  "optgroup",
  "option",
  "output",
  "p",
  "picture",
  "popup",
  "pre",
  "progress",
  "q",
  "rb",
  "rp",
  "rt",
  "rtc",
  "ruby",
  "s",
  "samp",
  "section",
  "select",
  "selectmenu",
  "small",
  "source",
  "span",
  "strike",
  "strong",
  "style",
  "sub",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "track",
  "tt",
  "u",
  "ul",
  "var",
  "video",
  "wbr"
], gC = [
  "basefont",
  "command",
  "data",
  "iframe",
  "image",
  "plaintext",
  "portal",
  "slot",
  // 'template', //TODO: Not exactly correct to never allow this, too strict
  "textarea",
  "title",
  "xmp"
], bC = /* @__PURE__ */ new Set([
  ...Hb,
  ...gC
]), Vb = [
  "svg",
  "a",
  "altglyph",
  "altglyphdef",
  "altglyphitem",
  "animatecolor",
  "animatemotion",
  "animatetransform",
  "circle",
  "clippath",
  "defs",
  "desc",
  "ellipse",
  "filter",
  "font",
  "g",
  "glyph",
  "glyphref",
  "hkern",
  "image",
  "line",
  "lineargradient",
  "marker",
  "mask",
  "metadata",
  "mpath",
  "path",
  "pattern",
  "polygon",
  "polyline",
  "radialgradient",
  "rect",
  "stop",
  "style",
  "switch",
  "symbol",
  "text",
  "textpath",
  "title",
  "tref",
  "tspan",
  "view",
  "vkern",
  /* FILTERS */
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feDistantLight",
  "feFlood",
  "feFuncA",
  "feFuncB",
  "feFuncG",
  "feFuncR",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMergeNode",
  "feMorphology",
  "feOffset",
  "fePointLight",
  "feSpecularLighting",
  "feSpotLight",
  "feTile",
  "feTurbulence"
], yC = [
  "animate",
  "color-profile",
  "cursor",
  "discard",
  "fedropshadow",
  "font-face",
  "font-face-format",
  "font-face-name",
  "font-face-src",
  "font-face-uri",
  "foreignobject",
  "hatch",
  "hatchpath",
  "mesh",
  "meshgradient",
  "meshpatch",
  "meshrow",
  "missing-glyph",
  "script",
  "set",
  "solidcolor",
  "unknown",
  "use"
], _C = /* @__PURE__ */ new Set([
  ...Vb,
  ...yC
]), Ub = [
  "math",
  "menclose",
  "merror",
  "mfenced",
  "mfrac",
  "mglyph",
  "mi",
  "mlabeledtr",
  "mmultiscripts",
  "mn",
  "mo",
  "mover",
  "mpadded",
  "mphantom",
  "mroot",
  "mrow",
  "ms",
  "mspace",
  "msqrt",
  "mstyle",
  "msub",
  "msup",
  "msubsup",
  "mtable",
  "mtd",
  "mtext",
  "mtr",
  "munder",
  "munderover"
], wC = [
  "maction",
  "maligngroup",
  "malignmark",
  "mlongdiv",
  "mscarries",
  "mscarry",
  "msgroup",
  "mstack",
  "msline",
  "msrow",
  "semantics",
  "annotation",
  "annotation-xml",
  "mprescripts",
  "none"
], kC = /* @__PURE__ */ new Set([
  ...Ub,
  ...wC
]), vC = [
  "abbr",
  "accept",
  "accept-charset",
  "accesskey",
  "action",
  "align",
  "alink",
  "allow",
  "allowfullscreen",
  "alt",
  "anchor",
  "archive",
  "as",
  "async",
  "autocapitalize",
  "autocomplete",
  "autocorrect",
  "autofocus",
  "autopictureinpicture",
  "autoplay",
  "axis",
  "background",
  "behavior",
  "bgcolor",
  "border",
  "bordercolor",
  "capture",
  "cellpadding",
  "cellspacing",
  "challenge",
  "char",
  "charoff",
  "charset",
  "checked",
  "cite",
  "class",
  "classid",
  "clear",
  "code",
  "codebase",
  "codetype",
  "color",
  "cols",
  "colspan",
  "compact",
  "content",
  "contenteditable",
  "controls",
  "controlslist",
  "conversiondestination",
  "coords",
  "crossorigin",
  "csp",
  "data",
  "datetime",
  "declare",
  "decoding",
  "default",
  "defer",
  "dir",
  "direction",
  "dirname",
  "disabled",
  "disablepictureinpicture",
  "disableremoteplayback",
  "disallowdocumentaccess",
  "download",
  "draggable",
  "elementtiming",
  "enctype",
  "end",
  "enterkeyhint",
  "event",
  "exportparts",
  "face",
  "for",
  "form",
  "formaction",
  "formenctype",
  "formmethod",
  "formnovalidate",
  "formtarget",
  "frame",
  "frameborder",
  "headers",
  "height",
  "hidden",
  "high",
  "href",
  "hreflang",
  "hreftranslate",
  "hspace",
  "http-equiv",
  "id",
  "imagesizes",
  "imagesrcset",
  "importance",
  "impressiondata",
  "impressionexpiry",
  "incremental",
  "inert",
  "inputmode",
  "integrity",
  "invisible",
  "ismap",
  "keytype",
  "kind",
  "label",
  "lang",
  "language",
  "latencyhint",
  "leftmargin",
  "link",
  "list",
  "loading",
  "longdesc",
  "loop",
  "low",
  "lowsrc",
  "manifest",
  "marginheight",
  "marginwidth",
  "max",
  "maxlength",
  "mayscript",
  "media",
  "method",
  "min",
  "minlength",
  "multiple",
  "muted",
  "name",
  "nohref",
  "nomodule",
  "nonce",
  "noresize",
  "noshade",
  "novalidate",
  "nowrap",
  "object",
  "open",
  "optimum",
  "part",
  "pattern",
  "ping",
  "placeholder",
  "playsinline",
  "policy",
  "poster",
  "preload",
  "pseudo",
  "readonly",
  "referrerpolicy",
  "rel",
  "reportingorigin",
  "required",
  "resources",
  "rev",
  "reversed",
  "role",
  "rows",
  "rowspan",
  "rules",
  "sandbox",
  "scheme",
  "scope",
  "scopes",
  "scrollamount",
  "scrolldelay",
  "scrolling",
  "select",
  "selected",
  "shadowroot",
  "shadowrootdelegatesfocus",
  "shape",
  "size",
  "sizes",
  "slot",
  "span",
  "spellcheck",
  "src",
  "srclang",
  "srcset",
  "standby",
  "start",
  "step",
  "style",
  "summary",
  "tabindex",
  "target",
  "text",
  "title",
  "topmargin",
  "translate",
  "truespeed",
  "trusttoken",
  "type",
  "usemap",
  "valign",
  "value",
  "valuetype",
  "version",
  "virtualkeyboardpolicy",
  "vlink",
  "vspace",
  "webkitdirectory",
  "width",
  "wrap"
], CC = [
  "accent-height",
  "accumulate",
  "additive",
  "alignment-baseline",
  "ascent",
  "attributename",
  "attributetype",
  "azimuth",
  "basefrequency",
  "baseline-shift",
  "begin",
  "bias",
  "by",
  "class",
  "clip",
  "clippathunits",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "cx",
  "cy",
  "d",
  "dx",
  "dy",
  "diffuseconstant",
  "direction",
  "display",
  "divisor",
  "dominant-baseline",
  "dur",
  "edgemode",
  "elevation",
  "end",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "filterunits",
  "flood-color",
  "flood-opacity",
  "font-family",
  "font-size",
  "font-size-adjust",
  "font-stretch",
  "font-style",
  "font-variant",
  "font-weight",
  "fx",
  "fy",
  "g1",
  "g2",
  "glyph-name",
  "glyphref",
  "gradientunits",
  "gradienttransform",
  "height",
  "href",
  "id",
  "image-rendering",
  "in",
  "in2",
  "k",
  "k1",
  "k2",
  "k3",
  "k4",
  "kerning",
  "keypoints",
  "keysplines",
  "keytimes",
  "lang",
  "lengthadjust",
  "letter-spacing",
  "kernelmatrix",
  "kernelunitlength",
  "lighting-color",
  "local",
  "marker-end",
  "marker-mid",
  "marker-start",
  "markerheight",
  "markerunits",
  "markerwidth",
  "maskcontentunits",
  "maskunits",
  "max",
  "mask",
  "media",
  "method",
  "mode",
  "min",
  "name",
  "numoctaves",
  "offset",
  "operator",
  "opacity",
  "order",
  "orient",
  "orientation",
  "origin",
  "overflow",
  "paint-order",
  "path",
  "pathlength",
  "patterncontentunits",
  "patterntransform",
  "patternunits",
  "points",
  "preservealpha",
  "preserveaspectratio",
  "primitiveunits",
  "r",
  "rx",
  "ry",
  "radius",
  "refx",
  "refy",
  "repeatcount",
  "repeatdur",
  "restart",
  "result",
  "rotate",
  "scale",
  "seed",
  "shape-rendering",
  "specularconstant",
  "specularexponent",
  "spreadmethod",
  "startoffset",
  "stddeviation",
  "stitchtiles",
  "stop-color",
  "stop-opacity",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke",
  "stroke-width",
  "style",
  "surfacescale",
  "systemlanguage",
  "tabindex",
  "targetx",
  "targety",
  "transform",
  "transform-origin",
  "text-anchor",
  "text-decoration",
  "text-rendering",
  "textlength",
  "type",
  "u1",
  "u2",
  "unicode",
  "values",
  "viewbox",
  "visibility",
  "version",
  "vert-adv-y",
  "vert-origin-x",
  "vert-origin-y",
  "width",
  "word-spacing",
  "wrap",
  "writing-mode",
  "xchannelselector",
  "ychannelselector",
  "x",
  "x1",
  "x2",
  "xmlns",
  "y",
  "y1",
  "y2",
  "z",
  "zoomandpan"
], SC = [
  "accent",
  "accentunder",
  "align",
  "bevelled",
  "close",
  "columnsalign",
  "columnlines",
  "columnspan",
  "denomalign",
  "depth",
  "dir",
  "display",
  "displaystyle",
  "encoding",
  "fence",
  "frame",
  "height",
  "href",
  "id",
  "largeop",
  "length",
  "linethickness",
  "lspace",
  "lquote",
  "mathbackground",
  "mathcolor",
  "mathsize",
  "mathvariant",
  "maxsize",
  "minsize",
  "movablelimits",
  "notation",
  "numalign",
  "open",
  "rowalign",
  "rowlines",
  "rowspacing",
  "rowspan",
  "rspace",
  "rquote",
  "scriptlevel",
  "scriptminsize",
  "scriptsizemultiplier",
  "selection",
  "separator",
  "separators",
  "stretchy",
  "subscriptshift",
  "supscriptshift",
  "symmetric",
  "voffset",
  "width",
  "xmlns"
], dn = {
  HTML: "http://www.w3.org/1999/xhtml",
  SVG: "http://www.w3.org/2000/svg",
  MATH: "http://www.w3.org/1998/Math/MathML"
}, EC = {
  [dn.HTML]: bC,
  [dn.SVG]: _C,
  [dn.MATH]: kC
}, xC = {
  [dn.HTML]: "html",
  [dn.SVG]: "svg",
  [dn.MATH]: "math"
}, DC = {
  [dn.HTML]: "",
  [dn.SVG]: "svg:",
  [dn.MATH]: "math:"
}, AC = /* @__PURE__ */ new Set([
  "A",
  "AREA",
  "BUTTON",
  "FORM",
  "IFRAME",
  "INPUT"
]), qb = {
  allowComments: !0,
  allowCustomElements: !1,
  allowUnknownMarkup: !1,
  allowElements: [
    ...Hb,
    ...Vb.map((n) => `svg:${n}`),
    ...Ub.map((n) => `math:${n}`)
  ],
  allowAttributes: fC([
    Object.fromEntries(vC.map((n) => [n, ["*"]])),
    Object.fromEntries(CC.map((n) => [n, ["svg:*"]])),
    Object.fromEntries(SC.map((n) => [n, ["math:*"]]))
  ])
};
var nd = function(n, e, t, r, i) {
  if (r === "m") throw new TypeError("Private method is not writable");
  if (r === "a" && !i) throw new TypeError("Private accessor was defined without a setter");
  if (typeof e == "function" ? n !== e || !i : !e.has(n)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return r === "a" ? i.call(n, t) : i ? i.value = t : e.set(n, t), t;
}, jr = function(n, e, t, r) {
  if (t === "a" && !r) throw new TypeError("Private accessor was defined without a getter");
  if (typeof e == "function" ? n !== e || !r : !e.has(n)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return t === "m" ? r : t === "a" ? r.call(n) : r ? r.value : e.get(n);
}, pr, Hl, Vl;
class jb {
  /* CONSTRUCTOR */
  constructor(e = {}) {
    pr.set(this, void 0), Hl.set(this, void 0), Vl.set(this, void 0), this.getConfiguration = () => ou(jr(this, pr, "f")), this.sanitize = (d) => {
      const u = jr(this, Hl, "f"), h = jr(this, Vl, "f");
      return mC(d, (f, p) => {
        const m = f.namespaceURI || dn.HTML, g = p.namespaceURI || dn.HTML, y = EC[m], _ = xC[m], b = DC[m], k = f.tagName.toLowerCase(), C = `${b}${k}`, x = `${b}*`;
        if (!y.has(k) || !u.has(C) || m !== g && k !== _)
          p.removeChild(f);
        else {
          const S = f.getAttributeNames(), D = S.length;
          if (D) {
            for (let T = 0; T < D; T++) {
              const I = S[T], U = h[I];
              (!U || !U.has(x) && !U.has(C)) && f.removeAttribute(I);
            }
            if (lC(f))
              if (uC(f)) {
                const T = f.getAttribute("href");
                T && hC(T) && sl(f.protocol) && f.removeAttribute("href");
              } else aC(f) ? sl(f.action) && f.removeAttribute("action") : dC(f) ? sl(f.formAction) && f.removeAttribute("formaction") : cC(f) && (sl(f.src) && f.removeAttribute("formaction"), f.setAttribute("sandbox", "allow-scripts"));
          }
        }
      }), d;
    }, this.sanitizeFor = (d, u) => {
      throw new Error('"sanitizeFor" is not implemented yet');
    };
    const { allowComments: t, allowCustomElements: r, allowUnknownMarkup: i, blockElements: o, dropElements: s, dropAttributes: l } = e;
    if (t === !1)
      throw new Error('A false "allowComments" is not supported yet');
    if (r)
      throw new Error('A true "allowCustomElements" is not supported yet');
    if (i)
      throw new Error('A true "allowUnknownMarkup" is not supported yet');
    if (o)
      throw new Error('"blockElements" is not supported yet, use "allowElements" instead');
    if (s)
      throw new Error('"dropElements" is not supported yet, use "allowElements" instead');
    if (l)
      throw new Error('"dropAttributes" is not supported yet, use "allowAttributes" instead');
    nd(this, pr, ou(qb), "f");
    const { allowElements: a, allowAttributes: c } = e;
    a && (jr(this, pr, "f").allowElements = e.allowElements), c && (jr(this, pr, "f").allowAttributes = e.allowAttributes), nd(this, Hl, new Set(jr(this, pr, "f").allowElements), "f"), nd(this, Vl, Object.fromEntries(Object.entries(jr(this, pr, "f").allowAttributes || {}).map(([d, u]) => [d, new Set(u)])), "f");
  }
}
pr = /* @__PURE__ */ new WeakMap(), Hl = /* @__PURE__ */ new WeakMap(), Vl = /* @__PURE__ */ new WeakMap();
jb.getDefaultConfiguration = () => ou(qb);
const TC = (n, e = location.href) => {
  try {
    return !!n && new URL(n).origin !== new URL(e).origin;
  } catch {
    return !1;
  }
};
function zp(n) {
  const e = new jb(), t = new DOMParser().parseFromString(n, "text/html");
  return Wb(t.body, "A", (r) => {
    r instanceof HTMLElement && "target" in r && TC(r.getAttribute("href"), location.href) && (r.setAttribute("target", "_blank"), r.setAttribute("rel", "noopener noreferrer"));
  }), e.sanitize(t).body.innerHTML;
}
function Wb(n, e, t) {
  n && (n.nodeName === e || typeof e == "function") && t(n);
  const r = (n == null ? void 0 : n.childNodes) || [];
  for (let i = 0; i < r.length; i++)
    Wb(r[i], e, t);
}
const Hp = [
  "!--",
  "!doctype",
  "a",
  "abbr",
  "acronym",
  "address",
  "applet",
  "area",
  "article",
  "aside",
  "audio",
  "b",
  "base",
  "basefont",
  "bdi",
  "bdo",
  "big",
  "blockquote",
  "body",
  "br",
  "button",
  "canvas",
  "caption",
  "center",
  "cite",
  "code",
  "col",
  "colgroup",
  "data",
  "datalist",
  "dd",
  "del",
  "details",
  "dfn",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "em",
  "embed",
  "fieldset",
  "figcaption",
  "figure",
  "font",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hgroup",
  "hr",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "link",
  "main",
  "map",
  "mark",
  "menu",
  "meta",
  "meter",
  "nav",
  "noframes",
  "noscript",
  "object",
  "ol",
  "optgroup",
  "option",
  "output",
  "p",
  "param",
  "picture",
  "pre",
  "progress",
  "q",
  "rp",
  "rt",
  "ruby",
  "s",
  "samp",
  "script",
  "search",
  "section",
  "select",
  "small",
  "source",
  "span",
  "strike",
  "strong",
  "style",
  "sub",
  "summary",
  "sup",
  "svg",
  "table",
  "tbody",
  "td",
  "template",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "title",
  "tr",
  "track",
  "tt",
  "u",
  "ul",
  "var",
  "video",
  "wbr"
], MC = [
  // Base structural elements
  "g",
  "defs",
  "use",
  "symbol",
  // Shape elements
  "rect",
  "circle",
  "ellipse",
  "line",
  "polyline",
  "polygon",
  "path",
  "image",
  // Text elements
  "text",
  "tspan",
  "textPath",
  // Gradient and effects
  "linearGradient",
  "radialGradient",
  "stop",
  "pattern",
  "clipPath",
  "mask",
  "filter",
  // Filter effects
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feGaussianBlur",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTurbulence",
  "feMergeNode",
  "feFuncR",
  "feFuncG",
  "feFuncB",
  "feFuncA",
  "feDistantLight",
  "fePointLight",
  "feSpotLight",
  "feFlood",
  "feTile",
  // Animation elements
  "animate",
  "animateTransform",
  "animateMotion",
  "mpath",
  "set",
  // Interactive and other elements
  "view",
  "cursor",
  "foreignObject",
  "desc",
  "title",
  "metadata",
  "switch"
], OC = [
  ...Hp,
  ...MC.filter((n) => !Hp.includes(n))
], {
  HtmlTagHydration: FC,
  SvelteComponent: NC,
  attr: $C,
  binding_callbacks: IC,
  children: LC,
  claim_element: RC,
  claim_html_tag: BC,
  detach: Vp,
  element: PC,
  init: zC,
  insert_hydration: HC,
  noop: Up,
  safe_not_equal: VC,
  toggle_class: ll
} = window.__gradio__svelte__internal, { afterUpdate: UC, tick: qC, onMount: GP } = window.__gradio__svelte__internal;
function jC(n) {
  let e, t;
  return {
    c() {
      e = PC("span"), t = new FC(!1), this.h();
    },
    l(r) {
      e = RC(r, "SPAN", { class: !0 });
      var i = LC(e);
      t = BC(i, !1), i.forEach(Vp), this.h();
    },
    h() {
      t.a = null, $C(e, "class", "md svelte-1m32c2s"), ll(
        e,
        "chatbot",
        /*chatbot*/
        n[0]
      ), ll(
        e,
        "prose",
        /*render_markdown*/
        n[1]
      );
    },
    m(r, i) {
      HC(r, e, i), t.m(
        /*html*/
        n[3],
        e
      ), n[11](e);
    },
    p(r, [i]) {
      i & /*html*/
      8 && t.p(
        /*html*/
        r[3]
      ), i & /*chatbot*/
      1 && ll(
        e,
        "chatbot",
        /*chatbot*/
        r[0]
      ), i & /*render_markdown*/
      2 && ll(
        e,
        "prose",
        /*render_markdown*/
        r[1]
      );
    },
    i: Up,
    o: Up,
    d(r) {
      r && Vp(e), n[11](null);
    }
  };
}
function qp(n) {
  return n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function WC(n, e, t) {
  var r = this && this.__awaiter || function(w, x, S, D) {
    function T(I) {
      return I instanceof S ? I : new S(function(U) {
        U(I);
      });
    }
    return new (S || (S = Promise))(function(I, U) {
      function Te(K) {
        try {
          fe(D.next(K));
        } catch (be) {
          U(be);
        }
      }
      function ce(K) {
        try {
          fe(D.throw(K));
        } catch (be) {
          U(be);
        }
      }
      function fe(K) {
        K.done ? I(K.value) : T(K.value).then(Te, ce);
      }
      fe((D = D.apply(w, x || [])).next());
    });
  };
  let { chatbot: i = !0 } = e, { message: o } = e, { sanitize_html: s = !0 } = e, { latex_delimiters: l = [] } = e, { render_markdown: a = !0 } = e, { line_breaks: c = !0 } = e, { header_links: d = !1 } = e, { allow_tags: u = !1 } = e, { theme_mode: h = "system" } = e, f, p, m = !1;
  const g = oC({
    header_links: d,
    line_breaks: c,
    latex_delimiters: l || []
  });
  function y(w) {
    return !l || l.length === 0 ? !1 : l.some((x) => w.includes(x.left) && w.includes(x.right));
  }
  function _(w, x) {
    if (x === !0) {
      const S = /<\/?([a-zA-Z][a-zA-Z0-9-]*)([\s>])/g;
      return w.replace(S, (D, T, I) => OC.includes(T.toLowerCase()) ? D : D.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
    }
    if (Array.isArray(x)) {
      const S = x.map((T) => ({
        open: new RegExp(`<(${T})(\\s+[^>]*)?>`, "gi"),
        close: new RegExp(`</(${T})>`, "gi")
      }));
      let D = w;
      return S.forEach((T) => {
        D = D.replace(T.open, (I) => I.replace(/</g, "&lt;").replace(/>/g, "&gt;")), D = D.replace(T.close, (I) => I.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
      }), D;
    }
    return w;
  }
  function b(w) {
    let x = w;
    if (a) {
      const S = [];
      l.forEach((D, T) => {
        const I = qp(D.left), U = qp(D.right), Te = new RegExp(`${I}([\\s\\S]+?)${U}`, "g");
        x = x.replace(Te, (ce, fe) => (S.push(ce), `%%%LATEX_BLOCK_${S.length - 1}%%%`));
      }), x = g.parse(x), x = x.replace(/%%%LATEX_BLOCK_(\d+)%%%/g, (D, T) => S[parseInt(T, 10)]);
    }
    return u && (x = _(x, u)), s && zp && (x = zp(x)), x;
  }
  function k(w) {
    return r(this, void 0, void 0, function* () {
      if (l.length > 0 && w && y(w))
        if (!m)
          yield Promise.all([
            Promise.resolve({              }),
            import("./auto-render-BwaQGe8P.js")
          ]).then(([, { default: x }]) => {
            m = !0, x(f, {
              delimiters: l,
              throwOnError: !1
            });
          });
        else {
          const { default: x } = yield import("./auto-render-BwaQGe8P.js");
          x(f, {
            delimiters: l,
            throwOnError: !1
          });
        }
      if (f) {
        const x = f.querySelectorAll(".mermaid");
        if (x.length > 0) {
          yield qC();
          const { default: S } = yield import("./mermaid.core-DVZvGj-F.js").then((D) => D.bB);
          S.initialize({
            startOnLoad: !1,
            theme: h === "dark" ? "dark" : "default",
            securityLevel: "antiscript"
          }), yield S.run({
            nodes: Array.from(x).map((D) => D)
          });
        }
      }
    });
  }
  UC(() => r(void 0, void 0, void 0, function* () {
    f && document.body.contains(f) ? yield k(o) : console.error("Element is not in the DOM");
  }));
  function C(w) {
    IC[w ? "unshift" : "push"](() => {
      f = w, t(2, f);
    });
  }
  return n.$$set = (w) => {
    "chatbot" in w && t(0, i = w.chatbot), "message" in w && t(4, o = w.message), "sanitize_html" in w && t(5, s = w.sanitize_html), "latex_delimiters" in w && t(6, l = w.latex_delimiters), "render_markdown" in w && t(1, a = w.render_markdown), "line_breaks" in w && t(7, c = w.line_breaks), "header_links" in w && t(8, d = w.header_links), "allow_tags" in w && t(9, u = w.allow_tags), "theme_mode" in w && t(10, h = w.theme_mode);
  }, n.$$.update = () => {
    n.$$.dirty & /*message*/
    16 && (o && o.trim() ? t(3, p = b(o)) : t(3, p = ""));
  }, [
    i,
    a,
    f,
    p,
    o,
    s,
    l,
    c,
    d,
    u,
    h,
    C
  ];
}
class GC extends NC {
  constructor(e) {
    super(), zC(this, e, WC, jC, VC, {
      chatbot: 0,
      message: 4,
      sanitize_html: 5,
      latex_delimiters: 6,
      render_markdown: 1,
      line_breaks: 7,
      header_links: 8,
      allow_tags: 9,
      theme_mode: 10
    });
  }
}
const {
  SvelteComponent: KC,
  attr: JC,
  children: YC,
  claim_component: XC,
  claim_element: ZC,
  create_component: QC,
  destroy_component: eS,
  detach: jp,
  element: tS,
  init: nS,
  insert_hydration: rS,
  mount_component: iS,
  safe_not_equal: oS,
  transition_in: sS,
  transition_out: lS
} = window.__gradio__svelte__internal;
function aS(n) {
  let e, t, r;
  return t = new GC({
    props: {
      message: (
        /*info*/
        n[0]
      ),
      sanitize_html: !0
    }
  }), {
    c() {
      e = tS("div"), QC(t.$$.fragment), this.h();
    },
    l(i) {
      e = ZC(i, "DIV", { class: !0 });
      var o = YC(e);
      XC(t.$$.fragment, o), o.forEach(jp), this.h();
    },
    h() {
      JC(e, "class", "svelte-17qq50w");
    },
    m(i, o) {
      rS(i, e, o), iS(t, e, null), r = !0;
    },
    p(i, [o]) {
      const s = {};
      o & /*info*/
      1 && (s.message = /*info*/
      i[0]), t.$set(s);
    },
    i(i) {
      r || (sS(t.$$.fragment, i), r = !0);
    },
    o(i) {
      lS(t.$$.fragment, i), r = !1;
    },
    d(i) {
      i && jp(e), eS(t);
    }
  };
}
function cS(n, e, t) {
  let { info: r } = e;
  return n.$$set = (i) => {
    "info" in i && t(0, r = i.info);
  }, [r];
}
class dS extends KC {
  constructor(e) {
    super(), nS(this, e, cS, aS, oS, { info: 0 });
  }
}
const {
  SvelteComponent: uS,
  attr: al,
  check_outros: hS,
  children: fS,
  claim_component: pS,
  claim_element: mS,
  claim_space: gS,
  create_component: bS,
  create_slot: yS,
  destroy_component: _S,
  detach: cl,
  element: wS,
  empty: Wp,
  get_all_dirty_from_scope: kS,
  get_slot_changes: vS,
  group_outros: CS,
  init: SS,
  insert_hydration: rd,
  mount_component: ES,
  safe_not_equal: xS,
  space: DS,
  toggle_class: Ri,
  transition_in: Ro,
  transition_out: Ul,
  update_slot_base: AS
} = window.__gradio__svelte__internal;
function Gp(n) {
  let e, t;
  return e = new dS({ props: { info: (
    /*info*/
    n[1]
  ) } }), {
    c() {
      bS(e.$$.fragment);
    },
    l(r) {
      pS(e.$$.fragment, r);
    },
    m(r, i) {
      ES(e, r, i), t = !0;
    },
    p(r, i) {
      const o = {};
      i & /*info*/
      2 && (o.info = /*info*/
      r[1]), e.$set(o);
    },
    i(r) {
      t || (Ro(e.$$.fragment, r), t = !0);
    },
    o(r) {
      Ul(e.$$.fragment, r), t = !1;
    },
    d(r) {
      _S(e, r);
    }
  };
}
function TS(n) {
  let e, t, r, i, o;
  const s = (
    /*#slots*/
    n[4].default
  ), l = yS(
    s,
    n,
    /*$$scope*/
    n[3],
    null
  );
  let a = (
    /*info*/
    n[1] && Gp(n)
  );
  return {
    c() {
      e = wS("span"), l && l.c(), r = DS(), a && a.c(), i = Wp(), this.h();
    },
    l(c) {
      e = mS(c, "SPAN", {
        "data-testid": !0,
        dir: !0,
        class: !0
      });
      var d = fS(e);
      l && l.l(d), d.forEach(cl), r = gS(c), a && a.l(c), i = Wp(), this.h();
    },
    h() {
      al(e, "data-testid", "block-info"), al(e, "dir", t = /*rtl*/
      n[2] ? "rtl" : "ltr"), al(e, "class", "svelte-zgrq3"), Ri(e, "sr-only", !/*show_label*/
      n[0]), Ri(e, "hide", !/*show_label*/
      n[0]), Ri(
        e,
        "has-info",
        /*info*/
        n[1] != null
      );
    },
    m(c, d) {
      rd(c, e, d), l && l.m(e, null), rd(c, r, d), a && a.m(c, d), rd(c, i, d), o = !0;
    },
    p(c, [d]) {
      l && l.p && (!o || d & /*$$scope*/
      8) && AS(
        l,
        s,
        c,
        /*$$scope*/
        c[3],
        o ? vS(
          s,
          /*$$scope*/
          c[3],
          d,
          null
        ) : kS(
          /*$$scope*/
          c[3]
        ),
        null
      ), (!o || d & /*rtl*/
      4 && t !== (t = /*rtl*/
      c[2] ? "rtl" : "ltr")) && al(e, "dir", t), (!o || d & /*show_label*/
      1) && Ri(e, "sr-only", !/*show_label*/
      c[0]), (!o || d & /*show_label*/
      1) && Ri(e, "hide", !/*show_label*/
      c[0]), (!o || d & /*info*/
      2) && Ri(
        e,
        "has-info",
        /*info*/
        c[1] != null
      ), /*info*/
      c[1] ? a ? (a.p(c, d), d & /*info*/
      2 && Ro(a, 1)) : (a = Gp(c), a.c(), Ro(a, 1), a.m(i.parentNode, i)) : a && (CS(), Ul(a, 1, 1, () => {
        a = null;
      }), hS());
    },
    i(c) {
      o || (Ro(l, c), Ro(a), o = !0);
    },
    o(c) {
      Ul(l, c), Ul(a), o = !1;
    },
    d(c) {
      c && (cl(e), cl(r), cl(i)), l && l.d(c), a && a.d(c);
    }
  };
}
function MS(n, e, t) {
  let { $$slots: r = {}, $$scope: i } = e, { show_label: o = !0 } = e, { info: s = void 0 } = e, { rtl: l = !1 } = e;
  return n.$$set = (a) => {
    "show_label" in a && t(0, o = a.show_label), "info" in a && t(1, s = a.info), "rtl" in a && t(2, l = a.rtl), "$$scope" in a && t(3, i = a.$$scope);
  }, [o, s, l, i, r];
}
class OS extends uS {
  constructor(e) {
    super(), SS(this, e, MS, TS, xS, { show_label: 0, info: 1, rtl: 2 });
  }
}
const {
  SvelteComponent: KP,
  append_hydration: JP,
  attr: YP,
  children: XP,
  claim_component: ZP,
  claim_element: QP,
  claim_space: e3,
  claim_text: t3,
  create_component: n3,
  destroy_component: r3,
  detach: i3,
  element: o3,
  init: s3,
  insert_hydration: l3,
  mount_component: a3,
  safe_not_equal: c3,
  set_data: d3,
  space: u3,
  text: h3,
  toggle_class: f3,
  transition_in: p3,
  transition_out: m3
} = window.__gradio__svelte__internal, {
  SvelteComponent: FS,
  append_hydration: ql,
  attr: Wn,
  bubble: NS,
  check_outros: $S,
  children: su,
  claim_component: IS,
  claim_element: lu,
  claim_space: Kp,
  claim_text: LS,
  construct_svelte_component: Jp,
  create_component: Yp,
  create_slot: RS,
  destroy_component: Xp,
  detach: Ko,
  element: au,
  get_all_dirty_from_scope: BS,
  get_slot_changes: PS,
  group_outros: zS,
  init: HS,
  insert_hydration: Gb,
  listen: VS,
  mount_component: Zp,
  safe_not_equal: US,
  set_data: qS,
  set_style: dl,
  space: Qp,
  text: jS,
  toggle_class: Qe,
  transition_in: id,
  transition_out: od,
  update_slot_base: WS
} = window.__gradio__svelte__internal;
function em(n) {
  let e, t;
  return {
    c() {
      e = au("span"), t = jS(
        /*label*/
        n[1]
      ), this.h();
    },
    l(r) {
      e = lu(r, "SPAN", { class: !0 });
      var i = su(e);
      t = LS(
        i,
        /*label*/
        n[1]
      ), i.forEach(Ko), this.h();
    },
    h() {
      Wn(e, "class", "svelte-qgco6m");
    },
    m(r, i) {
      Gb(r, e, i), ql(e, t);
    },
    p(r, i) {
      i & /*label*/
      2 && qS(
        t,
        /*label*/
        r[1]
      );
    },
    d(r) {
      r && Ko(e);
    }
  };
}
function GS(n) {
  let e, t, r, i, o, s, l, a, c = (
    /*show_label*/
    n[2] && em(n)
  );
  var d = (
    /*Icon*/
    n[0]
  );
  function u(p, m) {
    return {};
  }
  d && (i = Jp(d, u()));
  const h = (
    /*#slots*/
    n[14].default
  ), f = RS(
    h,
    n,
    /*$$scope*/
    n[13],
    null
  );
  return {
    c() {
      e = au("button"), c && c.c(), t = Qp(), r = au("div"), i && Yp(i.$$.fragment), o = Qp(), f && f.c(), this.h();
    },
    l(p) {
      e = lu(p, "BUTTON", {
        "aria-label": !0,
        "aria-haspopup": !0,
        title: !0,
        class: !0
      });
      var m = su(e);
      c && c.l(m), t = Kp(m), r = lu(m, "DIV", { class: !0 });
      var g = su(r);
      i && IS(i.$$.fragment, g), o = Kp(g), f && f.l(g), g.forEach(Ko), m.forEach(Ko), this.h();
    },
    h() {
      Wn(r, "class", "svelte-qgco6m"), Qe(
        r,
        "x-small",
        /*size*/
        n[4] === "x-small"
      ), Qe(
        r,
        "small",
        /*size*/
        n[4] === "small"
      ), Qe(
        r,
        "large",
        /*size*/
        n[4] === "large"
      ), Qe(
        r,
        "medium",
        /*size*/
        n[4] === "medium"
      ), e.disabled = /*disabled*/
      n[7], Wn(
        e,
        "aria-label",
        /*label*/
        n[1]
      ), Wn(
        e,
        "aria-haspopup",
        /*hasPopup*/
        n[8]
      ), Wn(
        e,
        "title",
        /*label*/
        n[1]
      ), Wn(e, "class", "svelte-qgco6m"), Qe(
        e,
        "pending",
        /*pending*/
        n[3]
      ), Qe(
        e,
        "padded",
        /*padded*/
        n[5]
      ), Qe(
        e,
        "highlight",
        /*highlight*/
        n[6]
      ), Qe(
        e,
        "transparent",
        /*transparent*/
        n[9]
      ), dl(e, "color", !/*disabled*/
      n[7] && /*_color*/
      n[11] ? (
        /*_color*/
        n[11]
      ) : "var(--block-label-text-color)"), dl(e, "--bg-color", /*disabled*/
      n[7] ? "auto" : (
        /*background*/
        n[10]
      ));
    },
    m(p, m) {
      Gb(p, e, m), c && c.m(e, null), ql(e, t), ql(e, r), i && Zp(i, r, null), ql(r, o), f && f.m(r, null), s = !0, l || (a = VS(
        e,
        "click",
        /*click_handler*/
        n[15]
      ), l = !0);
    },
    p(p, [m]) {
      if (/*show_label*/
      p[2] ? c ? c.p(p, m) : (c = em(p), c.c(), c.m(e, t)) : c && (c.d(1), c = null), m & /*Icon*/
      1 && d !== (d = /*Icon*/
      p[0])) {
        if (i) {
          zS();
          const g = i;
          od(g.$$.fragment, 1, 0, () => {
            Xp(g, 1);
          }), $S();
        }
        d ? (i = Jp(d, u()), Yp(i.$$.fragment), id(i.$$.fragment, 1), Zp(i, r, o)) : i = null;
      }
      f && f.p && (!s || m & /*$$scope*/
      8192) && WS(
        f,
        h,
        p,
        /*$$scope*/
        p[13],
        s ? PS(
          h,
          /*$$scope*/
          p[13],
          m,
          null
        ) : BS(
          /*$$scope*/
          p[13]
        ),
        null
      ), (!s || m & /*size*/
      16) && Qe(
        r,
        "x-small",
        /*size*/
        p[4] === "x-small"
      ), (!s || m & /*size*/
      16) && Qe(
        r,
        "small",
        /*size*/
        p[4] === "small"
      ), (!s || m & /*size*/
      16) && Qe(
        r,
        "large",
        /*size*/
        p[4] === "large"
      ), (!s || m & /*size*/
      16) && Qe(
        r,
        "medium",
        /*size*/
        p[4] === "medium"
      ), (!s || m & /*disabled*/
      128) && (e.disabled = /*disabled*/
      p[7]), (!s || m & /*label*/
      2) && Wn(
        e,
        "aria-label",
        /*label*/
        p[1]
      ), (!s || m & /*hasPopup*/
      256) && Wn(
        e,
        "aria-haspopup",
        /*hasPopup*/
        p[8]
      ), (!s || m & /*label*/
      2) && Wn(
        e,
        "title",
        /*label*/
        p[1]
      ), (!s || m & /*pending*/
      8) && Qe(
        e,
        "pending",
        /*pending*/
        p[3]
      ), (!s || m & /*padded*/
      32) && Qe(
        e,
        "padded",
        /*padded*/
        p[5]
      ), (!s || m & /*highlight*/
      64) && Qe(
        e,
        "highlight",
        /*highlight*/
        p[6]
      ), (!s || m & /*transparent*/
      512) && Qe(
        e,
        "transparent",
        /*transparent*/
        p[9]
      ), m & /*disabled, _color*/
      2176 && dl(e, "color", !/*disabled*/
      p[7] && /*_color*/
      p[11] ? (
        /*_color*/
        p[11]
      ) : "var(--block-label-text-color)"), m & /*disabled, background*/
      1152 && dl(e, "--bg-color", /*disabled*/
      p[7] ? "auto" : (
        /*background*/
        p[10]
      ));
    },
    i(p) {
      s || (i && id(i.$$.fragment, p), id(f, p), s = !0);
    },
    o(p) {
      i && od(i.$$.fragment, p), od(f, p), s = !1;
    },
    d(p) {
      p && Ko(e), c && c.d(), i && Xp(i), f && f.d(p), l = !1, a();
    }
  };
}
function KS(n, e, t) {
  let r, { $$slots: i = {}, $$scope: o } = e, { Icon: s } = e, { label: l = "" } = e, { show_label: a = !1 } = e, { pending: c = !1 } = e, { size: d = "small" } = e, { padded: u = !0 } = e, { highlight: h = !1 } = e, { disabled: f = !1 } = e, { hasPopup: p = !1 } = e, { color: m = "var(--block-label-text-color)" } = e, { transparent: g = !1 } = e, { background: y = "var(--block-background-fill)" } = e;
  function _(b) {
    NS.call(this, n, b);
  }
  return n.$$set = (b) => {
    "Icon" in b && t(0, s = b.Icon), "label" in b && t(1, l = b.label), "show_label" in b && t(2, a = b.show_label), "pending" in b && t(3, c = b.pending), "size" in b && t(4, d = b.size), "padded" in b && t(5, u = b.padded), "highlight" in b && t(6, h = b.highlight), "disabled" in b && t(7, f = b.disabled), "hasPopup" in b && t(8, p = b.hasPopup), "color" in b && t(12, m = b.color), "transparent" in b && t(9, g = b.transparent), "background" in b && t(10, y = b.background), "$$scope" in b && t(13, o = b.$$scope);
  }, n.$$.update = () => {
    n.$$.dirty & /*highlight, color*/
    4160 && t(11, r = h ? "var(--color-accent)" : m);
  }, [
    s,
    l,
    a,
    c,
    d,
    u,
    h,
    f,
    p,
    g,
    y,
    r,
    m,
    o,
    i,
    _
  ];
}
class JS extends FS {
  constructor(e) {
    super(), HS(this, e, KS, GS, US, {
      Icon: 0,
      label: 1,
      show_label: 2,
      pending: 3,
      size: 4,
      padded: 5,
      highlight: 6,
      disabled: 7,
      hasPopup: 8,
      color: 12,
      transparent: 9,
      background: 10
    });
  }
}
const {
  SvelteComponent: g3,
  append_hydration: b3,
  attr: y3,
  binding_callbacks: _3,
  children: w3,
  claim_element: k3,
  create_slot: v3,
  detach: C3,
  element: S3,
  get_all_dirty_from_scope: E3,
  get_slot_changes: x3,
  init: D3,
  insert_hydration: A3,
  safe_not_equal: T3,
  toggle_class: M3,
  transition_in: O3,
  transition_out: F3,
  update_slot_base: N3
} = window.__gradio__svelte__internal, {
  SvelteComponent: $3,
  append_hydration: I3,
  attr: L3,
  children: R3,
  claim_svg_element: B3,
  detach: P3,
  init: z3,
  insert_hydration: H3,
  noop: V3,
  safe_not_equal: U3,
  svg_element: q3
} = window.__gradio__svelte__internal, {
  SvelteComponent: j3,
  append_hydration: W3,
  attr: G3,
  children: K3,
  claim_svg_element: J3,
  detach: Y3,
  init: X3,
  insert_hydration: Z3,
  noop: Q3,
  safe_not_equal: e4,
  svg_element: t4
} = window.__gradio__svelte__internal, {
  SvelteComponent: n4,
  append_hydration: r4,
  attr: i4,
  children: o4,
  claim_svg_element: s4,
  detach: l4,
  init: a4,
  insert_hydration: c4,
  noop: d4,
  safe_not_equal: u4,
  svg_element: h4
} = window.__gradio__svelte__internal, {
  SvelteComponent: f4,
  append_hydration: p4,
  attr: m4,
  children: g4,
  claim_svg_element: b4,
  detach: y4,
  init: _4,
  insert_hydration: w4,
  noop: k4,
  safe_not_equal: v4,
  svg_element: C4
} = window.__gradio__svelte__internal, {
  SvelteComponent: S4,
  append_hydration: E4,
  attr: x4,
  children: D4,
  claim_svg_element: A4,
  detach: T4,
  init: M4,
  insert_hydration: O4,
  noop: F4,
  safe_not_equal: N4,
  svg_element: $4
} = window.__gradio__svelte__internal, {
  SvelteComponent: I4,
  append_hydration: L4,
  attr: R4,
  children: B4,
  claim_svg_element: P4,
  detach: z4,
  init: H4,
  insert_hydration: V4,
  noop: U4,
  safe_not_equal: q4,
  svg_element: j4
} = window.__gradio__svelte__internal, {
  SvelteComponent: W4,
  append_hydration: G4,
  attr: K4,
  children: J4,
  claim_svg_element: Y4,
  detach: X4,
  init: Z4,
  insert_hydration: Q4,
  noop: e5,
  safe_not_equal: t5,
  svg_element: n5
} = window.__gradio__svelte__internal, {
  SvelteComponent: r5,
  append_hydration: i5,
  attr: o5,
  children: s5,
  claim_svg_element: l5,
  detach: a5,
  init: c5,
  insert_hydration: d5,
  noop: u5,
  safe_not_equal: h5,
  svg_element: f5
} = window.__gradio__svelte__internal, {
  SvelteComponent: p5,
  append_hydration: m5,
  attr: g5,
  children: b5,
  claim_svg_element: y5,
  detach: _5,
  init: w5,
  insert_hydration: k5,
  noop: v5,
  safe_not_equal: C5,
  svg_element: S5
} = window.__gradio__svelte__internal, {
  SvelteComponent: E5,
  append_hydration: x5,
  attr: D5,
  children: A5,
  claim_svg_element: T5,
  detach: M5,
  init: O5,
  insert_hydration: F5,
  noop: N5,
  safe_not_equal: $5,
  svg_element: I5
} = window.__gradio__svelte__internal, {
  SvelteComponent: L5,
  append_hydration: R5,
  attr: B5,
  children: P5,
  claim_svg_element: z5,
  detach: H5,
  init: V5,
  insert_hydration: U5,
  noop: q5,
  safe_not_equal: j5,
  svg_element: W5
} = window.__gradio__svelte__internal, {
  SvelteComponent: G5,
  append_hydration: K5,
  attr: J5,
  children: Y5,
  claim_svg_element: X5,
  detach: Z5,
  init: Q5,
  insert_hydration: e8,
  noop: t8,
  safe_not_equal: n8,
  svg_element: r8
} = window.__gradio__svelte__internal, {
  SvelteComponent: YS,
  append_hydration: sd,
  attr: Qt,
  children: ul,
  claim_svg_element: hl,
  detach: Ao,
  init: XS,
  insert_hydration: ZS,
  noop: ld,
  safe_not_equal: QS,
  set_style: _n,
  svg_element: fl
} = window.__gradio__svelte__internal;
function eE(n) {
  let e, t, r, i;
  return {
    c() {
      e = fl("svg"), t = fl("g"), r = fl("path"), i = fl("path"), this.h();
    },
    l(o) {
      e = hl(o, "svg", {
        width: !0,
        height: !0,
        viewBox: !0,
        version: !0,
        xmlns: !0,
        "xmlns:xlink": !0,
        "xml:space": !0,
        stroke: !0,
        style: !0
      });
      var s = ul(e);
      t = hl(s, "g", { transform: !0 });
      var l = ul(t);
      r = hl(l, "path", { d: !0, style: !0 }), ul(r).forEach(Ao), l.forEach(Ao), i = hl(s, "path", { d: !0, style: !0 }), ul(i).forEach(Ao), s.forEach(Ao), this.h();
    },
    h() {
      Qt(r, "d", "M18,6L6.087,17.913"), _n(r, "fill", "none"), _n(r, "fill-rule", "nonzero"), _n(r, "stroke-width", "2px"), Qt(t, "transform", "matrix(1.14096,-0.140958,-0.140958,1.14096,-0.0559523,0.0559523)"), Qt(i, "d", "M4.364,4.364L19.636,19.636"), _n(i, "fill", "none"), _n(i, "fill-rule", "nonzero"), _n(i, "stroke-width", "2px"), Qt(e, "width", "100%"), Qt(e, "height", "100%"), Qt(e, "viewBox", "0 0 24 24"), Qt(e, "version", "1.1"), Qt(e, "xmlns", "http://www.w3.org/2000/svg"), Qt(e, "xmlns:xlink", "http://www.w3.org/1999/xlink"), Qt(e, "xml:space", "preserve"), Qt(e, "stroke", "currentColor"), _n(e, "fill-rule", "evenodd"), _n(e, "clip-rule", "evenodd"), _n(e, "stroke-linecap", "round"), _n(e, "stroke-linejoin", "round");
    },
    m(o, s) {
      ZS(o, e, s), sd(e, t), sd(t, r), sd(e, i);
    },
    p: ld,
    i: ld,
    o: ld,
    d(o) {
      o && Ao(e);
    }
  };
}
class tE extends YS {
  constructor(e) {
    super(), XS(this, e, null, eE, QS, {});
  }
}
const {
  SvelteComponent: i8,
  append_hydration: o8,
  attr: s8,
  children: l8,
  claim_svg_element: a8,
  detach: c8,
  init: d8,
  insert_hydration: u8,
  noop: h8,
  safe_not_equal: f8,
  svg_element: p8
} = window.__gradio__svelte__internal, {
  SvelteComponent: m8,
  append_hydration: g8,
  attr: b8,
  children: y8,
  claim_svg_element: _8,
  detach: w8,
  init: k8,
  insert_hydration: v8,
  noop: C8,
  safe_not_equal: S8,
  svg_element: E8
} = window.__gradio__svelte__internal, {
  SvelteComponent: x8,
  append_hydration: D8,
  attr: A8,
  children: T8,
  claim_svg_element: M8,
  detach: O8,
  init: F8,
  insert_hydration: N8,
  noop: $8,
  safe_not_equal: I8,
  svg_element: L8
} = window.__gradio__svelte__internal, {
  SvelteComponent: R8,
  append_hydration: B8,
  attr: P8,
  children: z8,
  claim_svg_element: H8,
  detach: V8,
  init: U8,
  insert_hydration: q8,
  noop: j8,
  safe_not_equal: W8,
  svg_element: G8
} = window.__gradio__svelte__internal, {
  SvelteComponent: K8,
  append_hydration: J8,
  attr: Y8,
  children: X8,
  claim_svg_element: Z8,
  detach: Q8,
  init: ez,
  insert_hydration: tz,
  noop: nz,
  safe_not_equal: rz,
  svg_element: iz
} = window.__gradio__svelte__internal, {
  SvelteComponent: oz,
  append_hydration: sz,
  attr: lz,
  children: az,
  claim_svg_element: cz,
  detach: dz,
  init: uz,
  insert_hydration: hz,
  noop: fz,
  safe_not_equal: pz,
  svg_element: mz
} = window.__gradio__svelte__internal, {
  SvelteComponent: gz,
  append_hydration: bz,
  attr: yz,
  children: _z,
  claim_svg_element: wz,
  detach: kz,
  init: vz,
  insert_hydration: Cz,
  noop: Sz,
  safe_not_equal: Ez,
  svg_element: xz
} = window.__gradio__svelte__internal, {
  SvelteComponent: Dz,
  append_hydration: Az,
  attr: Tz,
  children: Mz,
  claim_svg_element: Oz,
  detach: Fz,
  init: Nz,
  insert_hydration: $z,
  noop: Iz,
  safe_not_equal: Lz,
  svg_element: Rz
} = window.__gradio__svelte__internal, {
  SvelteComponent: Bz,
  append_hydration: Pz,
  attr: zz,
  children: Hz,
  claim_svg_element: Vz,
  detach: Uz,
  init: qz,
  insert_hydration: jz,
  noop: Wz,
  safe_not_equal: Gz,
  svg_element: Kz
} = window.__gradio__svelte__internal, {
  SvelteComponent: Jz,
  append_hydration: Yz,
  attr: Xz,
  children: Zz,
  claim_svg_element: Qz,
  detach: e9,
  init: t9,
  insert_hydration: n9,
  noop: r9,
  safe_not_equal: i9,
  svg_element: o9
} = window.__gradio__svelte__internal, {
  SvelteComponent: s9,
  append_hydration: l9,
  attr: a9,
  children: c9,
  claim_svg_element: d9,
  detach: u9,
  init: h9,
  insert_hydration: f9,
  noop: p9,
  safe_not_equal: m9,
  svg_element: g9
} = window.__gradio__svelte__internal, {
  SvelteComponent: b9,
  append_hydration: y9,
  attr: _9,
  children: w9,
  claim_svg_element: k9,
  detach: v9,
  init: C9,
  insert_hydration: S9,
  noop: E9,
  safe_not_equal: x9,
  svg_element: D9
} = window.__gradio__svelte__internal, {
  SvelteComponent: A9,
  append_hydration: T9,
  attr: M9,
  children: O9,
  claim_svg_element: F9,
  detach: N9,
  init: $9,
  insert_hydration: I9,
  noop: L9,
  safe_not_equal: R9,
  svg_element: B9
} = window.__gradio__svelte__internal, {
  SvelteComponent: P9,
  append_hydration: z9,
  attr: H9,
  children: V9,
  claim_svg_element: U9,
  detach: q9,
  init: j9,
  insert_hydration: W9,
  noop: G9,
  safe_not_equal: K9,
  svg_element: J9
} = window.__gradio__svelte__internal, {
  SvelteComponent: Y9,
  append_hydration: X9,
  attr: Z9,
  children: Q9,
  claim_svg_element: eH,
  detach: tH,
  init: nH,
  insert_hydration: rH,
  noop: iH,
  safe_not_equal: oH,
  svg_element: sH
} = window.__gradio__svelte__internal, {
  SvelteComponent: lH,
  append_hydration: aH,
  attr: cH,
  children: dH,
  claim_svg_element: uH,
  detach: hH,
  init: fH,
  insert_hydration: pH,
  noop: mH,
  safe_not_equal: gH,
  svg_element: bH
} = window.__gradio__svelte__internal, {
  SvelteComponent: yH,
  append_hydration: _H,
  attr: wH,
  children: kH,
  claim_svg_element: vH,
  detach: CH,
  init: SH,
  insert_hydration: EH,
  noop: xH,
  safe_not_equal: DH,
  svg_element: AH
} = window.__gradio__svelte__internal, {
  SvelteComponent: TH,
  append_hydration: MH,
  attr: OH,
  children: FH,
  claim_svg_element: NH,
  detach: $H,
  init: IH,
  insert_hydration: LH,
  noop: RH,
  safe_not_equal: BH,
  svg_element: PH
} = window.__gradio__svelte__internal, {
  SvelteComponent: zH,
  append_hydration: HH,
  attr: VH,
  children: UH,
  claim_svg_element: qH,
  detach: jH,
  init: WH,
  insert_hydration: GH,
  noop: KH,
  safe_not_equal: JH,
  svg_element: YH
} = window.__gradio__svelte__internal, {
  SvelteComponent: XH,
  append_hydration: ZH,
  attr: QH,
  children: e6,
  claim_svg_element: t6,
  detach: n6,
  init: r6,
  insert_hydration: i6,
  noop: o6,
  safe_not_equal: s6,
  svg_element: l6
} = window.__gradio__svelte__internal, {
  SvelteComponent: a6,
  append_hydration: c6,
  attr: d6,
  children: u6,
  claim_svg_element: h6,
  detach: f6,
  init: p6,
  insert_hydration: m6,
  noop: g6,
  safe_not_equal: b6,
  svg_element: y6
} = window.__gradio__svelte__internal, {
  SvelteComponent: _6,
  append_hydration: w6,
  attr: k6,
  children: v6,
  claim_svg_element: C6,
  detach: S6,
  init: E6,
  insert_hydration: x6,
  noop: D6,
  safe_not_equal: A6,
  svg_element: T6
} = window.__gradio__svelte__internal, {
  SvelteComponent: M6,
  append_hydration: O6,
  attr: F6,
  children: N6,
  claim_svg_element: $6,
  detach: I6,
  init: L6,
  insert_hydration: R6,
  noop: B6,
  safe_not_equal: P6,
  svg_element: z6
} = window.__gradio__svelte__internal, {
  SvelteComponent: H6,
  append_hydration: V6,
  attr: U6,
  children: q6,
  claim_svg_element: j6,
  detach: W6,
  init: G6,
  insert_hydration: K6,
  noop: J6,
  safe_not_equal: Y6,
  svg_element: X6
} = window.__gradio__svelte__internal, {
  SvelteComponent: Z6,
  append_hydration: Q6,
  attr: e7,
  children: t7,
  claim_svg_element: n7,
  detach: r7,
  init: i7,
  insert_hydration: o7,
  noop: s7,
  safe_not_equal: l7,
  svg_element: a7
} = window.__gradio__svelte__internal, {
  SvelteComponent: c7,
  append_hydration: d7,
  attr: u7,
  children: h7,
  claim_svg_element: f7,
  detach: p7,
  init: m7,
  insert_hydration: g7,
  noop: b7,
  safe_not_equal: y7,
  svg_element: _7
} = window.__gradio__svelte__internal, {
  SvelteComponent: w7,
  append_hydration: k7,
  attr: v7,
  children: C7,
  claim_svg_element: S7,
  detach: E7,
  init: x7,
  insert_hydration: D7,
  noop: A7,
  safe_not_equal: T7,
  svg_element: M7
} = window.__gradio__svelte__internal, {
  SvelteComponent: O7,
  append_hydration: F7,
  attr: N7,
  children: $7,
  claim_svg_element: I7,
  detach: L7,
  init: R7,
  insert_hydration: B7,
  noop: P7,
  safe_not_equal: z7,
  svg_element: H7
} = window.__gradio__svelte__internal, {
  SvelteComponent: V7,
  append_hydration: U7,
  attr: q7,
  children: j7,
  claim_svg_element: W7,
  detach: G7,
  init: K7,
  insert_hydration: J7,
  noop: Y7,
  safe_not_equal: X7,
  svg_element: Z7
} = window.__gradio__svelte__internal, {
  SvelteComponent: Q7,
  append_hydration: eV,
  attr: tV,
  children: nV,
  claim_svg_element: rV,
  detach: iV,
  init: oV,
  insert_hydration: sV,
  noop: lV,
  safe_not_equal: aV,
  svg_element: cV
} = window.__gradio__svelte__internal, {
  SvelteComponent: dV,
  append_hydration: uV,
  attr: hV,
  children: fV,
  claim_svg_element: pV,
  detach: mV,
  init: gV,
  insert_hydration: bV,
  noop: yV,
  safe_not_equal: _V,
  svg_element: wV
} = window.__gradio__svelte__internal, {
  SvelteComponent: kV,
  append_hydration: vV,
  attr: CV,
  children: SV,
  claim_svg_element: EV,
  detach: xV,
  init: DV,
  insert_hydration: AV,
  noop: TV,
  safe_not_equal: MV,
  svg_element: OV
} = window.__gradio__svelte__internal, {
  SvelteComponent: FV,
  append_hydration: NV,
  attr: $V,
  children: IV,
  claim_svg_element: LV,
  detach: RV,
  init: BV,
  insert_hydration: PV,
  noop: zV,
  safe_not_equal: HV,
  svg_element: VV
} = window.__gradio__svelte__internal, {
  SvelteComponent: UV,
  append_hydration: qV,
  attr: jV,
  children: WV,
  claim_svg_element: GV,
  detach: KV,
  init: JV,
  insert_hydration: YV,
  noop: XV,
  safe_not_equal: ZV,
  svg_element: QV
} = window.__gradio__svelte__internal, {
  SvelteComponent: eU,
  append_hydration: tU,
  attr: nU,
  children: rU,
  claim_svg_element: iU,
  detach: oU,
  init: sU,
  insert_hydration: lU,
  noop: aU,
  safe_not_equal: cU,
  set_style: dU,
  svg_element: uU
} = window.__gradio__svelte__internal, {
  SvelteComponent: hU,
  append_hydration: fU,
  attr: pU,
  children: mU,
  claim_svg_element: gU,
  detach: bU,
  init: yU,
  insert_hydration: _U,
  noop: wU,
  safe_not_equal: kU,
  svg_element: vU
} = window.__gradio__svelte__internal, {
  SvelteComponent: CU,
  append_hydration: SU,
  attr: EU,
  children: xU,
  claim_svg_element: DU,
  detach: AU,
  init: TU,
  insert_hydration: MU,
  noop: OU,
  safe_not_equal: FU,
  svg_element: NU
} = window.__gradio__svelte__internal, {
  SvelteComponent: $U,
  append_hydration: IU,
  attr: LU,
  children: RU,
  claim_svg_element: BU,
  detach: PU,
  init: zU,
  insert_hydration: HU,
  noop: VU,
  safe_not_equal: UU,
  svg_element: qU
} = window.__gradio__svelte__internal, {
  SvelteComponent: jU,
  append_hydration: WU,
  attr: GU,
  children: KU,
  claim_svg_element: JU,
  detach: YU,
  init: XU,
  insert_hydration: ZU,
  noop: QU,
  safe_not_equal: eq,
  svg_element: tq
} = window.__gradio__svelte__internal, {
  SvelteComponent: nq,
  append_hydration: rq,
  attr: iq,
  children: oq,
  claim_svg_element: sq,
  detach: lq,
  init: aq,
  insert_hydration: cq,
  noop: dq,
  safe_not_equal: uq,
  svg_element: hq
} = window.__gradio__svelte__internal, {
  SvelteComponent: fq,
  append_hydration: pq,
  attr: mq,
  children: gq,
  claim_svg_element: bq,
  detach: yq,
  init: _q,
  insert_hydration: wq,
  noop: kq,
  safe_not_equal: vq,
  svg_element: Cq
} = window.__gradio__svelte__internal, {
  SvelteComponent: Sq,
  append_hydration: Eq,
  attr: xq,
  children: Dq,
  claim_svg_element: Aq,
  detach: Tq,
  init: Mq,
  insert_hydration: Oq,
  noop: Fq,
  safe_not_equal: Nq,
  svg_element: $q
} = window.__gradio__svelte__internal, {
  SvelteComponent: Iq,
  append_hydration: Lq,
  attr: Rq,
  children: Bq,
  claim_svg_element: Pq,
  detach: zq,
  init: Hq,
  insert_hydration: Vq,
  noop: Uq,
  safe_not_equal: qq,
  svg_element: jq
} = window.__gradio__svelte__internal, {
  SvelteComponent: Wq,
  append_hydration: Gq,
  attr: Kq,
  children: Jq,
  claim_svg_element: Yq,
  claim_text: Xq,
  detach: Zq,
  init: Qq,
  insert_hydration: ej,
  noop: tj,
  safe_not_equal: nj,
  svg_element: rj,
  text: ij
} = window.__gradio__svelte__internal, {
  SvelteComponent: oj,
  append_hydration: sj,
  attr: lj,
  children: aj,
  claim_svg_element: cj,
  detach: dj,
  init: uj,
  insert_hydration: hj,
  noop: fj,
  safe_not_equal: pj,
  svg_element: mj
} = window.__gradio__svelte__internal, {
  SvelteComponent: gj,
  append_hydration: bj,
  attr: yj,
  children: _j,
  claim_svg_element: wj,
  detach: kj,
  init: vj,
  insert_hydration: Cj,
  noop: Sj,
  safe_not_equal: Ej,
  svg_element: xj
} = window.__gradio__svelte__internal, {
  SvelteComponent: Dj,
  append_hydration: Aj,
  attr: Tj,
  children: Mj,
  claim_svg_element: Oj,
  detach: Fj,
  init: Nj,
  insert_hydration: $j,
  noop: Ij,
  safe_not_equal: Lj,
  svg_element: Rj
} = window.__gradio__svelte__internal, {
  SvelteComponent: Bj,
  append_hydration: Pj,
  attr: zj,
  children: Hj,
  claim_svg_element: Vj,
  detach: Uj,
  init: qj,
  insert_hydration: jj,
  noop: Wj,
  safe_not_equal: Gj,
  svg_element: Kj
} = window.__gradio__svelte__internal, {
  SvelteComponent: Jj,
  append_hydration: Yj,
  attr: Xj,
  children: Zj,
  claim_svg_element: Qj,
  detach: eW,
  init: tW,
  insert_hydration: nW,
  noop: rW,
  safe_not_equal: iW,
  svg_element: oW
} = window.__gradio__svelte__internal, {
  SvelteComponent: sW,
  append_hydration: lW,
  attr: aW,
  children: cW,
  claim_svg_element: dW,
  detach: uW,
  init: hW,
  insert_hydration: fW,
  noop: pW,
  safe_not_equal: mW,
  svg_element: gW
} = window.__gradio__svelte__internal, {
  SvelteComponent: bW,
  append_hydration: yW,
  attr: _W,
  children: wW,
  claim_svg_element: kW,
  detach: vW,
  init: CW,
  insert_hydration: SW,
  noop: EW,
  safe_not_equal: xW,
  svg_element: DW
} = window.__gradio__svelte__internal, {
  SvelteComponent: AW,
  append_hydration: TW,
  attr: MW,
  children: OW,
  claim_svg_element: FW,
  claim_text: NW,
  detach: $W,
  init: IW,
  insert_hydration: LW,
  noop: RW,
  safe_not_equal: BW,
  svg_element: PW,
  text: zW
} = window.__gradio__svelte__internal, {
  SvelteComponent: HW,
  append_hydration: VW,
  attr: UW,
  children: qW,
  claim_svg_element: jW,
  claim_text: WW,
  detach: GW,
  init: KW,
  insert_hydration: JW,
  noop: YW,
  safe_not_equal: XW,
  svg_element: ZW,
  text: QW
} = window.__gradio__svelte__internal, {
  SvelteComponent: eG,
  append_hydration: tG,
  attr: nG,
  children: rG,
  claim_svg_element: iG,
  claim_text: oG,
  detach: sG,
  init: lG,
  insert_hydration: aG,
  noop: cG,
  safe_not_equal: dG,
  svg_element: uG,
  text: hG
} = window.__gradio__svelte__internal, {
  SvelteComponent: fG,
  append_hydration: pG,
  attr: mG,
  children: gG,
  claim_svg_element: bG,
  detach: yG,
  init: _G,
  insert_hydration: wG,
  noop: kG,
  safe_not_equal: vG,
  svg_element: CG
} = window.__gradio__svelte__internal, {
  SvelteComponent: SG,
  append_hydration: EG,
  attr: xG,
  children: DG,
  claim_svg_element: AG,
  detach: TG,
  init: MG,
  insert_hydration: OG,
  noop: FG,
  safe_not_equal: NG,
  svg_element: $G
} = window.__gradio__svelte__internal, {
  SvelteComponent: IG,
  append_hydration: LG,
  attr: RG,
  children: BG,
  claim_svg_element: PG,
  detach: zG,
  init: HG,
  insert_hydration: VG,
  noop: UG,
  safe_not_equal: qG,
  svg_element: jG
} = window.__gradio__svelte__internal, {
  SvelteComponent: WG,
  append_hydration: GG,
  attr: KG,
  children: JG,
  claim_svg_element: YG,
  detach: XG,
  init: ZG,
  insert_hydration: QG,
  noop: eK,
  safe_not_equal: tK,
  svg_element: nK
} = window.__gradio__svelte__internal, {
  SvelteComponent: rK,
  append_hydration: iK,
  attr: oK,
  children: sK,
  claim_svg_element: lK,
  detach: aK,
  init: cK,
  insert_hydration: dK,
  noop: uK,
  safe_not_equal: hK,
  svg_element: fK
} = window.__gradio__svelte__internal, {
  SvelteComponent: pK,
  append_hydration: mK,
  attr: gK,
  children: bK,
  claim_svg_element: yK,
  detach: _K,
  init: wK,
  insert_hydration: kK,
  noop: vK,
  safe_not_equal: CK,
  svg_element: SK
} = window.__gradio__svelte__internal, {
  SvelteComponent: EK,
  append_hydration: xK,
  attr: DK,
  children: AK,
  claim_svg_element: TK,
  detach: MK,
  init: OK,
  insert_hydration: FK,
  noop: NK,
  safe_not_equal: $K,
  svg_element: IK
} = window.__gradio__svelte__internal, {
  SvelteComponent: LK,
  append_hydration: RK,
  attr: BK,
  children: PK,
  claim_svg_element: zK,
  detach: HK,
  init: VK,
  insert_hydration: UK,
  noop: qK,
  safe_not_equal: jK,
  svg_element: WK
} = window.__gradio__svelte__internal, nE = [
  { color: "red", primary: 600, secondary: 100 },
  { color: "green", primary: 600, secondary: 100 },
  { color: "blue", primary: 600, secondary: 100 },
  { color: "yellow", primary: 500, secondary: 100 },
  { color: "purple", primary: 600, secondary: 100 },
  { color: "teal", primary: 600, secondary: 100 },
  { color: "orange", primary: 600, secondary: 100 },
  { color: "cyan", primary: 600, secondary: 100 },
  { color: "lime", primary: 500, secondary: 100 },
  { color: "pink", primary: 600, secondary: 100 }
], tm = {
  inherit: "inherit",
  current: "currentColor",
  transparent: "transparent",
  black: "#000",
  white: "#fff",
  slate: {
    50: "#f8fafc",
    100: "#f1f5f9",
    200: "#e2e8f0",
    300: "#cbd5e1",
    400: "#94a3b8",
    500: "#64748b",
    600: "#475569",
    700: "#334155",
    800: "#1e293b",
    900: "#0f172a",
    950: "#020617"
  },
  gray: {
    50: "#f9fafb",
    100: "#f3f4f6",
    200: "#e5e7eb",
    300: "#d1d5db",
    400: "#9ca3af",
    500: "#6b7280",
    600: "#4b5563",
    700: "#374151",
    800: "#1f2937",
    900: "#111827",
    950: "#030712"
  },
  zinc: {
    50: "#fafafa",
    100: "#f4f4f5",
    200: "#e4e4e7",
    300: "#d4d4d8",
    400: "#a1a1aa",
    500: "#71717a",
    600: "#52525b",
    700: "#3f3f46",
    800: "#27272a",
    900: "#18181b",
    950: "#09090b"
  },
  neutral: {
    50: "#fafafa",
    100: "#f5f5f5",
    200: "#e5e5e5",
    300: "#d4d4d4",
    400: "#a3a3a3",
    500: "#737373",
    600: "#525252",
    700: "#404040",
    800: "#262626",
    900: "#171717",
    950: "#0a0a0a"
  },
  stone: {
    50: "#fafaf9",
    100: "#f5f5f4",
    200: "#e7e5e4",
    300: "#d6d3d1",
    400: "#a8a29e",
    500: "#78716c",
    600: "#57534e",
    700: "#44403c",
    800: "#292524",
    900: "#1c1917",
    950: "#0c0a09"
  },
  red: {
    50: "#fef2f2",
    100: "#fee2e2",
    200: "#fecaca",
    300: "#fca5a5",
    400: "#f87171",
    500: "#ef4444",
    600: "#dc2626",
    700: "#b91c1c",
    800: "#991b1b",
    900: "#7f1d1d",
    950: "#450a0a"
  },
  orange: {
    50: "#fff7ed",
    100: "#ffedd5",
    200: "#fed7aa",
    300: "#fdba74",
    400: "#fb923c",
    500: "#f97316",
    600: "#ea580c",
    700: "#c2410c",
    800: "#9a3412",
    900: "#7c2d12",
    950: "#431407"
  },
  amber: {
    50: "#fffbeb",
    100: "#fef3c7",
    200: "#fde68a",
    300: "#fcd34d",
    400: "#fbbf24",
    500: "#f59e0b",
    600: "#d97706",
    700: "#b45309",
    800: "#92400e",
    900: "#78350f",
    950: "#451a03"
  },
  yellow: {
    50: "#fefce8",
    100: "#fef9c3",
    200: "#fef08a",
    300: "#fde047",
    400: "#facc15",
    500: "#eab308",
    600: "#ca8a04",
    700: "#a16207",
    800: "#854d0e",
    900: "#713f12",
    950: "#422006"
  },
  lime: {
    50: "#f7fee7",
    100: "#ecfccb",
    200: "#d9f99d",
    300: "#bef264",
    400: "#a3e635",
    500: "#84cc16",
    600: "#65a30d",
    700: "#4d7c0f",
    800: "#3f6212",
    900: "#365314",
    950: "#1a2e05"
  },
  green: {
    50: "#f0fdf4",
    100: "#dcfce7",
    200: "#bbf7d0",
    300: "#86efac",
    400: "#4ade80",
    500: "#22c55e",
    600: "#16a34a",
    700: "#15803d",
    800: "#166534",
    900: "#14532d",
    950: "#052e16"
  },
  emerald: {
    50: "#ecfdf5",
    100: "#d1fae5",
    200: "#a7f3d0",
    300: "#6ee7b7",
    400: "#34d399",
    500: "#10b981",
    600: "#059669",
    700: "#047857",
    800: "#065f46",
    900: "#064e3b",
    950: "#022c22"
  },
  teal: {
    50: "#f0fdfa",
    100: "#ccfbf1",
    200: "#99f6e4",
    300: "#5eead4",
    400: "#2dd4bf",
    500: "#14b8a6",
    600: "#0d9488",
    700: "#0f766e",
    800: "#115e59",
    900: "#134e4a",
    950: "#042f2e"
  },
  cyan: {
    50: "#ecfeff",
    100: "#cffafe",
    200: "#a5f3fc",
    300: "#67e8f9",
    400: "#22d3ee",
    500: "#06b6d4",
    600: "#0891b2",
    700: "#0e7490",
    800: "#155e75",
    900: "#164e63",
    950: "#083344"
  },
  sky: {
    50: "#f0f9ff",
    100: "#e0f2fe",
    200: "#bae6fd",
    300: "#7dd3fc",
    400: "#38bdf8",
    500: "#0ea5e9",
    600: "#0284c7",
    700: "#0369a1",
    800: "#075985",
    900: "#0c4a6e",
    950: "#082f49"
  },
  blue: {
    50: "#eff6ff",
    100: "#dbeafe",
    200: "#bfdbfe",
    300: "#93c5fd",
    400: "#60a5fa",
    500: "#3b82f6",
    600: "#2563eb",
    700: "#1d4ed8",
    800: "#1e40af",
    900: "#1e3a8a",
    950: "#172554"
  },
  indigo: {
    50: "#eef2ff",
    100: "#e0e7ff",
    200: "#c7d2fe",
    300: "#a5b4fc",
    400: "#818cf8",
    500: "#6366f1",
    600: "#4f46e5",
    700: "#4338ca",
    800: "#3730a3",
    900: "#312e81",
    950: "#1e1b4b"
  },
  violet: {
    50: "#f5f3ff",
    100: "#ede9fe",
    200: "#ddd6fe",
    300: "#c4b5fd",
    400: "#a78bfa",
    500: "#8b5cf6",
    600: "#7c3aed",
    700: "#6d28d9",
    800: "#5b21b6",
    900: "#4c1d95",
    950: "#2e1065"
  },
  purple: {
    50: "#faf5ff",
    100: "#f3e8ff",
    200: "#e9d5ff",
    300: "#d8b4fe",
    400: "#c084fc",
    500: "#a855f7",
    600: "#9333ea",
    700: "#7e22ce",
    800: "#6b21a8",
    900: "#581c87",
    950: "#3b0764"
  },
  fuchsia: {
    50: "#fdf4ff",
    100: "#fae8ff",
    200: "#f5d0fe",
    300: "#f0abfc",
    400: "#e879f9",
    500: "#d946ef",
    600: "#c026d3",
    700: "#a21caf",
    800: "#86198f",
    900: "#701a75",
    950: "#4a044e"
  },
  pink: {
    50: "#fdf2f8",
    100: "#fce7f3",
    200: "#fbcfe8",
    300: "#f9a8d4",
    400: "#f472b6",
    500: "#ec4899",
    600: "#db2777",
    700: "#be185d",
    800: "#9d174d",
    900: "#831843",
    950: "#500724"
  },
  rose: {
    50: "#fff1f2",
    100: "#ffe4e6",
    200: "#fecdd3",
    300: "#fda4af",
    400: "#fb7185",
    500: "#f43f5e",
    600: "#e11d48",
    700: "#be123c",
    800: "#9f1239",
    900: "#881337",
    950: "#4c0519"
  }
};
nE.reduce(
  (n, { color: e, primary: t, secondary: r }) => ({
    ...n,
    [e]: {
      primary: tm[e][t],
      secondary: tm[e][r]
    }
  }),
  {}
);
const {
  SvelteComponent: GK,
  claim_component: KK,
  create_component: JK,
  destroy_component: YK,
  init: XK,
  mount_component: ZK,
  safe_not_equal: QK,
  transition_in: eJ,
  transition_out: tJ
} = window.__gradio__svelte__internal, { createEventDispatcher: nJ } = window.__gradio__svelte__internal, {
  SvelteComponent: rJ,
  append_hydration: iJ,
  attr: oJ,
  check_outros: sJ,
  children: lJ,
  claim_component: aJ,
  claim_element: cJ,
  claim_space: dJ,
  claim_text: uJ,
  create_component: hJ,
  destroy_component: fJ,
  detach: pJ,
  element: mJ,
  empty: gJ,
  group_outros: bJ,
  init: yJ,
  insert_hydration: _J,
  mount_component: wJ,
  safe_not_equal: kJ,
  set_data: vJ,
  space: CJ,
  text: SJ,
  toggle_class: EJ,
  transition_in: xJ,
  transition_out: DJ
} = window.__gradio__svelte__internal, {
  SvelteComponent: AJ,
  attr: TJ,
  children: MJ,
  claim_element: OJ,
  create_slot: FJ,
  detach: NJ,
  element: $J,
  get_all_dirty_from_scope: IJ,
  get_slot_changes: LJ,
  init: RJ,
  insert_hydration: BJ,
  safe_not_equal: PJ,
  toggle_class: zJ,
  transition_in: HJ,
  transition_out: VJ,
  update_slot_base: UJ
} = window.__gradio__svelte__internal, {
  SvelteComponent: qJ,
  append_hydration: jJ,
  attr: WJ,
  check_outros: GJ,
  children: KJ,
  claim_component: JJ,
  claim_element: YJ,
  claim_space: XJ,
  create_component: ZJ,
  destroy_component: QJ,
  detach: eY,
  element: tY,
  empty: nY,
  group_outros: rY,
  init: iY,
  insert_hydration: oY,
  listen: sY,
  mount_component: lY,
  safe_not_equal: aY,
  space: cY,
  toggle_class: dY,
  transition_in: uY,
  transition_out: hY
} = window.__gradio__svelte__internal, {
  SvelteComponent: fY,
  attr: pY,
  children: mY,
  claim_element: gY,
  create_slot: bY,
  detach: yY,
  element: _Y,
  get_all_dirty_from_scope: wY,
  get_slot_changes: kY,
  init: vY,
  insert_hydration: CY,
  null_to_empty: SY,
  safe_not_equal: EY,
  transition_in: xY,
  transition_out: DY,
  update_slot_base: AY
} = window.__gradio__svelte__internal, {
  SvelteComponent: TY,
  check_outros: MY,
  claim_component: OY,
  create_component: FY,
  destroy_component: NY,
  detach: $Y,
  empty: IY,
  group_outros: LY,
  init: RY,
  insert_hydration: BY,
  mount_component: PY,
  noop: zY,
  safe_not_equal: HY,
  transition_in: VY,
  transition_out: UY
} = window.__gradio__svelte__internal, { createEventDispatcher: qY } = window.__gradio__svelte__internal;
function qi(n) {
  let e = ["", "k", "M", "G", "T", "P", "E", "Z"], t = 0;
  for (; n > 1e3 && t < e.length - 1; )
    n /= 1e3, t++;
  let r = e[t];
  return (Number.isInteger(n) ? n : n.toFixed(1)) + r;
}
function jl() {
}
const Kb = typeof window < "u";
let nm = Kb ? () => window.performance.now() : () => Date.now(), Jb = Kb ? (n) => requestAnimationFrame(n) : jl;
const Ki = /* @__PURE__ */ new Set();
function Yb(n) {
  Ki.forEach((e) => {
    e.c(n) || (Ki.delete(e), e.f());
  }), Ki.size !== 0 && Jb(Yb);
}
function rE(n) {
  let e;
  return Ki.size === 0 && Jb(Yb), { promise: new Promise((t) => {
    Ki.add(e = { c: n, f: t });
  }), abort() {
    Ki.delete(e);
  } };
}
const Bi = [];
function iE(n, e = jl) {
  let t;
  const r = /* @__PURE__ */ new Set();
  function i(s) {
    if (a = s, ((l = n) != l ? a == a : l !== a || l && typeof l == "object" || typeof l == "function") && (n = s, t)) {
      const c = !Bi.length;
      for (const d of r) d[1](), Bi.push(d, n);
      if (c) {
        for (let d = 0; d < Bi.length; d += 2) Bi[d][0](Bi[d + 1]);
        Bi.length = 0;
      }
    }
    var l, a;
  }
  function o(s) {
    i(s(n));
  }
  return { set: i, update: o, subscribe: function(s, l = jl) {
    const a = [s, l];
    return r.add(a), r.size === 1 && (t = e(i, o) || jl), s(n), () => {
      r.delete(a), r.size === 0 && t && (t(), t = null);
    };
  } };
}
function rm(n) {
  return Object.prototype.toString.call(n) === "[object Date]";
}
function cu(n, e, t, r) {
  if (typeof t == "number" || rm(t)) {
    const i = r - t, o = (t - e) / (n.dt || 1 / 60), s = (o + (n.opts.stiffness * i - n.opts.damping * o) * n.inv_mass) * n.dt;
    return Math.abs(s) < n.opts.precision && Math.abs(i) < n.opts.precision ? r : (n.settled = !1, rm(t) ? new Date(t.getTime() + s) : t + s);
  }
  if (Array.isArray(t)) return t.map((i, o) => cu(n, e[o], t[o], r[o]));
  if (typeof t == "object") {
    const i = {};
    for (const o in t) i[o] = cu(n, e[o], t[o], r[o]);
    return i;
  }
  throw new Error(`Cannot spring ${typeof t} values`);
}
function im(n, e = {}) {
  const t = iE(n), { stiffness: r = 0.15, damping: i = 0.8, precision: o = 0.01 } = e;
  let s, l, a, c = n, d = n, u = 1, h = 0, f = !1;
  function p(g, y = {}) {
    d = g;
    const _ = a = {};
    return n == null || y.hard || m.stiffness >= 1 && m.damping >= 1 ? (f = !0, s = nm(), c = g, t.set(n = d), Promise.resolve()) : (y.soft && (h = 1 / (60 * (y.soft === !0 ? 0.5 : +y.soft)), u = 0), l || (s = nm(), f = !1, l = rE((b) => {
      if (f) return f = !1, l = null, !1;
      u = Math.min(u + h, 1);
      const k = { inv_mass: u, opts: m, settled: !0, dt: 60 * (b - s) / 1e3 }, C = cu(k, c, n, d);
      return s = b, c = n, t.set(n = C), k.settled && (l = null), !k.settled;
    })), new Promise((b) => {
      l.promise.then(() => {
        _ === a && b();
      });
    }));
  }
  const m = { set: p, update: (g, y) => p(g(d, n), y), subscribe: t.subscribe, stiffness: r, damping: i, precision: o };
  return m;
}
const {
  SvelteComponent: oE,
  append_hydration: en,
  attr: ee,
  children: It,
  claim_element: sE,
  claim_svg_element: tn,
  component_subscribe: om,
  detach: vt,
  element: lE,
  init: aE,
  insert_hydration: cE,
  noop: sm,
  safe_not_equal: dE,
  set_style: pl,
  svg_element: nn,
  toggle_class: lm
} = window.__gradio__svelte__internal, { onMount: uE } = window.__gradio__svelte__internal;
function hE(n) {
  let e, t, r, i, o, s, l, a, c, d, u, h;
  return {
    c() {
      e = lE("div"), t = nn("svg"), r = nn("g"), i = nn("path"), o = nn("path"), s = nn("path"), l = nn("path"), a = nn("g"), c = nn("path"), d = nn("path"), u = nn("path"), h = nn("path"), this.h();
    },
    l(f) {
      e = sE(f, "DIV", { class: !0 });
      var p = It(e);
      t = tn(p, "svg", {
        viewBox: !0,
        fill: !0,
        xmlns: !0,
        class: !0
      });
      var m = It(t);
      r = tn(m, "g", { style: !0 });
      var g = It(r);
      i = tn(g, "path", {
        d: !0,
        fill: !0,
        "fill-opacity": !0,
        class: !0
      }), It(i).forEach(vt), o = tn(g, "path", { d: !0, fill: !0, class: !0 }), It(o).forEach(vt), s = tn(g, "path", {
        d: !0,
        fill: !0,
        "fill-opacity": !0,
        class: !0
      }), It(s).forEach(vt), l = tn(g, "path", { d: !0, fill: !0, class: !0 }), It(l).forEach(vt), g.forEach(vt), a = tn(m, "g", { style: !0 });
      var y = It(a);
      c = tn(y, "path", {
        d: !0,
        fill: !0,
        "fill-opacity": !0,
        class: !0
      }), It(c).forEach(vt), d = tn(y, "path", { d: !0, fill: !0, class: !0 }), It(d).forEach(vt), u = tn(y, "path", {
        d: !0,
        fill: !0,
        "fill-opacity": !0,
        class: !0
      }), It(u).forEach(vt), h = tn(y, "path", { d: !0, fill: !0, class: !0 }), It(h).forEach(vt), y.forEach(vt), m.forEach(vt), p.forEach(vt), this.h();
    },
    h() {
      ee(i, "d", "M255.926 0.754768L509.702 139.936V221.027L255.926 81.8465V0.754768Z"), ee(i, "fill", "#FF7C00"), ee(i, "fill-opacity", "0.4"), ee(i, "class", "svelte-43sxxs"), ee(o, "d", "M509.69 139.936L254.981 279.641V361.255L509.69 221.55V139.936Z"), ee(o, "fill", "#FF7C00"), ee(o, "class", "svelte-43sxxs"), ee(s, "d", "M0.250138 139.937L254.981 279.641V361.255L0.250138 221.55V139.937Z"), ee(s, "fill", "#FF7C00"), ee(s, "fill-opacity", "0.4"), ee(s, "class", "svelte-43sxxs"), ee(l, "d", "M255.923 0.232622L0.236328 139.936V221.55L255.923 81.8469V0.232622Z"), ee(l, "fill", "#FF7C00"), ee(l, "class", "svelte-43sxxs"), pl(r, "transform", "translate(" + /*$top*/
      n[1][0] + "px, " + /*$top*/
      n[1][1] + "px)"), ee(c, "d", "M255.926 141.5L509.702 280.681V361.773L255.926 222.592V141.5Z"), ee(c, "fill", "#FF7C00"), ee(c, "fill-opacity", "0.4"), ee(c, "class", "svelte-43sxxs"), ee(d, "d", "M509.69 280.679L254.981 420.384V501.998L509.69 362.293V280.679Z"), ee(d, "fill", "#FF7C00"), ee(d, "class", "svelte-43sxxs"), ee(u, "d", "M0.250138 280.681L254.981 420.386V502L0.250138 362.295V280.681Z"), ee(u, "fill", "#FF7C00"), ee(u, "fill-opacity", "0.4"), ee(u, "class", "svelte-43sxxs"), ee(h, "d", "M255.923 140.977L0.236328 280.68V362.294L255.923 222.591V140.977Z"), ee(h, "fill", "#FF7C00"), ee(h, "class", "svelte-43sxxs"), pl(a, "transform", "translate(" + /*$bottom*/
      n[2][0] + "px, " + /*$bottom*/
      n[2][1] + "px)"), ee(t, "viewBox", "-1200 -1200 3000 3000"), ee(t, "fill", "none"), ee(t, "xmlns", "http://www.w3.org/2000/svg"), ee(t, "class", "svelte-43sxxs"), ee(e, "class", "svelte-43sxxs"), lm(
        e,
        "margin",
        /*margin*/
        n[0]
      );
    },
    m(f, p) {
      cE(f, e, p), en(e, t), en(t, r), en(r, i), en(r, o), en(r, s), en(r, l), en(t, a), en(a, c), en(a, d), en(a, u), en(a, h);
    },
    p(f, [p]) {
      p & /*$top*/
      2 && pl(r, "transform", "translate(" + /*$top*/
      f[1][0] + "px, " + /*$top*/
      f[1][1] + "px)"), p & /*$bottom*/
      4 && pl(a, "transform", "translate(" + /*$bottom*/
      f[2][0] + "px, " + /*$bottom*/
      f[2][1] + "px)"), p & /*margin*/
      1 && lm(
        e,
        "margin",
        /*margin*/
        f[0]
      );
    },
    i: sm,
    o: sm,
    d(f) {
      f && vt(e);
    }
  };
}
function fE(n, e, t) {
  let r, i;
  var o = this && this.__awaiter || function(f, p, m, g) {
    function y(_) {
      return _ instanceof m ? _ : new m(function(b) {
        b(_);
      });
    }
    return new (m || (m = Promise))(function(_, b) {
      function k(x) {
        try {
          w(g.next(x));
        } catch (S) {
          b(S);
        }
      }
      function C(x) {
        try {
          w(g.throw(x));
        } catch (S) {
          b(S);
        }
      }
      function w(x) {
        x.done ? _(x.value) : y(x.value).then(k, C);
      }
      w((g = g.apply(f, p || [])).next());
    });
  };
  let { margin: s = !0 } = e;
  const l = im([0, 0]);
  om(n, l, (f) => t(1, r = f));
  const a = im([0, 0]);
  om(n, a, (f) => t(2, i = f));
  let c;
  function d() {
    return o(this, void 0, void 0, function* () {
      yield Promise.all([l.set([125, 140]), a.set([-125, -140])]), yield Promise.all([l.set([-125, 140]), a.set([125, -140])]), yield Promise.all([l.set([-125, 0]), a.set([125, -0])]), yield Promise.all([l.set([125, 0]), a.set([-125, 0])]);
    });
  }
  function u() {
    return o(this, void 0, void 0, function* () {
      yield d(), c || u();
    });
  }
  function h() {
    return o(this, void 0, void 0, function* () {
      yield Promise.all([l.set([125, 0]), a.set([-125, 0])]), u();
    });
  }
  return uE(() => (h(), () => c = !0)), n.$$set = (f) => {
    "margin" in f && t(0, s = f.margin);
  }, [s, r, i, l, a];
}
class pE extends oE {
  constructor(e) {
    super(), aE(this, e, fE, hE, dE, { margin: 0 });
  }
}
const {
  SvelteComponent: mE,
  append_hydration: Xr,
  attr: an,
  binding_callbacks: am,
  check_outros: du,
  children: xn,
  claim_component: Xb,
  claim_element: Dn,
  claim_space: qt,
  claim_text: ve,
  create_component: Zb,
  create_slot: Qb,
  destroy_component: ey,
  destroy_each: ty,
  detach: H,
  element: An,
  empty: Jt,
  ensure_array_like: da,
  get_all_dirty_from_scope: ny,
  get_slot_changes: ry,
  group_outros: uu,
  init: gE,
  insert_hydration: q,
  mount_component: iy,
  noop: hu,
  safe_not_equal: bE,
  set_data: Yt,
  set_style: Cr,
  space: jt,
  text: Ce,
  toggle_class: Pt,
  transition_in: sn,
  transition_out: Tn,
  update_slot_base: oy
} = window.__gradio__svelte__internal, { tick: yE } = window.__gradio__svelte__internal, { onDestroy: _E } = window.__gradio__svelte__internal, { createEventDispatcher: wE } = window.__gradio__svelte__internal, kE = (n) => ({}), cm = (n) => ({}), vE = (n) => ({}), dm = (n) => ({});
function um(n, e, t) {
  const r = n.slice();
  return r[40] = e[t], r[42] = t, r;
}
function hm(n, e, t) {
  const r = n.slice();
  return r[40] = e[t], r;
}
function CE(n) {
  let e, t, r, i, o = (
    /*i18n*/
    n[1]("common.error") + ""
  ), s, l, a;
  t = new JS({
    props: {
      Icon: tE,
      label: (
        /*i18n*/
        n[1]("common.clear")
      ),
      disabled: !1
    }
  }), t.$on(
    "click",
    /*click_handler*/
    n[32]
  );
  const c = (
    /*#slots*/
    n[30].error
  ), d = Qb(
    c,
    n,
    /*$$scope*/
    n[29],
    cm
  );
  return {
    c() {
      e = An("div"), Zb(t.$$.fragment), r = jt(), i = An("span"), s = Ce(o), l = jt(), d && d.c(), this.h();
    },
    l(u) {
      e = Dn(u, "DIV", { class: !0 });
      var h = xn(e);
      Xb(t.$$.fragment, h), h.forEach(H), r = qt(u), i = Dn(u, "SPAN", { class: !0 });
      var f = xn(i);
      s = ve(f, o), f.forEach(H), l = qt(u), d && d.l(u), this.h();
    },
    h() {
      an(e, "class", "clear-status svelte-17v219f"), an(i, "class", "error svelte-17v219f");
    },
    m(u, h) {
      q(u, e, h), iy(t, e, null), q(u, r, h), q(u, i, h), Xr(i, s), q(u, l, h), d && d.m(u, h), a = !0;
    },
    p(u, h) {
      const f = {};
      h[0] & /*i18n*/
      2 && (f.label = /*i18n*/
      u[1]("common.clear")), t.$set(f), (!a || h[0] & /*i18n*/
      2) && o !== (o = /*i18n*/
      u[1]("common.error") + "") && Yt(s, o), d && d.p && (!a || h[0] & /*$$scope*/
      536870912) && oy(
        d,
        c,
        u,
        /*$$scope*/
        u[29],
        a ? ry(
          c,
          /*$$scope*/
          u[29],
          h,
          kE
        ) : ny(
          /*$$scope*/
          u[29]
        ),
        cm
      );
    },
    i(u) {
      a || (sn(t.$$.fragment, u), sn(d, u), a = !0);
    },
    o(u) {
      Tn(t.$$.fragment, u), Tn(d, u), a = !1;
    },
    d(u) {
      u && (H(e), H(r), H(i), H(l)), ey(t), d && d.d(u);
    }
  };
}
function SE(n) {
  let e, t, r, i, o, s, l, a, c, d = (
    /*variant*/
    n[8] === "default" && /*show_eta_bar*/
    n[18] && /*show_progress*/
    n[6] === "full" && fm(n)
  );
  function u(b, k) {
    if (
      /*progress*/
      b[7]
    ) return DE;
    if (
      /*queue_position*/
      b[2] !== null && /*queue_size*/
      b[3] !== void 0 && /*queue_position*/
      b[2] >= 0
    ) return xE;
    if (
      /*queue_position*/
      b[2] === 0
    ) return EE;
  }
  let h = u(n), f = h && h(n), p = (
    /*timer*/
    n[5] && gm(n)
  );
  const m = [OE, ME], g = [];
  function y(b, k) {
    return (
      /*last_progress_level*/
      b[15] != null ? 0 : (
        /*show_progress*/
        b[6] === "full" ? 1 : -1
      )
    );
  }
  ~(o = y(n)) && (s = g[o] = m[o](n));
  let _ = !/*timer*/
  n[5] && Cm(n);
  return {
    c() {
      d && d.c(), e = jt(), t = An("div"), f && f.c(), r = jt(), p && p.c(), i = jt(), s && s.c(), l = jt(), _ && _.c(), a = Jt(), this.h();
    },
    l(b) {
      d && d.l(b), e = qt(b), t = Dn(b, "DIV", { class: !0 });
      var k = xn(t);
      f && f.l(k), r = qt(k), p && p.l(k), k.forEach(H), i = qt(b), s && s.l(b), l = qt(b), _ && _.l(b), a = Jt(), this.h();
    },
    h() {
      an(t, "class", "progress-text svelte-17v219f"), Pt(
        t,
        "meta-text-center",
        /*variant*/
        n[8] === "center"
      ), Pt(
        t,
        "meta-text",
        /*variant*/
        n[8] === "default"
      );
    },
    m(b, k) {
      d && d.m(b, k), q(b, e, k), q(b, t, k), f && f.m(t, null), Xr(t, r), p && p.m(t, null), q(b, i, k), ~o && g[o].m(b, k), q(b, l, k), _ && _.m(b, k), q(b, a, k), c = !0;
    },
    p(b, k) {
      /*variant*/
      b[8] === "default" && /*show_eta_bar*/
      b[18] && /*show_progress*/
      b[6] === "full" ? d ? d.p(b, k) : (d = fm(b), d.c(), d.m(e.parentNode, e)) : d && (d.d(1), d = null), h === (h = u(b)) && f ? f.p(b, k) : (f && f.d(1), f = h && h(b), f && (f.c(), f.m(t, r))), /*timer*/
      b[5] ? p ? p.p(b, k) : (p = gm(b), p.c(), p.m(t, null)) : p && (p.d(1), p = null), (!c || k[0] & /*variant*/
      256) && Pt(
        t,
        "meta-text-center",
        /*variant*/
        b[8] === "center"
      ), (!c || k[0] & /*variant*/
      256) && Pt(
        t,
        "meta-text",
        /*variant*/
        b[8] === "default"
      );
      let C = o;
      o = y(b), o === C ? ~o && g[o].p(b, k) : (s && (uu(), Tn(g[C], 1, 1, () => {
        g[C] = null;
      }), du()), ~o ? (s = g[o], s ? s.p(b, k) : (s = g[o] = m[o](b), s.c()), sn(s, 1), s.m(l.parentNode, l)) : s = null), /*timer*/
      b[5] ? _ && (uu(), Tn(_, 1, 1, () => {
        _ = null;
      }), du()) : _ ? (_.p(b, k), k[0] & /*timer*/
      32 && sn(_, 1)) : (_ = Cm(b), _.c(), sn(_, 1), _.m(a.parentNode, a));
    },
    i(b) {
      c || (sn(s), sn(_), c = !0);
    },
    o(b) {
      Tn(s), Tn(_), c = !1;
    },
    d(b) {
      b && (H(e), H(t), H(i), H(l), H(a)), d && d.d(b), f && f.d(), p && p.d(), ~o && g[o].d(b), _ && _.d(b);
    }
  };
}
function fm(n) {
  let e, t = `translateX(${/*eta_level*/
  (n[17] || 0) * 100 - 100}%)`;
  return {
    c() {
      e = An("div"), this.h();
    },
    l(r) {
      e = Dn(r, "DIV", { class: !0 }), xn(e).forEach(H), this.h();
    },
    h() {
      an(e, "class", "eta-bar svelte-17v219f"), Cr(e, "transform", t);
    },
    m(r, i) {
      q(r, e, i);
    },
    p(r, i) {
      i[0] & /*eta_level*/
      131072 && t !== (t = `translateX(${/*eta_level*/
      (r[17] || 0) * 100 - 100}%)`) && Cr(e, "transform", t);
    },
    d(r) {
      r && H(e);
    }
  };
}
function EE(n) {
  let e;
  return {
    c() {
      e = Ce("processing |");
    },
    l(t) {
      e = ve(t, "processing |");
    },
    m(t, r) {
      q(t, e, r);
    },
    p: hu,
    d(t) {
      t && H(e);
    }
  };
}
function xE(n) {
  let e, t = (
    /*queue_position*/
    n[2] + 1 + ""
  ), r, i, o, s;
  return {
    c() {
      e = Ce("queue: "), r = Ce(t), i = Ce("/"), o = Ce(
        /*queue_size*/
        n[3]
      ), s = Ce(" |");
    },
    l(l) {
      e = ve(l, "queue: "), r = ve(l, t), i = ve(l, "/"), o = ve(
        l,
        /*queue_size*/
        n[3]
      ), s = ve(l, " |");
    },
    m(l, a) {
      q(l, e, a), q(l, r, a), q(l, i, a), q(l, o, a), q(l, s, a);
    },
    p(l, a) {
      a[0] & /*queue_position*/
      4 && t !== (t = /*queue_position*/
      l[2] + 1 + "") && Yt(r, t), a[0] & /*queue_size*/
      8 && Yt(
        o,
        /*queue_size*/
        l[3]
      );
    },
    d(l) {
      l && (H(e), H(r), H(i), H(o), H(s));
    }
  };
}
function DE(n) {
  let e, t = da(
    /*progress*/
    n[7]
  ), r = [];
  for (let i = 0; i < t.length; i += 1)
    r[i] = mm(hm(n, t, i));
  return {
    c() {
      for (let i = 0; i < r.length; i += 1)
        r[i].c();
      e = Jt();
    },
    l(i) {
      for (let o = 0; o < r.length; o += 1)
        r[o].l(i);
      e = Jt();
    },
    m(i, o) {
      for (let s = 0; s < r.length; s += 1)
        r[s] && r[s].m(i, o);
      q(i, e, o);
    },
    p(i, o) {
      if (o[0] & /*progress*/
      128) {
        t = da(
          /*progress*/
          i[7]
        );
        let s;
        for (s = 0; s < t.length; s += 1) {
          const l = hm(i, t, s);
          r[s] ? r[s].p(l, o) : (r[s] = mm(l), r[s].c(), r[s].m(e.parentNode, e));
        }
        for (; s < r.length; s += 1)
          r[s].d(1);
        r.length = t.length;
      }
    },
    d(i) {
      i && H(e), ty(r, i);
    }
  };
}
function pm(n) {
  let e, t = (
    /*p*/
    n[40].unit + ""
  ), r, i, o = " ", s;
  function l(d, u) {
    return (
      /*p*/
      d[40].length != null ? TE : AE
    );
  }
  let a = l(n), c = a(n);
  return {
    c() {
      c.c(), e = jt(), r = Ce(t), i = Ce(" | "), s = Ce(o);
    },
    l(d) {
      c.l(d), e = qt(d), r = ve(d, t), i = ve(d, " | "), s = ve(d, o);
    },
    m(d, u) {
      c.m(d, u), q(d, e, u), q(d, r, u), q(d, i, u), q(d, s, u);
    },
    p(d, u) {
      a === (a = l(d)) && c ? c.p(d, u) : (c.d(1), c = a(d), c && (c.c(), c.m(e.parentNode, e))), u[0] & /*progress*/
      128 && t !== (t = /*p*/
      d[40].unit + "") && Yt(r, t);
    },
    d(d) {
      d && (H(e), H(r), H(i), H(s)), c.d(d);
    }
  };
}
function AE(n) {
  let e = qi(
    /*p*/
    n[40].index || 0
  ) + "", t;
  return {
    c() {
      t = Ce(e);
    },
    l(r) {
      t = ve(r, e);
    },
    m(r, i) {
      q(r, t, i);
    },
    p(r, i) {
      i[0] & /*progress*/
      128 && e !== (e = qi(
        /*p*/
        r[40].index || 0
      ) + "") && Yt(t, e);
    },
    d(r) {
      r && H(t);
    }
  };
}
function TE(n) {
  let e = qi(
    /*p*/
    n[40].index || 0
  ) + "", t, r, i = qi(
    /*p*/
    n[40].length
  ) + "", o;
  return {
    c() {
      t = Ce(e), r = Ce("/"), o = Ce(i);
    },
    l(s) {
      t = ve(s, e), r = ve(s, "/"), o = ve(s, i);
    },
    m(s, l) {
      q(s, t, l), q(s, r, l), q(s, o, l);
    },
    p(s, l) {
      l[0] & /*progress*/
      128 && e !== (e = qi(
        /*p*/
        s[40].index || 0
      ) + "") && Yt(t, e), l[0] & /*progress*/
      128 && i !== (i = qi(
        /*p*/
        s[40].length
      ) + "") && Yt(o, i);
    },
    d(s) {
      s && (H(t), H(r), H(o));
    }
  };
}
function mm(n) {
  let e, t = (
    /*p*/
    n[40].index != null && pm(n)
  );
  return {
    c() {
      t && t.c(), e = Jt();
    },
    l(r) {
      t && t.l(r), e = Jt();
    },
    m(r, i) {
      t && t.m(r, i), q(r, e, i);
    },
    p(r, i) {
      /*p*/
      r[40].index != null ? t ? t.p(r, i) : (t = pm(r), t.c(), t.m(e.parentNode, e)) : t && (t.d(1), t = null);
    },
    d(r) {
      r && H(e), t && t.d(r);
    }
  };
}
function gm(n) {
  let e, t = (
    /*eta*/
    n[0] ? `/${/*formatted_eta*/
    n[19]}` : ""
  ), r, i;
  return {
    c() {
      e = Ce(
        /*formatted_timer*/
        n[20]
      ), r = Ce(t), i = Ce("s");
    },
    l(o) {
      e = ve(
        o,
        /*formatted_timer*/
        n[20]
      ), r = ve(o, t), i = ve(o, "s");
    },
    m(o, s) {
      q(o, e, s), q(o, r, s), q(o, i, s);
    },
    p(o, s) {
      s[0] & /*formatted_timer*/
      1048576 && Yt(
        e,
        /*formatted_timer*/
        o[20]
      ), s[0] & /*eta, formatted_eta*/
      524289 && t !== (t = /*eta*/
      o[0] ? `/${/*formatted_eta*/
      o[19]}` : "") && Yt(r, t);
    },
    d(o) {
      o && (H(e), H(r), H(i));
    }
  };
}
function ME(n) {
  let e, t;
  return e = new pE({
    props: { margin: (
      /*variant*/
      n[8] === "default"
    ) }
  }), {
    c() {
      Zb(e.$$.fragment);
    },
    l(r) {
      Xb(e.$$.fragment, r);
    },
    m(r, i) {
      iy(e, r, i), t = !0;
    },
    p(r, i) {
      const o = {};
      i[0] & /*variant*/
      256 && (o.margin = /*variant*/
      r[8] === "default"), e.$set(o);
    },
    i(r) {
      t || (sn(e.$$.fragment, r), t = !0);
    },
    o(r) {
      Tn(e.$$.fragment, r), t = !1;
    },
    d(r) {
      ey(e, r);
    }
  };
}
function OE(n) {
  let e, t, r, i, o, s = `${/*last_progress_level*/
  n[15] * 100}%`, l = (
    /*progress*/
    n[7] != null && bm(n)
  );
  return {
    c() {
      e = An("div"), t = An("div"), l && l.c(), r = jt(), i = An("div"), o = An("div"), this.h();
    },
    l(a) {
      e = Dn(a, "DIV", { class: !0 });
      var c = xn(e);
      t = Dn(c, "DIV", { class: !0 });
      var d = xn(t);
      l && l.l(d), d.forEach(H), r = qt(c), i = Dn(c, "DIV", { class: !0 });
      var u = xn(i);
      o = Dn(u, "DIV", { class: !0 }), xn(o).forEach(H), u.forEach(H), c.forEach(H), this.h();
    },
    h() {
      an(t, "class", "progress-level-inner svelte-17v219f"), an(o, "class", "progress-bar svelte-17v219f"), Cr(o, "width", s), an(i, "class", "progress-bar-wrap svelte-17v219f"), an(e, "class", "progress-level svelte-17v219f");
    },
    m(a, c) {
      q(a, e, c), Xr(e, t), l && l.m(t, null), Xr(e, r), Xr(e, i), Xr(i, o), n[31](o);
    },
    p(a, c) {
      /*progress*/
      a[7] != null ? l ? l.p(a, c) : (l = bm(a), l.c(), l.m(t, null)) : l && (l.d(1), l = null), c[0] & /*last_progress_level*/
      32768 && s !== (s = `${/*last_progress_level*/
      a[15] * 100}%`) && Cr(o, "width", s);
    },
    i: hu,
    o: hu,
    d(a) {
      a && H(e), l && l.d(), n[31](null);
    }
  };
}
function bm(n) {
  let e, t = da(
    /*progress*/
    n[7]
  ), r = [];
  for (let i = 0; i < t.length; i += 1)
    r[i] = vm(um(n, t, i));
  return {
    c() {
      for (let i = 0; i < r.length; i += 1)
        r[i].c();
      e = Jt();
    },
    l(i) {
      for (let o = 0; o < r.length; o += 1)
        r[o].l(i);
      e = Jt();
    },
    m(i, o) {
      for (let s = 0; s < r.length; s += 1)
        r[s] && r[s].m(i, o);
      q(i, e, o);
    },
    p(i, o) {
      if (o[0] & /*progress_level, progress*/
      16512) {
        t = da(
          /*progress*/
          i[7]
        );
        let s;
        for (s = 0; s < t.length; s += 1) {
          const l = um(i, t, s);
          r[s] ? r[s].p(l, o) : (r[s] = vm(l), r[s].c(), r[s].m(e.parentNode, e));
        }
        for (; s < r.length; s += 1)
          r[s].d(1);
        r.length = t.length;
      }
    },
    d(i) {
      i && H(e), ty(r, i);
    }
  };
}
function ym(n) {
  let e, t, r, i, o = (
    /*i*/
    n[42] !== 0 && FE()
  ), s = (
    /*p*/
    n[40].desc != null && _m(n)
  ), l = (
    /*p*/
    n[40].desc != null && /*progress_level*/
    n[14] && /*progress_level*/
    n[14][
      /*i*/
      n[42]
    ] != null && wm()
  ), a = (
    /*progress_level*/
    n[14] != null && km(n)
  );
  return {
    c() {
      o && o.c(), e = jt(), s && s.c(), t = jt(), l && l.c(), r = jt(), a && a.c(), i = Jt();
    },
    l(c) {
      o && o.l(c), e = qt(c), s && s.l(c), t = qt(c), l && l.l(c), r = qt(c), a && a.l(c), i = Jt();
    },
    m(c, d) {
      o && o.m(c, d), q(c, e, d), s && s.m(c, d), q(c, t, d), l && l.m(c, d), q(c, r, d), a && a.m(c, d), q(c, i, d);
    },
    p(c, d) {
      /*p*/
      c[40].desc != null ? s ? s.p(c, d) : (s = _m(c), s.c(), s.m(t.parentNode, t)) : s && (s.d(1), s = null), /*p*/
      c[40].desc != null && /*progress_level*/
      c[14] && /*progress_level*/
      c[14][
        /*i*/
        c[42]
      ] != null ? l || (l = wm(), l.c(), l.m(r.parentNode, r)) : l && (l.d(1), l = null), /*progress_level*/
      c[14] != null ? a ? a.p(c, d) : (a = km(c), a.c(), a.m(i.parentNode, i)) : a && (a.d(1), a = null);
    },
    d(c) {
      c && (H(e), H(t), H(r), H(i)), o && o.d(c), s && s.d(c), l && l.d(c), a && a.d(c);
    }
  };
}
function FE(n) {
  let e;
  return {
    c() {
      e = Ce(" /");
    },
    l(t) {
      e = ve(t, " /");
    },
    m(t, r) {
      q(t, e, r);
    },
    d(t) {
      t && H(e);
    }
  };
}
function _m(n) {
  let e = (
    /*p*/
    n[40].desc + ""
  ), t;
  return {
    c() {
      t = Ce(e);
    },
    l(r) {
      t = ve(r, e);
    },
    m(r, i) {
      q(r, t, i);
    },
    p(r, i) {
      i[0] & /*progress*/
      128 && e !== (e = /*p*/
      r[40].desc + "") && Yt(t, e);
    },
    d(r) {
      r && H(t);
    }
  };
}
function wm(n) {
  let e;
  return {
    c() {
      e = Ce("-");
    },
    l(t) {
      e = ve(t, "-");
    },
    m(t, r) {
      q(t, e, r);
    },
    d(t) {
      t && H(e);
    }
  };
}
function km(n) {
  let e = (100 * /*progress_level*/
  (n[14][
    /*i*/
    n[42]
  ] || 0)).toFixed(1) + "", t, r;
  return {
    c() {
      t = Ce(e), r = Ce("%");
    },
    l(i) {
      t = ve(i, e), r = ve(i, "%");
    },
    m(i, o) {
      q(i, t, o), q(i, r, o);
    },
    p(i, o) {
      o[0] & /*progress_level*/
      16384 && e !== (e = (100 * /*progress_level*/
      (i[14][
        /*i*/
        i[42]
      ] || 0)).toFixed(1) + "") && Yt(t, e);
    },
    d(i) {
      i && (H(t), H(r));
    }
  };
}
function vm(n) {
  let e, t = (
    /*p*/
    (n[40].desc != null || /*progress_level*/
    n[14] && /*progress_level*/
    n[14][
      /*i*/
      n[42]
    ] != null) && ym(n)
  );
  return {
    c() {
      t && t.c(), e = Jt();
    },
    l(r) {
      t && t.l(r), e = Jt();
    },
    m(r, i) {
      t && t.m(r, i), q(r, e, i);
    },
    p(r, i) {
      /*p*/
      r[40].desc != null || /*progress_level*/
      r[14] && /*progress_level*/
      r[14][
        /*i*/
        r[42]
      ] != null ? t ? t.p(r, i) : (t = ym(r), t.c(), t.m(e.parentNode, e)) : t && (t.d(1), t = null);
    },
    d(r) {
      r && H(e), t && t.d(r);
    }
  };
}
function Cm(n) {
  let e, t, r, i;
  const o = (
    /*#slots*/
    n[30]["additional-loading-text"]
  ), s = Qb(
    o,
    n,
    /*$$scope*/
    n[29],
    dm
  );
  return {
    c() {
      e = An("p"), t = Ce(
        /*loading_text*/
        n[9]
      ), r = jt(), s && s.c(), this.h();
    },
    l(l) {
      e = Dn(l, "P", { class: !0 });
      var a = xn(e);
      t = ve(
        a,
        /*loading_text*/
        n[9]
      ), a.forEach(H), r = qt(l), s && s.l(l), this.h();
    },
    h() {
      an(e, "class", "loading svelte-17v219f");
    },
    m(l, a) {
      q(l, e, a), Xr(e, t), q(l, r, a), s && s.m(l, a), i = !0;
    },
    p(l, a) {
      (!i || a[0] & /*loading_text*/
      512) && Yt(
        t,
        /*loading_text*/
        l[9]
      ), s && s.p && (!i || a[0] & /*$$scope*/
      536870912) && oy(
        s,
        o,
        l,
        /*$$scope*/
        l[29],
        i ? ry(
          o,
          /*$$scope*/
          l[29],
          a,
          vE
        ) : ny(
          /*$$scope*/
          l[29]
        ),
        dm
      );
    },
    i(l) {
      i || (sn(s, l), i = !0);
    },
    o(l) {
      Tn(s, l), i = !1;
    },
    d(l) {
      l && (H(e), H(r)), s && s.d(l);
    }
  };
}
function NE(n) {
  let e, t, r, i, o;
  const s = [SE, CE], l = [];
  function a(c, d) {
    return (
      /*status*/
      c[4] === "pending" ? 0 : (
        /*status*/
        c[4] === "error" ? 1 : -1
      )
    );
  }
  return ~(t = a(n)) && (r = l[t] = s[t](n)), {
    c() {
      e = An("div"), r && r.c(), this.h();
    },
    l(c) {
      e = Dn(c, "DIV", { class: !0 });
      var d = xn(e);
      r && r.l(d), d.forEach(H), this.h();
    },
    h() {
      an(e, "class", i = "wrap " + /*variant*/
      n[8] + " " + /*show_progress*/
      n[6] + " svelte-17v219f"), Pt(e, "hide", !/*status*/
      n[4] || /*status*/
      n[4] === "complete" || /*show_progress*/
      n[6] === "hidden" || /*status*/
      n[4] == "streaming"), Pt(
        e,
        "translucent",
        /*variant*/
        n[8] === "center" && /*status*/
        (n[4] === "pending" || /*status*/
        n[4] === "error") || /*translucent*/
        n[11] || /*show_progress*/
        n[6] === "minimal"
      ), Pt(
        e,
        "generating",
        /*status*/
        n[4] === "generating" && /*show_progress*/
        n[6] === "full"
      ), Pt(
        e,
        "border",
        /*border*/
        n[12]
      ), Cr(
        e,
        "position",
        /*absolute*/
        n[10] ? "absolute" : "static"
      ), Cr(
        e,
        "padding",
        /*absolute*/
        n[10] ? "0" : "var(--size-8) 0"
      );
    },
    m(c, d) {
      q(c, e, d), ~t && l[t].m(e, null), n[33](e), o = !0;
    },
    p(c, d) {
      let u = t;
      t = a(c), t === u ? ~t && l[t].p(c, d) : (r && (uu(), Tn(l[u], 1, 1, () => {
        l[u] = null;
      }), du()), ~t ? (r = l[t], r ? r.p(c, d) : (r = l[t] = s[t](c), r.c()), sn(r, 1), r.m(e, null)) : r = null), (!o || d[0] & /*variant, show_progress*/
      320 && i !== (i = "wrap " + /*variant*/
      c[8] + " " + /*show_progress*/
      c[6] + " svelte-17v219f")) && an(e, "class", i), (!o || d[0] & /*variant, show_progress, status, show_progress*/
      336) && Pt(e, "hide", !/*status*/
      c[4] || /*status*/
      c[4] === "complete" || /*show_progress*/
      c[6] === "hidden" || /*status*/
      c[4] == "streaming"), (!o || d[0] & /*variant, show_progress, variant, status, translucent, show_progress*/
      2384) && Pt(
        e,
        "translucent",
        /*variant*/
        c[8] === "center" && /*status*/
        (c[4] === "pending" || /*status*/
        c[4] === "error") || /*translucent*/
        c[11] || /*show_progress*/
        c[6] === "minimal"
      ), (!o || d[0] & /*variant, show_progress, status, show_progress*/
      336) && Pt(
        e,
        "generating",
        /*status*/
        c[4] === "generating" && /*show_progress*/
        c[6] === "full"
      ), (!o || d[0] & /*variant, show_progress, border*/
      4416) && Pt(
        e,
        "border",
        /*border*/
        c[12]
      ), d[0] & /*absolute*/
      1024 && Cr(
        e,
        "position",
        /*absolute*/
        c[10] ? "absolute" : "static"
      ), d[0] & /*absolute*/
      1024 && Cr(
        e,
        "padding",
        /*absolute*/
        c[10] ? "0" : "var(--size-8) 0"
      );
    },
    i(c) {
      o || (sn(r), o = !0);
    },
    o(c) {
      Tn(r), o = !1;
    },
    d(c) {
      c && H(e), ~t && l[t].d(), n[33](null);
    }
  };
}
var $E = function(n, e, t, r) {
  function i(o) {
    return o instanceof t ? o : new t(function(s) {
      s(o);
    });
  }
  return new (t || (t = Promise))(function(o, s) {
    function l(d) {
      try {
        c(r.next(d));
      } catch (u) {
        s(u);
      }
    }
    function a(d) {
      try {
        c(r.throw(d));
      } catch (u) {
        s(u);
      }
    }
    function c(d) {
      d.done ? o(d.value) : i(d.value).then(l, a);
    }
    c((r = r.apply(n, e || [])).next());
  });
};
let ml = [], ad = !1;
const IE = typeof window < "u", sy = IE ? window.requestAnimationFrame : (n) => {
};
function LE(n) {
  return $E(this, arguments, void 0, function* (e, t = !0) {
    if (!(window.__gradio_mode__ === "website" || window.__gradio_mode__ !== "app" && t !== !0)) {
      if (ml.push(e), !ad) ad = !0;
      else return;
      yield yE(), sy(() => {
        let r = [0, 0];
        for (let i = 0; i < ml.length; i++) {
          const s = ml[i].getBoundingClientRect();
          (i === 0 || s.top + window.scrollY <= r[0]) && (r[0] = s.top + window.scrollY, r[1] = i);
        }
        window.scrollTo({ top: r[0] - 20, behavior: "smooth" }), ad = !1, ml = [];
      });
    }
  });
}
function RE(n, e, t) {
  let r, { $$slots: i = {}, $$scope: o } = e;
  const s = wE();
  let { i18n: l } = e, { eta: a = null } = e, { queue_position: c } = e, { queue_size: d } = e, { status: u } = e, { scroll_to_output: h = !1 } = e, { timer: f = !0 } = e, { show_progress: p = "full" } = e, { message: m = null } = e, { progress: g = null } = e, { variant: y = "default" } = e, { loading_text: _ = "Loading..." } = e, { absolute: b = !0 } = e, { translucent: k = !1 } = e, { border: C = !1 } = e, { autoscroll: w } = e, x, S = !1, D = 0, T = 0, I = null, U = null, Te = 0, ce = null, fe, K = null, be = !0;
  const ke = () => {
    t(0, a = t(27, I = t(19, N = null))), t(25, D = performance.now()), t(26, T = 0), S = !0, qe();
  };
  function qe() {
    sy(() => {
      t(26, T = (performance.now() - D) / 1e3), S && qe();
    });
  }
  function mt() {
    t(26, T = 0), t(0, a = t(27, I = t(19, N = null))), S && (S = !1);
  }
  _E(() => {
    S && mt();
  });
  let N = null;
  function $e($) {
    am[$ ? "unshift" : "push"](() => {
      K = $, t(16, K), t(7, g), t(14, ce), t(15, fe);
    });
  }
  const ye = () => {
    s("clear_status");
  };
  function Ye($) {
    am[$ ? "unshift" : "push"](() => {
      x = $, t(13, x);
    });
  }
  return n.$$set = ($) => {
    "i18n" in $ && t(1, l = $.i18n), "eta" in $ && t(0, a = $.eta), "queue_position" in $ && t(2, c = $.queue_position), "queue_size" in $ && t(3, d = $.queue_size), "status" in $ && t(4, u = $.status), "scroll_to_output" in $ && t(22, h = $.scroll_to_output), "timer" in $ && t(5, f = $.timer), "show_progress" in $ && t(6, p = $.show_progress), "message" in $ && t(23, m = $.message), "progress" in $ && t(7, g = $.progress), "variant" in $ && t(8, y = $.variant), "loading_text" in $ && t(9, _ = $.loading_text), "absolute" in $ && t(10, b = $.absolute), "translucent" in $ && t(11, k = $.translucent), "border" in $ && t(12, C = $.border), "autoscroll" in $ && t(24, w = $.autoscroll), "$$scope" in $ && t(29, o = $.$$scope);
  }, n.$$.update = () => {
    n.$$.dirty[0] & /*eta, old_eta, timer_start, eta_from_start*/
    436207617 && (a === null && t(0, a = I), a != null && I !== a && (t(28, U = (performance.now() - D) / 1e3 + a), t(19, N = U.toFixed(1)), t(27, I = a))), n.$$.dirty[0] & /*eta_from_start, timer_diff*/
    335544320 && t(17, Te = U === null || U <= 0 || !T ? null : Math.min(T / U, 1)), n.$$.dirty[0] & /*progress*/
    128 && g != null && t(18, be = !1), n.$$.dirty[0] & /*progress, progress_level, progress_bar, last_progress_level*/
    114816 && (g != null ? t(14, ce = g.map(($) => {
      if ($.index != null && $.length != null)
        return $.index / $.length;
      if ($.progress != null)
        return $.progress;
    })) : t(14, ce = null), ce ? (t(15, fe = ce[ce.length - 1]), K && (fe === 0 ? t(16, K.style.transition = "0", K) : t(16, K.style.transition = "150ms", K))) : t(15, fe = void 0)), n.$$.dirty[0] & /*status*/
    16 && (u === "pending" ? ke() : mt()), n.$$.dirty[0] & /*el, scroll_to_output, status, autoscroll*/
    20979728 && x && h && (u === "pending" || u === "complete") && LE(x, w), n.$$.dirty[0] & /*status, message*/
    8388624, n.$$.dirty[0] & /*timer_diff*/
    67108864 && t(20, r = T.toFixed(1));
  }, [
    a,
    l,
    c,
    d,
    u,
    f,
    p,
    g,
    y,
    _,
    b,
    k,
    C,
    x,
    ce,
    fe,
    K,
    Te,
    be,
    N,
    r,
    s,
    h,
    m,
    w,
    D,
    T,
    I,
    U,
    o,
    i,
    $e,
    ye,
    Ye
  ];
}
class BE extends mE {
  constructor(e) {
    super(), gE(
      this,
      e,
      RE,
      NE,
      bE,
      {
        i18n: 1,
        eta: 0,
        queue_position: 2,
        queue_size: 3,
        status: 4,
        scroll_to_output: 22,
        timer: 5,
        show_progress: 6,
        message: 23,
        progress: 7,
        variant: 8,
        loading_text: 9,
        absolute: 10,
        translucent: 11,
        border: 12,
        autoscroll: 24
      },
      null,
      [-1, -1]
    );
  }
}
/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */
const {
  entries: ly,
  setPrototypeOf: Sm,
  isFrozen: PE,
  getPrototypeOf: zE,
  getOwnPropertyDescriptor: HE
} = Object;
let {
  freeze: dt,
  seal: Xt,
  create: ay
} = Object, {
  apply: fu,
  construct: pu
} = typeof Reflect < "u" && Reflect;
dt || (dt = function(e) {
  return e;
});
Xt || (Xt = function(e) {
  return e;
});
fu || (fu = function(e, t, r) {
  return e.apply(t, r);
});
pu || (pu = function(e, t) {
  return new e(...t);
});
const gl = ut(Array.prototype.forEach), VE = ut(Array.prototype.lastIndexOf), Em = ut(Array.prototype.pop), To = ut(Array.prototype.push), UE = ut(Array.prototype.splice), Wl = ut(String.prototype.toLowerCase), cd = ut(String.prototype.toString), xm = ut(String.prototype.match), Mo = ut(String.prototype.replace), qE = ut(String.prototype.indexOf), jE = ut(String.prototype.trim), rn = ut(Object.prototype.hasOwnProperty), lt = ut(RegExp.prototype.test), Oo = WE(TypeError);
function ut(n) {
  return function(e) {
    e instanceof RegExp && (e.lastIndex = 0);
    for (var t = arguments.length, r = new Array(t > 1 ? t - 1 : 0), i = 1; i < t; i++)
      r[i - 1] = arguments[i];
    return fu(n, e, r);
  };
}
function WE(n) {
  return function() {
    for (var e = arguments.length, t = new Array(e), r = 0; r < e; r++)
      t[r] = arguments[r];
    return pu(n, t);
  };
}
function Y(n, e) {
  let t = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : Wl;
  Sm && Sm(n, null);
  let r = e.length;
  for (; r--; ) {
    let i = e[r];
    if (typeof i == "string") {
      const o = t(i);
      o !== i && (PE(e) || (e[r] = o), i = o);
    }
    n[i] = !0;
  }
  return n;
}
function GE(n) {
  for (let e = 0; e < n.length; e++)
    rn(n, e) || (n[e] = null);
  return n;
}
function Gn(n) {
  const e = ay(null);
  for (const [t, r] of ly(n))
    rn(n, t) && (Array.isArray(r) ? e[t] = GE(r) : r && typeof r == "object" && r.constructor === Object ? e[t] = Gn(r) : e[t] = r);
  return e;
}
function Fo(n, e) {
  for (; n !== null; ) {
    const r = HE(n, e);
    if (r) {
      if (r.get)
        return ut(r.get);
      if (typeof r.value == "function")
        return ut(r.value);
    }
    n = zE(n);
  }
  function t() {
    return null;
  }
  return t;
}
const Dm = dt(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "shadow", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]), dd = dt(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]), ud = dt(["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"]), KE = dt(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]), hd = dt(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]), JE = dt(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]), Am = dt(["#text"]), Tm = dt(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]), fd = dt(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]), Mm = dt(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]), bl = dt(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]), YE = Xt(/\{\{[\w\W]*|[\w\W]*\}\}/gm), XE = Xt(/<%[\w\W]*|[\w\W]*%>/gm), ZE = Xt(/\$\{[\w\W]*/gm), QE = Xt(/^data-[\-\w.\u00B7-\uFFFF]+$/), ex = Xt(/^aria-[\-\w]+$/), cy = Xt(
  /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  // eslint-disable-line no-useless-escape
), tx = Xt(/^(?:\w+script|data):/i), nx = Xt(
  /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
  // eslint-disable-line no-control-regex
), dy = Xt(/^html$/i), rx = Xt(/^[a-z][.\w]*(-[.\w]+)+$/i);
var Om = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ARIA_ATTR: ex,
  ATTR_WHITESPACE: nx,
  CUSTOM_ELEMENT: rx,
  DATA_ATTR: QE,
  DOCTYPE_NAME: dy,
  ERB_EXPR: XE,
  IS_ALLOWED_URI: cy,
  IS_SCRIPT_OR_DATA: tx,
  MUSTACHE_EXPR: YE,
  TMPLIT_EXPR: ZE
});
const No = {
  element: 1,
  text: 3,
  // Deprecated
  progressingInstruction: 7,
  comment: 8,
  document: 9
}, ix = function() {
  return typeof window > "u" ? null : window;
}, ox = function(e, t) {
  if (typeof e != "object" || typeof e.createPolicy != "function")
    return null;
  let r = null;
  const i = "data-tt-policy-suffix";
  t && t.hasAttribute(i) && (r = t.getAttribute(i));
  const o = "dompurify" + (r ? "#" + r : "");
  try {
    return e.createPolicy(o, {
      createHTML(s) {
        return s;
      },
      createScriptURL(s) {
        return s;
      }
    });
  } catch {
    return console.warn("TrustedTypes policy " + o + " could not be created."), null;
  }
}, Fm = function() {
  return {
    afterSanitizeAttributes: [],
    afterSanitizeElements: [],
    afterSanitizeShadowDOM: [],
    beforeSanitizeAttributes: [],
    beforeSanitizeElements: [],
    beforeSanitizeShadowDOM: [],
    uponSanitizeAttribute: [],
    uponSanitizeElement: [],
    uponSanitizeShadowNode: []
  };
};
function uy() {
  let n = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ix();
  const e = (z) => uy(z);
  if (e.version = "3.2.6", e.removed = [], !n || !n.document || n.document.nodeType !== No.document || !n.Element)
    return e.isSupported = !1, e;
  let {
    document: t
  } = n;
  const r = t, i = r.currentScript, {
    DocumentFragment: o,
    HTMLTemplateElement: s,
    Node: l,
    Element: a,
    NodeFilter: c,
    NamedNodeMap: d = n.NamedNodeMap || n.MozNamedAttrMap,
    HTMLFormElement: u,
    DOMParser: h,
    trustedTypes: f
  } = n, p = a.prototype, m = Fo(p, "cloneNode"), g = Fo(p, "remove"), y = Fo(p, "nextSibling"), _ = Fo(p, "childNodes"), b = Fo(p, "parentNode");
  if (typeof s == "function") {
    const z = t.createElement("template");
    z.content && z.content.ownerDocument && (t = z.content.ownerDocument);
  }
  let k, C = "";
  const {
    implementation: w,
    createNodeIterator: x,
    createDocumentFragment: S,
    getElementsByTagName: D
  } = t, {
    importNode: T
  } = r;
  let I = Fm();
  e.isSupported = typeof ly == "function" && typeof b == "function" && w && w.createHTMLDocument !== void 0;
  const {
    MUSTACHE_EXPR: U,
    ERB_EXPR: Te,
    TMPLIT_EXPR: ce,
    DATA_ATTR: fe,
    ARIA_ATTR: K,
    IS_SCRIPT_OR_DATA: be,
    ATTR_WHITESPACE: ke,
    CUSTOM_ELEMENT: qe
  } = Om;
  let {
    IS_ALLOWED_URI: mt
  } = Om, N = null;
  const $e = Y({}, [...Dm, ...dd, ...ud, ...hd, ...Am]);
  let ye = null;
  const Ye = Y({}, [...Tm, ...fd, ...Mm, ...bl]);
  let $ = Object.seal(ay(null, {
    tagNameCheck: {
      writable: !0,
      configurable: !1,
      enumerable: !0,
      value: null
    },
    attributeNameCheck: {
      writable: !0,
      configurable: !1,
      enumerable: !0,
      value: null
    },
    allowCustomizedBuiltInElements: {
      writable: !0,
      configurable: !1,
      enumerable: !0,
      value: !1
    }
  })), $t = null, cr = null, Ai = !0, Ti = !0, Mi = !1, Ur = !0, dr = !1, ur = !0, qr = !1, Uc = !1, qc = !1, Oi = !1, Xs = !1, Zs = !1, ip = !0, op = !1;
  const Nk = "user-content-";
  let jc = !0, So = !1, Fi = {}, Ni = null;
  const sp = Y({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]);
  let lp = null;
  const ap = Y({}, ["audio", "video", "img", "source", "image", "track"]);
  let Wc = null;
  const cp = Y({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]), Qs = "http://www.w3.org/1998/Math/MathML", el = "http://www.w3.org/2000/svg", Pn = "http://www.w3.org/1999/xhtml";
  let $i = Pn, Gc = !1, Kc = null;
  const $k = Y({}, [Qs, el, Pn], cd);
  let tl = Y({}, ["mi", "mo", "mn", "ms", "mtext"]), nl = Y({}, ["annotation-xml"]);
  const Ik = Y({}, ["title", "style", "font", "a", "script"]);
  let Eo = null;
  const Lk = ["application/xhtml+xml", "text/html"], Rk = "text/html";
  let Le = null, Ii = null;
  const Bk = t.createElement("form"), dp = function(v) {
    return v instanceof RegExp || v instanceof Function;
  }, Jc = function() {
    let v = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    if (!(Ii && Ii === v)) {
      if ((!v || typeof v != "object") && (v = {}), v = Gn(v), Eo = // eslint-disable-next-line unicorn/prefer-includes
      Lk.indexOf(v.PARSER_MEDIA_TYPE) === -1 ? Rk : v.PARSER_MEDIA_TYPE, Le = Eo === "application/xhtml+xml" ? cd : Wl, N = rn(v, "ALLOWED_TAGS") ? Y({}, v.ALLOWED_TAGS, Le) : $e, ye = rn(v, "ALLOWED_ATTR") ? Y({}, v.ALLOWED_ATTR, Le) : Ye, Kc = rn(v, "ALLOWED_NAMESPACES") ? Y({}, v.ALLOWED_NAMESPACES, cd) : $k, Wc = rn(v, "ADD_URI_SAFE_ATTR") ? Y(Gn(cp), v.ADD_URI_SAFE_ATTR, Le) : cp, lp = rn(v, "ADD_DATA_URI_TAGS") ? Y(Gn(ap), v.ADD_DATA_URI_TAGS, Le) : ap, Ni = rn(v, "FORBID_CONTENTS") ? Y({}, v.FORBID_CONTENTS, Le) : sp, $t = rn(v, "FORBID_TAGS") ? Y({}, v.FORBID_TAGS, Le) : Gn({}), cr = rn(v, "FORBID_ATTR") ? Y({}, v.FORBID_ATTR, Le) : Gn({}), Fi = rn(v, "USE_PROFILES") ? v.USE_PROFILES : !1, Ai = v.ALLOW_ARIA_ATTR !== !1, Ti = v.ALLOW_DATA_ATTR !== !1, Mi = v.ALLOW_UNKNOWN_PROTOCOLS || !1, Ur = v.ALLOW_SELF_CLOSE_IN_ATTR !== !1, dr = v.SAFE_FOR_TEMPLATES || !1, ur = v.SAFE_FOR_XML !== !1, qr = v.WHOLE_DOCUMENT || !1, Oi = v.RETURN_DOM || !1, Xs = v.RETURN_DOM_FRAGMENT || !1, Zs = v.RETURN_TRUSTED_TYPE || !1, qc = v.FORCE_BODY || !1, ip = v.SANITIZE_DOM !== !1, op = v.SANITIZE_NAMED_PROPS || !1, jc = v.KEEP_CONTENT !== !1, So = v.IN_PLACE || !1, mt = v.ALLOWED_URI_REGEXP || cy, $i = v.NAMESPACE || Pn, tl = v.MATHML_TEXT_INTEGRATION_POINTS || tl, nl = v.HTML_INTEGRATION_POINTS || nl, $ = v.CUSTOM_ELEMENT_HANDLING || {}, v.CUSTOM_ELEMENT_HANDLING && dp(v.CUSTOM_ELEMENT_HANDLING.tagNameCheck) && ($.tagNameCheck = v.CUSTOM_ELEMENT_HANDLING.tagNameCheck), v.CUSTOM_ELEMENT_HANDLING && dp(v.CUSTOM_ELEMENT_HANDLING.attributeNameCheck) && ($.attributeNameCheck = v.CUSTOM_ELEMENT_HANDLING.attributeNameCheck), v.CUSTOM_ELEMENT_HANDLING && typeof v.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements == "boolean" && ($.allowCustomizedBuiltInElements = v.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements), dr && (Ti = !1), Xs && (Oi = !0), Fi && (N = Y({}, Am), ye = [], Fi.html === !0 && (Y(N, Dm), Y(ye, Tm)), Fi.svg === !0 && (Y(N, dd), Y(ye, fd), Y(ye, bl)), Fi.svgFilters === !0 && (Y(N, ud), Y(ye, fd), Y(ye, bl)), Fi.mathMl === !0 && (Y(N, hd), Y(ye, Mm), Y(ye, bl))), v.ADD_TAGS && (N === $e && (N = Gn(N)), Y(N, v.ADD_TAGS, Le)), v.ADD_ATTR && (ye === Ye && (ye = Gn(ye)), Y(ye, v.ADD_ATTR, Le)), v.ADD_URI_SAFE_ATTR && Y(Wc, v.ADD_URI_SAFE_ATTR, Le), v.FORBID_CONTENTS && (Ni === sp && (Ni = Gn(Ni)), Y(Ni, v.FORBID_CONTENTS, Le)), jc && (N["#text"] = !0), qr && Y(N, ["html", "head", "body"]), N.table && (Y(N, ["tbody"]), delete $t.tbody), v.TRUSTED_TYPES_POLICY) {
        if (typeof v.TRUSTED_TYPES_POLICY.createHTML != "function")
          throw Oo('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
        if (typeof v.TRUSTED_TYPES_POLICY.createScriptURL != "function")
          throw Oo('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
        k = v.TRUSTED_TYPES_POLICY, C = k.createHTML("");
      } else
        k === void 0 && (k = ox(f, i)), k !== null && typeof C == "string" && (C = k.createHTML(""));
      dt && dt(v), Ii = v;
    }
  }, up = Y({}, [...dd, ...ud, ...KE]), hp = Y({}, [...hd, ...JE]), Pk = function(v) {
    let F = b(v);
    (!F || !F.tagName) && (F = {
      namespaceURI: $i,
      tagName: "template"
    });
    const B = Wl(v.tagName), _e = Wl(F.tagName);
    return Kc[v.namespaceURI] ? v.namespaceURI === el ? F.namespaceURI === Pn ? B === "svg" : F.namespaceURI === Qs ? B === "svg" && (_e === "annotation-xml" || tl[_e]) : !!up[B] : v.namespaceURI === Qs ? F.namespaceURI === Pn ? B === "math" : F.namespaceURI === el ? B === "math" && nl[_e] : !!hp[B] : v.namespaceURI === Pn ? F.namespaceURI === el && !nl[_e] || F.namespaceURI === Qs && !tl[_e] ? !1 : !hp[B] && (Ik[B] || !up[B]) : !!(Eo === "application/xhtml+xml" && Kc[v.namespaceURI]) : !1;
  }, yn = function(v) {
    To(e.removed, {
      element: v
    });
    try {
      b(v).removeChild(v);
    } catch {
      g(v);
    }
  }, Li = function(v, F) {
    try {
      To(e.removed, {
        attribute: F.getAttributeNode(v),
        from: F
      });
    } catch {
      To(e.removed, {
        attribute: null,
        from: F
      });
    }
    if (F.removeAttribute(v), v === "is")
      if (Oi || Xs)
        try {
          yn(F);
        } catch {
        }
      else
        try {
          F.setAttribute(v, "");
        } catch {
        }
  }, fp = function(v) {
    let F = null, B = null;
    if (qc)
      v = "<remove></remove>" + v;
    else {
      const Ie = xm(v, /^[\r\n\t ]+/);
      B = Ie && Ie[0];
    }
    Eo === "application/xhtml+xml" && $i === Pn && (v = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + v + "</body></html>");
    const _e = k ? k.createHTML(v) : v;
    if ($i === Pn)
      try {
        F = new h().parseFromString(_e, Eo);
      } catch {
      }
    if (!F || !F.documentElement) {
      F = w.createDocument($i, "template", null);
      try {
        F.documentElement.innerHTML = Gc ? C : _e;
      } catch {
      }
    }
    const Xe = F.body || F.documentElement;
    return v && B && Xe.insertBefore(t.createTextNode(B), Xe.childNodes[0] || null), $i === Pn ? D.call(F, qr ? "html" : "body")[0] : qr ? F.documentElement : Xe;
  }, pp = function(v) {
    return x.call(
      v.ownerDocument || v,
      v,
      // eslint-disable-next-line no-bitwise
      c.SHOW_ELEMENT | c.SHOW_COMMENT | c.SHOW_TEXT | c.SHOW_PROCESSING_INSTRUCTION | c.SHOW_CDATA_SECTION,
      null
    );
  }, Yc = function(v) {
    return v instanceof u && (typeof v.nodeName != "string" || typeof v.textContent != "string" || typeof v.removeChild != "function" || !(v.attributes instanceof d) || typeof v.removeAttribute != "function" || typeof v.setAttribute != "function" || typeof v.namespaceURI != "string" || typeof v.insertBefore != "function" || typeof v.hasChildNodes != "function");
  }, mp = function(v) {
    return typeof l == "function" && v instanceof l;
  };
  function zn(z, v, F) {
    gl(z, (B) => {
      B.call(e, v, F, Ii);
    });
  }
  const gp = function(v) {
    let F = null;
    if (zn(I.beforeSanitizeElements, v, null), Yc(v))
      return yn(v), !0;
    const B = Le(v.nodeName);
    if (zn(I.uponSanitizeElement, v, {
      tagName: B,
      allowedTags: N
    }), ur && v.hasChildNodes() && !mp(v.firstElementChild) && lt(/<[/\w!]/g, v.innerHTML) && lt(/<[/\w!]/g, v.textContent) || v.nodeType === No.progressingInstruction || ur && v.nodeType === No.comment && lt(/<[/\w]/g, v.data))
      return yn(v), !0;
    if (!N[B] || $t[B]) {
      if (!$t[B] && yp(B) && ($.tagNameCheck instanceof RegExp && lt($.tagNameCheck, B) || $.tagNameCheck instanceof Function && $.tagNameCheck(B)))
        return !1;
      if (jc && !Ni[B]) {
        const _e = b(v) || v.parentNode, Xe = _(v) || v.childNodes;
        if (Xe && _e) {
          const Ie = Xe.length;
          for (let gt = Ie - 1; gt >= 0; --gt) {
            const Hn = m(Xe[gt], !0);
            Hn.__removalCount = (v.__removalCount || 0) + 1, _e.insertBefore(Hn, y(v));
          }
        }
      }
      return yn(v), !0;
    }
    return v instanceof a && !Pk(v) || (B === "noscript" || B === "noembed" || B === "noframes") && lt(/<\/no(script|embed|frames)/i, v.innerHTML) ? (yn(v), !0) : (dr && v.nodeType === No.text && (F = v.textContent, gl([U, Te, ce], (_e) => {
      F = Mo(F, _e, " ");
    }), v.textContent !== F && (To(e.removed, {
      element: v.cloneNode()
    }), v.textContent = F)), zn(I.afterSanitizeElements, v, null), !1);
  }, bp = function(v, F, B) {
    if (ip && (F === "id" || F === "name") && (B in t || B in Bk))
      return !1;
    if (!(Ti && !cr[F] && lt(fe, F))) {
      if (!(Ai && lt(K, F))) {
        if (!ye[F] || cr[F]) {
          if (
            // First condition does a very basic check if a) it's basically a valid custom element tagname AND
            // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
            // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
            !(yp(v) && ($.tagNameCheck instanceof RegExp && lt($.tagNameCheck, v) || $.tagNameCheck instanceof Function && $.tagNameCheck(v)) && ($.attributeNameCheck instanceof RegExp && lt($.attributeNameCheck, F) || $.attributeNameCheck instanceof Function && $.attributeNameCheck(F)) || // Alternative, second condition checks if it's an `is`-attribute, AND
            // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
            F === "is" && $.allowCustomizedBuiltInElements && ($.tagNameCheck instanceof RegExp && lt($.tagNameCheck, B) || $.tagNameCheck instanceof Function && $.tagNameCheck(B)))
          ) return !1;
        } else if (!Wc[F]) {
          if (!lt(mt, Mo(B, ke, ""))) {
            if (!((F === "src" || F === "xlink:href" || F === "href") && v !== "script" && qE(B, "data:") === 0 && lp[v])) {
              if (!(Mi && !lt(be, Mo(B, ke, "")))) {
                if (B)
                  return !1;
              }
            }
          }
        }
      }
    }
    return !0;
  }, yp = function(v) {
    return v !== "annotation-xml" && xm(v, qe);
  }, _p = function(v) {
    zn(I.beforeSanitizeAttributes, v, null);
    const {
      attributes: F
    } = v;
    if (!F || Yc(v))
      return;
    const B = {
      attrName: "",
      attrValue: "",
      keepAttr: !0,
      allowedAttributes: ye,
      forceKeepAttr: void 0
    };
    let _e = F.length;
    for (; _e--; ) {
      const Xe = F[_e], {
        name: Ie,
        namespaceURI: gt,
        value: Hn
      } = Xe, xo = Le(Ie), Xc = Hn;
      let Ze = Ie === "value" ? Xc : jE(Xc);
      if (B.attrName = xo, B.attrValue = Ze, B.keepAttr = !0, B.forceKeepAttr = void 0, zn(I.uponSanitizeAttribute, v, B), Ze = B.attrValue, op && (xo === "id" || xo === "name") && (Li(Ie, v), Ze = Nk + Ze), ur && lt(/((--!?|])>)|<\/(style|title)/i, Ze)) {
        Li(Ie, v);
        continue;
      }
      if (B.forceKeepAttr)
        continue;
      if (!B.keepAttr) {
        Li(Ie, v);
        continue;
      }
      if (!Ur && lt(/\/>/i, Ze)) {
        Li(Ie, v);
        continue;
      }
      dr && gl([U, Te, ce], (kp) => {
        Ze = Mo(Ze, kp, " ");
      });
      const wp = Le(v.nodeName);
      if (!bp(wp, xo, Ze)) {
        Li(Ie, v);
        continue;
      }
      if (k && typeof f == "object" && typeof f.getAttributeType == "function" && !gt)
        switch (f.getAttributeType(wp, xo)) {
          case "TrustedHTML": {
            Ze = k.createHTML(Ze);
            break;
          }
          case "TrustedScriptURL": {
            Ze = k.createScriptURL(Ze);
            break;
          }
        }
      if (Ze !== Xc)
        try {
          gt ? v.setAttributeNS(gt, Ie, Ze) : v.setAttribute(Ie, Ze), Yc(v) ? yn(v) : Em(e.removed);
        } catch {
          Li(Ie, v);
        }
    }
    zn(I.afterSanitizeAttributes, v, null);
  }, zk = function z(v) {
    let F = null;
    const B = pp(v);
    for (zn(I.beforeSanitizeShadowDOM, v, null); F = B.nextNode(); )
      zn(I.uponSanitizeShadowNode, F, null), gp(F), _p(F), F.content instanceof o && z(F.content);
    zn(I.afterSanitizeShadowDOM, v, null);
  };
  return e.sanitize = function(z) {
    let v = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, F = null, B = null, _e = null, Xe = null;
    if (Gc = !z, Gc && (z = "<!-->"), typeof z != "string" && !mp(z))
      if (typeof z.toString == "function") {
        if (z = z.toString(), typeof z != "string")
          throw Oo("dirty is not a string, aborting");
      } else
        throw Oo("toString is not a function");
    if (!e.isSupported)
      return z;
    if (Uc || Jc(v), e.removed = [], typeof z == "string" && (So = !1), So) {
      if (z.nodeName) {
        const Hn = Le(z.nodeName);
        if (!N[Hn] || $t[Hn])
          throw Oo("root node is forbidden and cannot be sanitized in-place");
      }
    } else if (z instanceof l)
      F = fp("<!---->"), B = F.ownerDocument.importNode(z, !0), B.nodeType === No.element && B.nodeName === "BODY" || B.nodeName === "HTML" ? F = B : F.appendChild(B);
    else {
      if (!Oi && !dr && !qr && // eslint-disable-next-line unicorn/prefer-includes
      z.indexOf("<") === -1)
        return k && Zs ? k.createHTML(z) : z;
      if (F = fp(z), !F)
        return Oi ? null : Zs ? C : "";
    }
    F && qc && yn(F.firstChild);
    const Ie = pp(So ? z : F);
    for (; _e = Ie.nextNode(); )
      gp(_e), _p(_e), _e.content instanceof o && zk(_e.content);
    if (So)
      return z;
    if (Oi) {
      if (Xs)
        for (Xe = S.call(F.ownerDocument); F.firstChild; )
          Xe.appendChild(F.firstChild);
      else
        Xe = F;
      return (ye.shadowroot || ye.shadowrootmode) && (Xe = T.call(r, Xe, !0)), Xe;
    }
    let gt = qr ? F.outerHTML : F.innerHTML;
    return qr && N["!doctype"] && F.ownerDocument && F.ownerDocument.doctype && F.ownerDocument.doctype.name && lt(dy, F.ownerDocument.doctype.name) && (gt = "<!DOCTYPE " + F.ownerDocument.doctype.name + `>
` + gt), dr && gl([U, Te, ce], (Hn) => {
      gt = Mo(gt, Hn, " ");
    }), k && Zs ? k.createHTML(gt) : gt;
  }, e.setConfig = function() {
    let z = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    Jc(z), Uc = !0;
  }, e.clearConfig = function() {
    Ii = null, Uc = !1;
  }, e.isValidAttribute = function(z, v, F) {
    Ii || Jc({});
    const B = Le(z), _e = Le(v);
    return bp(B, _e, F);
  }, e.addHook = function(z, v) {
    typeof v == "function" && To(I[z], v);
  }, e.removeHook = function(z, v) {
    if (v !== void 0) {
      const F = VE(I[z], v);
      return F === -1 ? void 0 : UE(I[z], F, 1)[0];
    }
    return Em(I[z]);
  }, e.removeHooks = function(z) {
    I[z] = [];
  }, e.removeAllHooks = function() {
    I = Fm();
  }, e;
}
var jY = uy();
const {
  HtmlTagHydration: WY,
  SvelteComponent: GY,
  add_render_callback: KY,
  append_hydration: JY,
  attr: YY,
  bubble: XY,
  check_outros: ZY,
  children: QY,
  claim_component: eX,
  claim_element: tX,
  claim_html_tag: nX,
  claim_space: rX,
  claim_text: iX,
  create_component: oX,
  create_in_transition: sX,
  create_out_transition: lX,
  destroy_component: aX,
  detach: cX,
  element: dX,
  get_svelte_dataset: uX,
  group_outros: hX,
  init: fX,
  insert_hydration: pX,
  listen: mX,
  mount_component: gX,
  run_all: bX,
  safe_not_equal: yX,
  set_data: _X,
  space: wX,
  stop_propagation: kX,
  text: vX,
  toggle_class: CX,
  transition_in: SX,
  transition_out: EX
} = window.__gradio__svelte__internal, { createEventDispatcher: xX, onMount: DX } = window.__gradio__svelte__internal, {
  SvelteComponent: AX,
  append_hydration: TX,
  attr: MX,
  bubble: OX,
  check_outros: FX,
  children: NX,
  claim_component: $X,
  claim_element: IX,
  claim_space: LX,
  create_animation: RX,
  create_component: BX,
  destroy_component: PX,
  detach: zX,
  element: HX,
  ensure_array_like: VX,
  fix_and_outro_and_destroy_block: UX,
  fix_position: qX,
  group_outros: jX,
  init: WX,
  insert_hydration: GX,
  mount_component: KX,
  noop: JX,
  safe_not_equal: YX,
  set_style: XX,
  space: ZX,
  transition_in: QX,
  transition_out: eZ,
  update_keyed_each: tZ
} = window.__gradio__svelte__internal, {
  SvelteComponent: nZ,
  attr: rZ,
  children: iZ,
  claim_element: oZ,
  detach: sZ,
  element: lZ,
  empty: aZ,
  init: cZ,
  insert_hydration: dZ,
  noop: uZ,
  safe_not_equal: hZ,
  set_style: fZ
} = window.__gradio__svelte__internal;
function We(n) {
  this.content = n;
}
We.prototype = {
  constructor: We,
  find: function(n) {
    for (var e = 0; e < this.content.length; e += 2)
      if (this.content[e] === n) return e;
    return -1;
  },
  // :: (string) → ?any
  // Retrieve the value stored under `key`, or return undefined when
  // no such key exists.
  get: function(n) {
    var e = this.find(n);
    return e == -1 ? void 0 : this.content[e + 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(n, e, t) {
    var r = t && t != n ? this.remove(t) : this, i = r.find(n), o = r.content.slice();
    return i == -1 ? o.push(t || n, e) : (o[i + 1] = e, t && (o[i] = t)), new We(o);
  },
  // :: (string) → OrderedMap
  // Return a map with the given key removed, if it existed.
  remove: function(n) {
    var e = this.find(n);
    if (e == -1) return this;
    var t = this.content.slice();
    return t.splice(e, 2), new We(t);
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the start of the map.
  addToStart: function(n, e) {
    return new We([n, e].concat(this.remove(n).content));
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the end of the map.
  addToEnd: function(n, e) {
    var t = this.remove(n).content.slice();
    return t.push(n, e), new We(t);
  },
  // :: (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(n, e, t) {
    var r = this.remove(e), i = r.content.slice(), o = r.find(n);
    return i.splice(o == -1 ? i.length : o, 0, e, t), new We(i);
  },
  // :: ((key: string, value: any))
  // Call the given function for each key/value pair in the map, in
  // order.
  forEach: function(n) {
    for (var e = 0; e < this.content.length; e += 2)
      n(this.content[e], this.content[e + 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(n) {
    return n = We.from(n), n.size ? new We(n.content.concat(this.subtract(n).content)) : this;
  },
  // :: (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(n) {
    return n = We.from(n), n.size ? new We(this.subtract(n).content.concat(n.content)) : this;
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a map containing all the keys in this map that don't
  // appear in `map`.
  subtract: function(n) {
    var e = this;
    n = We.from(n);
    for (var t = 0; t < n.content.length; t += 2)
      e = e.remove(n.content[t]);
    return e;
  },
  // :: () → Object
  // Turn ordered map into a plain object.
  toObject: function() {
    var n = {};
    return this.forEach(function(e, t) {
      n[e] = t;
    }), n;
  },
  // :: number
  // The amount of keys in this map.
  get size() {
    return this.content.length >> 1;
  }
};
We.from = function(n) {
  if (n instanceof We) return n;
  var e = [];
  if (n) for (var t in n) e.push(t, n[t]);
  return new We(e);
};
function hy(n, e, t) {
  for (let r = 0; ; r++) {
    if (r == n.childCount || r == e.childCount)
      return n.childCount == e.childCount ? null : t;
    let i = n.child(r), o = e.child(r);
    if (i == o) {
      t += i.nodeSize;
      continue;
    }
    if (!i.sameMarkup(o))
      return t;
    if (i.isText && i.text != o.text) {
      for (let s = 0; i.text[s] == o.text[s]; s++)
        t++;
      return t;
    }
    if (i.content.size || o.content.size) {
      let s = hy(i.content, o.content, t + 1);
      if (s != null)
        return s;
    }
    t += i.nodeSize;
  }
}
function fy(n, e, t, r) {
  for (let i = n.childCount, o = e.childCount; ; ) {
    if (i == 0 || o == 0)
      return i == o ? null : { a: t, b: r };
    let s = n.child(--i), l = e.child(--o), a = s.nodeSize;
    if (s == l) {
      t -= a, r -= a;
      continue;
    }
    if (!s.sameMarkup(l))
      return { a: t, b: r };
    if (s.isText && s.text != l.text) {
      let c = 0, d = Math.min(s.text.length, l.text.length);
      for (; c < d && s.text[s.text.length - c - 1] == l.text[l.text.length - c - 1]; )
        c++, t--, r--;
      return { a: t, b: r };
    }
    if (s.content.size || l.content.size) {
      let c = fy(s.content, l.content, t - 1, r - 1);
      if (c)
        return c;
    }
    t -= a, r -= a;
  }
}
class A {
  /**
  @internal
  */
  constructor(e, t) {
    if (this.content = e, this.size = t || 0, t == null)
      for (let r = 0; r < e.length; r++)
        this.size += e[r].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(e, t, r, i = 0, o) {
    for (let s = 0, l = 0; l < t; s++) {
      let a = this.content[s], c = l + a.nodeSize;
      if (c > e && r(a, i + l, o || null, s) !== !1 && a.content.size) {
        let d = l + 1;
        a.nodesBetween(Math.max(0, e - d), Math.min(a.content.size, t - d), r, i + d);
      }
      l = c;
    }
  }
  /**
  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(e) {
    this.nodesBetween(0, this.size, e);
  }
  /**
  Extract the text between `from` and `to`. See the same method on
  [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
  */
  textBetween(e, t, r, i) {
    let o = "", s = !0;
    return this.nodesBetween(e, t, (l, a) => {
      let c = l.isText ? l.text.slice(Math.max(e, a) - a, t - a) : l.isLeaf ? i ? typeof i == "function" ? i(l) : i : l.type.spec.leafText ? l.type.spec.leafText(l) : "" : "";
      l.isBlock && (l.isLeaf && c || l.isTextblock) && r && (s ? s = !1 : o += r), o += c;
    }, 0), o;
  }
  /**
  Create a new fragment containing the combined content of this
  fragment and the other.
  */
  append(e) {
    if (!e.size)
      return this;
    if (!this.size)
      return e;
    let t = this.lastChild, r = e.firstChild, i = this.content.slice(), o = 0;
    for (t.isText && t.sameMarkup(r) && (i[i.length - 1] = t.withText(t.text + r.text), o = 1); o < e.content.length; o++)
      i.push(e.content[o]);
    return new A(i, this.size + e.size);
  }
  /**
  Cut out the sub-fragment between the two given positions.
  */
  cut(e, t = this.size) {
    if (e == 0 && t == this.size)
      return this;
    let r = [], i = 0;
    if (t > e)
      for (let o = 0, s = 0; s < t; o++) {
        let l = this.content[o], a = s + l.nodeSize;
        a > e && ((s < e || a > t) && (l.isText ? l = l.cut(Math.max(0, e - s), Math.min(l.text.length, t - s)) : l = l.cut(Math.max(0, e - s - 1), Math.min(l.content.size, t - s - 1))), r.push(l), i += l.nodeSize), s = a;
      }
    return new A(r, i);
  }
  /**
  @internal
  */
  cutByIndex(e, t) {
    return e == t ? A.empty : e == 0 && t == this.content.length ? this : new A(this.content.slice(e, t));
  }
  /**
  Create a new fragment in which the node at the given index is
  replaced by the given node.
  */
  replaceChild(e, t) {
    let r = this.content[e];
    if (r == t)
      return this;
    let i = this.content.slice(), o = this.size + t.nodeSize - r.nodeSize;
    return i[e] = t, new A(i, o);
  }
  /**
  Create a new fragment by prepending the given node to this
  fragment.
  */
  addToStart(e) {
    return new A([e].concat(this.content), this.size + e.nodeSize);
  }
  /**
  Create a new fragment by appending the given node to this
  fragment.
  */
  addToEnd(e) {
    return new A(this.content.concat(e), this.size + e.nodeSize);
  }
  /**
  Compare this fragment to another one.
  */
  eq(e) {
    if (this.content.length != e.content.length)
      return !1;
    for (let t = 0; t < this.content.length; t++)
      if (!this.content[t].eq(e.content[t]))
        return !1;
    return !0;
  }
  /**
  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(e) {
    let t = this.content[e];
    if (!t)
      throw new RangeError("Index " + e + " out of range for " + this);
    return t;
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(e) {
    return this.content[e] || null;
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(e) {
    for (let t = 0, r = 0; t < this.content.length; t++) {
      let i = this.content[t];
      e(i, r, t), r += i.nodeSize;
    }
  }
  /**
  Find the first position at which this fragment and another
  fragment differ, or `null` if they are the same.
  */
  findDiffStart(e, t = 0) {
    return hy(this, e, t);
  }
  /**
  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(e, t = this.size, r = e.size) {
    return fy(this, e, t, r);
  }
  /**
  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(e) {
    if (e == 0)
      return yl(0, e);
    if (e == this.size)
      return yl(this.content.length, e);
    if (e > this.size || e < 0)
      throw new RangeError(`Position ${e} outside of fragment (${this})`);
    for (let t = 0, r = 0; ; t++) {
      let i = this.child(t), o = r + i.nodeSize;
      if (o >= e)
        return o == e ? yl(t + 1, o) : yl(t, r);
      r = o;
    }
  }
  /**
  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((e) => e.toJSON()) : null;
  }
  /**
  Deserialize a fragment from its JSON representation.
  */
  static fromJSON(e, t) {
    if (!t)
      return A.empty;
    if (!Array.isArray(t))
      throw new RangeError("Invalid input for Fragment.fromJSON");
    return new A(t.map(e.nodeFromJSON));
  }
  /**
  Build a fragment from an array of nodes. Ensures that adjacent
  text nodes with the same marks are joined together.
  */
  static fromArray(e) {
    if (!e.length)
      return A.empty;
    let t, r = 0;
    for (let i = 0; i < e.length; i++) {
      let o = e[i];
      r += o.nodeSize, i && o.isText && e[i - 1].sameMarkup(o) ? (t || (t = e.slice(0, i)), t[t.length - 1] = o.withText(t[t.length - 1].text + o.text)) : t && t.push(o);
    }
    return new A(t || e, r);
  }
  /**
  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(e) {
    if (!e)
      return A.empty;
    if (e instanceof A)
      return e;
    if (Array.isArray(e))
      return this.fromArray(e);
    if (e.attrs)
      return new A([e], e.nodeSize);
    throw new RangeError("Can not convert " + e + " to a Fragment" + (e.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
  }
}
A.empty = new A([], 0);
const pd = { index: 0, offset: 0 };
function yl(n, e) {
  return pd.index = n, pd.offset = e, pd;
}
function ua(n, e) {
  if (n === e)
    return !0;
  if (!(n && typeof n == "object") || !(e && typeof e == "object"))
    return !1;
  let t = Array.isArray(n);
  if (Array.isArray(e) != t)
    return !1;
  if (t) {
    if (n.length != e.length)
      return !1;
    for (let r = 0; r < n.length; r++)
      if (!ua(n[r], e[r]))
        return !1;
  } else {
    for (let r in n)
      if (!(r in e) || !ua(n[r], e[r]))
        return !1;
    for (let r in e)
      if (!(r in n))
        return !1;
  }
  return !0;
}
let ue = class mu {
  /**
  @internal
  */
  constructor(e, t) {
    this.type = e, this.attrs = t;
  }
  /**
  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(e) {
    let t, r = !1;
    for (let i = 0; i < e.length; i++) {
      let o = e[i];
      if (this.eq(o))
        return e;
      if (this.type.excludes(o.type))
        t || (t = e.slice(0, i));
      else {
        if (o.type.excludes(this.type))
          return e;
        !r && o.type.rank > this.type.rank && (t || (t = e.slice(0, i)), t.push(this), r = !0), t && t.push(o);
      }
    }
    return t || (t = e.slice()), r || t.push(this), t;
  }
  /**
  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(e) {
    for (let t = 0; t < e.length; t++)
      if (this.eq(e[t]))
        return e.slice(0, t).concat(e.slice(t + 1));
    return e;
  }
  /**
  Test whether this mark is in the given set of marks.
  */
  isInSet(e) {
    for (let t = 0; t < e.length; t++)
      if (this.eq(e[t]))
        return !0;
    return !1;
  }
  /**
  Test whether this mark has the same type and attributes as
  another mark.
  */
  eq(e) {
    return this == e || this.type == e.type && ua(this.attrs, e.attrs);
  }
  /**
  Convert this mark to a JSON-serializeable representation.
  */
  toJSON() {
    let e = { type: this.type.name };
    for (let t in this.attrs) {
      e.attrs = this.attrs;
      break;
    }
    return e;
  }
  /**
  Deserialize a mark from JSON.
  */
  static fromJSON(e, t) {
    if (!t)
      throw new RangeError("Invalid input for Mark.fromJSON");
    let r = e.marks[t.type];
    if (!r)
      throw new RangeError(`There is no mark type ${t.type} in this schema`);
    let i = r.create(t.attrs);
    return r.checkAttrs(i.attrs), i;
  }
  /**
  Test whether two sets of marks are identical.
  */
  static sameSet(e, t) {
    if (e == t)
      return !0;
    if (e.length != t.length)
      return !1;
    for (let r = 0; r < e.length; r++)
      if (!e[r].eq(t[r]))
        return !1;
    return !0;
  }
  /**
  Create a properly sorted mark set from null, a single mark, or an
  unsorted array of marks.
  */
  static setFrom(e) {
    if (!e || Array.isArray(e) && e.length == 0)
      return mu.none;
    if (e instanceof mu)
      return [e];
    let t = e.slice();
    return t.sort((r, i) => r.type.rank - i.type.rank), t;
  }
};
ue.none = [];
class ha extends Error {
}
class O {
  /**
  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(e, t, r) {
    this.content = e, this.openStart = t, this.openEnd = r;
  }
  /**
  The size this slice would add when inserted into a document.
  */
  get size() {
    return this.content.size - this.openStart - this.openEnd;
  }
  /**
  @internal
  */
  insertAt(e, t) {
    let r = my(this.content, e + this.openStart, t);
    return r && new O(r, this.openStart, this.openEnd);
  }
  /**
  @internal
  */
  removeBetween(e, t) {
    return new O(py(this.content, e + this.openStart, t + this.openStart), this.openStart, this.openEnd);
  }
  /**
  Tests whether this slice is equal to another slice.
  */
  eq(e) {
    return this.content.eq(e.content) && this.openStart == e.openStart && this.openEnd == e.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 e = { content: this.content.toJSON() };
    return this.openStart > 0 && (e.openStart = this.openStart), this.openEnd > 0 && (e.openEnd = this.openEnd), e;
  }
  /**
  Deserialize a slice from its JSON representation.
  */
  static fromJSON(e, t) {
    if (!t)
      return O.empty;
    let r = t.openStart || 0, i = t.openEnd || 0;
    if (typeof r != "number" || typeof i != "number")
      throw new RangeError("Invalid input for Slice.fromJSON");
    return new O(A.fromJSON(e, t.content), r, i);
  }
  /**
  Create a slice from a fragment by taking the maximum possible
  open value on both side of the fragment.
  */
  static maxOpen(e, t = !0) {
    let r = 0, i = 0;
    for (let o = e.firstChild; o && !o.isLeaf && (t || !o.type.spec.isolating); o = o.firstChild)
      r++;
    for (let o = e.lastChild; o && !o.isLeaf && (t || !o.type.spec.isolating); o = o.lastChild)
      i++;
    return new O(e, r, i);
  }
}
O.empty = new O(A.empty, 0, 0);
function py(n, e, t) {
  let { index: r, offset: i } = n.findIndex(e), o = n.maybeChild(r), { index: s, offset: l } = n.findIndex(t);
  if (i == e || o.isText) {
    if (l != t && !n.child(s).isText)
      throw new RangeError("Removing non-flat range");
    return n.cut(0, e).append(n.cut(t));
  }
  if (r != s)
    throw new RangeError("Removing non-flat range");
  return n.replaceChild(r, o.copy(py(o.content, e - i - 1, t - i - 1)));
}
function my(n, e, t, r) {
  let { index: i, offset: o } = n.findIndex(e), s = n.maybeChild(i);
  if (o == e || s.isText)
    return n.cut(0, e).append(t).append(n.cut(e));
  let l = my(s.content, e - o - 1, t);
  return l && n.replaceChild(i, s.copy(l));
}
function sx(n, e, t) {
  if (t.openStart > n.depth)
    throw new ha("Inserted content deeper than insertion position");
  if (n.depth - t.openStart != e.depth - t.openEnd)
    throw new ha("Inconsistent open depths");
  return gy(n, e, t, 0);
}
function gy(n, e, t, r) {
  let i = n.index(r), o = n.node(r);
  if (i == e.index(r) && r < n.depth - t.openStart) {
    let s = gy(n, e, t, r + 1);
    return o.copy(o.content.replaceChild(i, s));
  } else if (t.content.size)
    if (!t.openStart && !t.openEnd && n.depth == r && e.depth == r) {
      let s = n.parent, l = s.content;
      return ii(s, l.cut(0, n.parentOffset).append(t.content).append(l.cut(e.parentOffset)));
    } else {
      let { start: s, end: l } = lx(t, n);
      return ii(o, yy(n, s, l, e, r));
    }
  else return ii(o, fa(n, e, r));
}
function by(n, e) {
  if (!e.type.compatibleContent(n.type))
    throw new ha("Cannot join " + e.type.name + " onto " + n.type.name);
}
function gu(n, e, t) {
  let r = n.node(t);
  return by(r, e.node(t)), r;
}
function ri(n, e) {
  let t = e.length - 1;
  t >= 0 && n.isText && n.sameMarkup(e[t]) ? e[t] = n.withText(e[t].text + n.text) : e.push(n);
}
function Jo(n, e, t, r) {
  let i = (e || n).node(t), o = 0, s = e ? e.index(t) : i.childCount;
  n && (o = n.index(t), n.depth > t ? o++ : n.textOffset && (ri(n.nodeAfter, r), o++));
  for (let l = o; l < s; l++)
    ri(i.child(l), r);
  e && e.depth == t && e.textOffset && ri(e.nodeBefore, r);
}
function ii(n, e) {
  return n.type.checkContent(e), n.copy(e);
}
function yy(n, e, t, r, i) {
  let o = n.depth > i && gu(n, e, i + 1), s = r.depth > i && gu(t, r, i + 1), l = [];
  return Jo(null, n, i, l), o && s && e.index(i) == t.index(i) ? (by(o, s), ri(ii(o, yy(n, e, t, r, i + 1)), l)) : (o && ri(ii(o, fa(n, e, i + 1)), l), Jo(e, t, i, l), s && ri(ii(s, fa(t, r, i + 1)), l)), Jo(r, null, i, l), new A(l);
}
function fa(n, e, t) {
  let r = [];
  if (Jo(null, n, t, r), n.depth > t) {
    let i = gu(n, e, t + 1);
    ri(ii(i, fa(n, e, t + 1)), r);
  }
  return Jo(e, null, t, r), new A(r);
}
function lx(n, e) {
  let t = e.depth - n.openStart, i = e.node(t).copy(n.content);
  for (let o = t - 1; o >= 0; o--)
    i = e.node(o).copy(A.from(i));
  return {
    start: i.resolveNoCache(n.openStart + t),
    end: i.resolveNoCache(i.content.size - n.openEnd - t)
  };
}
class us {
  /**
  @internal
  */
  constructor(e, t, r) {
    this.pos = e, this.path = t, this.parentOffset = r, this.depth = t.length / 3 - 1;
  }
  /**
  @internal
  */
  resolveDepth(e) {
    return e == null ? this.depth : e < 0 ? this.depth + e : e;
  }
  /**
  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(e) {
    return this.path[this.resolveDepth(e) * 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(e) {
    return this.path[this.resolveDepth(e) * 3 + 1];
  }
  /**
  The index pointing after this position into the ancestor at the
  given level.
  */
  indexAfter(e) {
    return e = this.resolveDepth(e), this.index(e) + (e == this.depth && !this.textOffset ? 0 : 1);
  }
  /**
  The (absolute) position at the start of the node at the given
  level.
  */
  start(e) {
    return e = this.resolveDepth(e), e == 0 ? 0 : this.path[e * 3 - 1] + 1;
  }
  /**
  The (absolute) position at the end of the node at the given
  level.
  */
  end(e) {
    return e = this.resolveDepth(e), this.start(e) + this.node(e).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(e) {
    if (e = this.resolveDepth(e), !e)
      throw new RangeError("There is no position before the top-level node");
    return e == this.depth + 1 ? this.pos : this.path[e * 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(e) {
    if (e = this.resolveDepth(e), !e)
      throw new RangeError("There is no position after the top-level node");
    return e == this.depth + 1 ? this.pos : this.path[e * 3 - 1] + this.path[e * 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 e = this.parent, t = this.index(this.depth);
    if (t == e.childCount)
      return null;
    let r = this.pos - this.path[this.path.length - 1], i = e.child(t);
    return r ? e.child(t).cut(r) : i;
  }
  /**
  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 e = this.index(this.depth), t = this.pos - this.path[this.path.length - 1];
    return t ? this.parent.child(e).cut(0, t) : e == 0 ? null : this.parent.child(e - 1);
  }
  /**
  Get the position at the given index in the parent node at the
  given depth (which defaults to `this.depth`).
  */
  posAtIndex(e, t) {
    t = this.resolveDepth(t);
    let r = this.path[t * 3], i = t == 0 ? 0 : this.path[t * 3 - 1] + 1;
    for (let o = 0; o < e; o++)
      i += r.child(o).nodeSize;
    return i;
  }
  /**
  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 e = this.parent, t = this.index();
    if (e.content.size == 0)
      return ue.none;
    if (this.textOffset)
      return e.child(t).marks;
    let r = e.maybeChild(t - 1), i = e.maybeChild(t);
    if (!r) {
      let l = r;
      r = i, i = l;
    }
    let o = r.marks;
    for (var s = 0; s < o.length; s++)
      o[s].type.spec.inclusive === !1 && (!i || !o[s].isInSet(i.marks)) && (o = o[s--].removeFromSet(o));
    return o;
  }
  /**
  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(e) {
    let t = this.parent.maybeChild(this.index());
    if (!t || !t.isInline)
      return null;
    let r = t.marks, i = e.parent.maybeChild(e.index());
    for (var o = 0; o < r.length; o++)
      r[o].type.spec.inclusive === !1 && (!i || !r[o].isInSet(i.marks)) && (r = r[o--].removeFromSet(r));
    return r;
  }
  /**
  The depth up to which this position and the given (non-resolved)
  position share the same parent nodes.
  */
  sharedDepth(e) {
    for (let t = this.depth; t > 0; t--)
      if (this.start(t) <= e && this.end(t) >= e)
        return t;
    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(e = this, t) {
    if (e.pos < this.pos)
      return e.blockRange(this);
    for (let r = this.depth - (this.parent.inlineContent || this.pos == e.pos ? 1 : 0); r >= 0; r--)
      if (e.pos <= this.end(r) && (!t || t(this.node(r))))
        return new pa(this, e, r);
    return null;
  }
  /**
  Query whether the given position shares the same parent node.
  */
  sameParent(e) {
    return this.pos - this.parentOffset == e.pos - e.parentOffset;
  }
  /**
  Return the greater of this and the given position.
  */
  max(e) {
    return e.pos > this.pos ? e : this;
  }
  /**
  Return the smaller of this and the given position.
  */
  min(e) {
    return e.pos < this.pos ? e : this;
  }
  /**
  @internal
  */
  toString() {
    let e = "";
    for (let t = 1; t <= this.depth; t++)
      e += (e ? "/" : "") + this.node(t).type.name + "_" + this.index(t - 1);
    return e + ":" + this.parentOffset;
  }
  /**
  @internal
  */
  static resolve(e, t) {
    if (!(t >= 0 && t <= e.content.size))
      throw new RangeError("Position " + t + " out of range");
    let r = [], i = 0, o = t;
    for (let s = e; ; ) {
      let { index: l, offset: a } = s.content.findIndex(o), c = o - a;
      if (r.push(s, l, i + a), !c || (s = s.child(l), s.isText))
        break;
      o = c - 1, i += a + 1;
    }
    return new us(t, r, o);
  }
  /**
  @internal
  */
  static resolveCached(e, t) {
    let r = Nm.get(e);
    if (r)
      for (let o = 0; o < r.elts.length; o++) {
        let s = r.elts[o];
        if (s.pos == t)
          return s;
      }
    else
      Nm.set(e, r = new ax());
    let i = r.elts[r.i] = us.resolve(e, t);
    return r.i = (r.i + 1) % cx, i;
  }
}
class ax {
  constructor() {
    this.elts = [], this.i = 0;
  }
}
const cx = 12, Nm = /* @__PURE__ */ new WeakMap();
class pa {
  /**
  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(e, t, r) {
    this.$from = e, this.$to = t, this.depth = r;
  }
  /**
  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);
  }
}
const dx = /* @__PURE__ */ Object.create(null);
let Qn = class bu {
  /**
  @internal
  */
  constructor(e, t, r, i = ue.none) {
    this.type = e, this.attrs = t, this.marks = i, this.content = r || A.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(e) {
    return this.content.child(e);
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(e) {
    return this.content.maybeChild(e);
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(e) {
    this.content.forEach(e);
  }
  /**
  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(e, t, r, i = 0) {
    this.content.nodesBetween(e, t, r, i, this);
  }
  /**
  Call the given callback for every descendant node. Doesn't
  descend into a node when the callback returns `false`.
  */
  descendants(e) {
    this.nodesBetween(0, this.content.size, e);
  }
  /**
  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(e, t, r, i) {
    return this.content.textBetween(e, t, r, i);
  }
  /**
  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(e) {
    return this == e || this.sameMarkup(e) && this.content.eq(e.content);
  }
  /**
  Compare the markup (type, attributes, and marks) of this node to
  those of another. Returns `true` if both have the same markup.
  */
  sameMarkup(e) {
    return this.hasMarkup(e.type, e.attrs, e.marks);
  }
  /**
  Check whether this node's markup correspond to the given type,
  attributes, and marks.
  */
  hasMarkup(e, t, r) {
    return this.type == e && ua(this.attrs, t || e.defaultAttrs || dx) && ue.sameSet(this.marks, r || ue.none);
  }
  /**
  Create a new node with the same markup as this node, containing
  the given content (or empty, if no content is given).
  */
  copy(e = null) {
    return e == this.content ? this : new bu(this.type, this.attrs, e, this.marks);
  }
  /**
  Create a copy of this node, with the given set of marks instead
  of the node's own marks.
  */
  mark(e) {
    return e == this.marks ? this : new bu(this.type, this.attrs, this.content, e);
  }
  /**
  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(e, t = this.content.size) {
    return e == 0 && t == this.content.size ? this : this.copy(this.content.cut(e, t));
  }
  /**
  Cut out the part of the document between the given positions, and
  return it as a `Slice` object.
  */
  slice(e, t = this.content.size, r = !1) {
    if (e == t)
      return O.empty;
    let i = this.resolve(e), o = this.resolve(t), s = r ? 0 : i.sharedDepth(t), l = i.start(s), c = i.node(s).content.cut(i.pos - l, o.pos - l);
    return new O(c, i.depth - s, o.depth - s);
  }
  /**
  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(e, t, r) {
    return sx(this.resolve(e), this.resolve(t), r);
  }
  /**
  Find the node directly after the given position.
  */
  nodeAt(e) {
    for (let t = this; ; ) {
      let { index: r, offset: i } = t.content.findIndex(e);
      if (t = t.maybeChild(r), !t)
        return null;
      if (i == e || t.isText)
        return t;
      e -= i + 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(e) {
    let { index: t, offset: r } = this.content.findIndex(e);
    return { node: this.content.maybeChild(t), index: t, offset: r };
  }
  /**
  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(e) {
    if (e == 0)
      return { node: null, index: 0, offset: 0 };
    let { index: t, offset: r } = this.content.findIndex(e);
    if (r < e)
      return { node: this.content.child(t), index: t, offset: r };
    let i = this.content.child(t - 1);
    return { node: i, index: t - 1, offset: r - i.nodeSize };
  }
  /**
  Resolve the given position in the document, returning an
  [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
  */
  resolve(e) {
    return us.resolveCached(this, e);
  }
  /**
  @internal
  */
  resolveNoCache(e) {
    return us.resolve(this, e);
  }
  /**
  Test whether a given mark or mark type occurs in this document
  between the two given positions.
  */
  rangeHasMark(e, t, r) {
    let i = !1;
    return t > e && this.nodesBetween(e, t, (o) => (r.isInSet(o.marks) && (i = !0), !i)), i;
  }
  /**
  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 e = this.type.name;
    return this.content.size && (e += "(" + this.content.toStringInner() + ")"), _y(this.marks, e);
  }
  /**
  Get the content match in this node at the given index.
  */
  contentMatchAt(e) {
    let t = this.type.contentMatch.matchFragment(this.content, 0, e);
    if (!t)
      throw new Error("Called contentMatchAt on a node with invalid content");
    return t;
  }
  /**
  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(e, t, r = A.empty, i = 0, o = r.childCount) {
    let s = this.contentMatchAt(e).matchFragment(r, i, o), l = s && s.matchFragment(this.content, t);
    if (!l || !l.validEnd)
      return !1;
    for (let a = i; a < o; a++)
      if (!this.type.allowsMarks(r.child(a).marks))
        return !1;
    return !0;
  }
  /**
  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(e, t, r, i) {
    if (i && !this.type.allowsMarks(i))
      return !1;
    let o = this.contentMatchAt(e).matchType(r), s = o && o.matchFragment(this.content, t);
    return s ? s.validEnd : !1;
  }
  /**
  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(e) {
    return e.content.size ? this.canReplace(this.childCount, this.childCount, e.content) : this.type.compatibleContent(e.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 e = ue.none;
    for (let t = 0; t < this.marks.length; t++) {
      let r = this.marks[t];
      r.type.checkAttrs(r.attrs), e = r.addToSet(e);
    }
    if (!ue.sameSet(e, this.marks))
      throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((t) => t.type.name)}`);
    this.content.forEach((t) => t.check());
  }
  /**
  Return a JSON-serializeable representation of this node.
  */
  toJSON() {
    let e = { type: this.type.name };
    for (let t in this.attrs) {
      e.attrs = this.attrs;
      break;
    }
    return this.content.size && (e.content = this.content.toJSON()), this.marks.length && (e.marks = this.marks.map((t) => t.toJSON())), e;
  }
  /**
  Deserialize a node from its JSON representation.
  */
  static fromJSON(e, t) {
    if (!t)
      throw new RangeError("Invalid input for Node.fromJSON");
    let r;
    if (t.marks) {
      if (!Array.isArray(t.marks))
        throw new RangeError("Invalid mark data for Node.fromJSON");
      r = t.marks.map(e.markFromJSON);
    }
    if (t.type == "text") {
      if (typeof t.text != "string")
        throw new RangeError("Invalid text node in JSON");
      return e.text(t.text, r);
    }
    let i = A.fromJSON(e, t.content), o = e.nodeType(t.type).create(t.attrs, i, r);
    return o.type.checkAttrs(o.attrs), o;
  }
};
Qn.prototype.text = void 0;
class ma extends Qn {
  /**
  @internal
  */
  constructor(e, t, r, i) {
    if (super(e, t, null, i), !r)
      throw new RangeError("Empty text nodes are not allowed");
    this.text = r;
  }
  toString() {
    return this.type.spec.toDebugString ? this.type.spec.toDebugString(this) : _y(this.marks, JSON.stringify(this.text));
  }
  get textContent() {
    return this.text;
  }
  textBetween(e, t) {
    return this.text.slice(e, t);
  }
  get nodeSize() {
    return this.text.length;
  }
  mark(e) {
    return e == this.marks ? this : new ma(this.type, this.attrs, this.text, e);
  }
  withText(e) {
    return e == this.text ? this : new ma(this.type, this.attrs, e, this.marks);
  }
  cut(e = 0, t = this.text.length) {
    return e == 0 && t == this.text.length ? this : this.withText(this.text.slice(e, t));
  }
  eq(e) {
    return this.sameMarkup(e) && this.text == e.text;
  }
  toJSON() {
    let e = super.toJSON();
    return e.text = this.text, e;
  }
}
function _y(n, e) {
  for (let t = n.length - 1; t >= 0; t--)
    e = n[t].type.name + "(" + e + ")";
  return e;
}
class hi {
  /**
  @internal
  */
  constructor(e) {
    this.validEnd = e, this.next = [], this.wrapCache = [];
  }
  /**
  @internal
  */
  static parse(e, t) {
    let r = new ux(e, t);
    if (r.next == null)
      return hi.empty;
    let i = wy(r);
    r.next && r.err("Unexpected trailing text");
    let o = yx(bx(i));
    return _x(o, r), o;
  }
  /**
  Match a node type, returning a match after that node if
  successful.
  */
  matchType(e) {
    for (let t = 0; t < this.next.length; t++)
      if (this.next[t].type == e)
        return this.next[t].next;
    return null;
  }
  /**
  Try to match a fragment. Returns the resulting match when
  successful.
  */
  matchFragment(e, t = 0, r = e.childCount) {
    let i = this;
    for (let o = t; i && o < r; o++)
      i = i.matchType(e.child(o).type);
    return i;
  }
  /**
  @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 e = 0; e < this.next.length; e++) {
      let { type: t } = this.next[e];
      if (!(t.isText || t.hasRequiredAttrs()))
        return t;
    }
    return null;
  }
  /**
  @internal
  */
  compatible(e) {
    for (let t = 0; t < this.next.length; t++)
      for (let r = 0; r < e.next.length; r++)
        if (this.next[t].type == e.next[r].type)
          return !0;
    return !1;
  }
  /**
  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(e, t = !1, r = 0) {
    let i = [this];
    function o(s, l) {
      let a = s.matchFragment(e, r);
      if (a && (!t || a.validEnd))
        return A.from(l.map((c) => c.createAndFill()));
      for (let c = 0; c < s.next.length; c++) {
        let { type: d, next: u } = s.next[c];
        if (!(d.isText || d.hasRequiredAttrs()) && i.indexOf(u) == -1) {
          i.push(u);
          let h = o(u, l.concat(d));
          if (h)
            return h;
        }
      }
      return null;
    }
    return o(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(e) {
    for (let r = 0; r < this.wrapCache.length; r += 2)
      if (this.wrapCache[r] == e)
        return this.wrapCache[r + 1];
    let t = this.computeWrapping(e);
    return this.wrapCache.push(e, t), t;
  }
  /**
  @internal
  */
  computeWrapping(e) {
    let t = /* @__PURE__ */ Object.create(null), r = [{ match: this, type: null, via: null }];
    for (; r.length; ) {
      let i = r.shift(), o = i.match;
      if (o.matchType(e)) {
        let s = [];
        for (let l = i; l.type; l = l.via)
          s.push(l.type);
        return s.reverse();
      }
      for (let s = 0; s < o.next.length; s++) {
        let { type: l, next: a } = o.next[s];
        !l.isLeaf && !l.hasRequiredAttrs() && !(l.name in t) && (!i.type || a.validEnd) && (r.push({ match: l.contentMatch, type: l, via: i }), t[l.name] = !0);
      }
    }
    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(e) {
    if (e >= this.next.length)
      throw new RangeError(`There's no ${e}th edge in this content match`);
    return this.next[e];
  }
  /**
  @internal
  */
  toString() {
    let e = [];
    function t(r) {
      e.push(r);
      for (let i = 0; i < r.next.length; i++)
        e.indexOf(r.next[i].next) == -1 && t(r.next[i].next);
    }
    return t(this), e.map((r, i) => {
      let o = i + (r.validEnd ? "*" : " ") + " ";
      for (let s = 0; s < r.next.length; s++)
        o += (s ? ", " : "") + r.next[s].type.name + "->" + e.indexOf(r.next[s].next);
      return o;
    }).join(`
`);
  }
}
hi.empty = new hi(!0);
class ux {
  constructor(e, t) {
    this.string = e, this.nodeTypes = t, this.inline = null, this.pos = 0, this.tokens = e.split(/\s*(?=\b|\W|$)/), this.tokens[this.tokens.length - 1] == "" && this.tokens.pop(), this.tokens[0] == "" && this.tokens.shift();
  }
  get next() {
    return this.tokens[this.pos];
  }
  eat(e) {
    return this.next == e && (this.pos++ || !0);
  }
  err(e) {
    throw new SyntaxError(e + " (in content expression '" + this.string + "')");
  }
}
function wy(n) {
  let e = [];
  do
    e.push(hx(n));
  while (n.eat("|"));
  return e.length == 1 ? e[0] : { type: "choice", exprs: e };
}
function hx(n) {
  let e = [];
  do
    e.push(fx(n));
  while (n.next && n.next != ")" && n.next != "|");
  return e.length == 1 ? e[0] : { type: "seq", exprs: e };
}
function fx(n) {
  let e = gx(n);
  for (; ; )
    if (n.eat("+"))
      e = { type: "plus", expr: e };
    else if (n.eat("*"))
      e = { type: "star", expr: e };
    else if (n.eat("?"))
      e = { type: "opt", expr: e };
    else if (n.eat("{"))
      e = px(n, e);
    else
      break;
  return e;
}
function $m(n) {
  /\D/.test(n.next) && n.err("Expected number, got '" + n.next + "'");
  let e = Number(n.next);
  return n.pos++, e;
}
function px(n, e) {
  let t = $m(n), r = t;
  return n.eat(",") && (n.next != "}" ? r = $m(n) : r = -1), n.eat("}") || n.err("Unclosed braced range"), { type: "range", min: t, max: r, expr: e };
}
function mx(n, e) {
  let t = n.nodeTypes, r = t[e];
  if (r)
    return [r];
  let i = [];
  for (let o in t) {
    let s = t[o];
    s.isInGroup(e) && i.push(s);
  }
  return i.length == 0 && n.err("No node type or group '" + e + "' found"), i;
}
function gx(n) {
  if (n.eat("(")) {
    let e = wy(n);
    return n.eat(")") || n.err("Missing closing paren"), e;
  } else if (/\W/.test(n.next))
    n.err("Unexpected token '" + n.next + "'");
  else {
    let e = mx(n, n.next).map((t) => (n.inline == null ? n.inline = t.isInline : n.inline != t.isInline && n.err("Mixing inline and block content"), { type: "name", value: t }));
    return n.pos++, e.length == 1 ? e[0] : { type: "choice", exprs: e };
  }
}
function bx(n) {
  let e = [[]];
  return i(o(n, 0), t()), e;
  function t() {
    return e.push([]) - 1;
  }
  function r(s, l, a) {
    let c = { term: a, to: l };
    return e[s].push(c), c;
  }
  function i(s, l) {
    s.forEach((a) => a.to = l);
  }
  function o(s, l) {
    if (s.type == "choice")
      return s.exprs.reduce((a, c) => a.concat(o(c, l)), []);
    if (s.type == "seq")
      for (let a = 0; ; a++) {
        let c = o(s.exprs[a], l);
        if (a == s.exprs.length - 1)
          return c;
        i(c, l = t());
      }
    else if (s.type == "star") {
      let a = t();
      return r(l, a), i(o(s.expr, a), a), [r(a)];
    } else if (s.type == "plus") {
      let a = t();
      return i(o(s.expr, l), a), i(o(s.expr, a), a), [r(a)];
    } else {
      if (s.type == "opt")
        return [r(l)].concat(o(s.expr, l));
      if (s.type == "range") {
        let a = l;
        for (let c = 0; c < s.min; c++) {
          let d = t();
          i(o(s.expr, a), d), a = d;
        }
        if (s.max == -1)
          i(o(s.expr, a), a);
        else
          for (let c = s.min; c < s.max; c++) {
            let d = t();
            r(a, d), i(o(s.expr, a), d), a = d;
          }
        return [r(a)];
      } else {
        if (s.type == "name")
          return [r(l, void 0, s.value)];
        throw new Error("Unknown expr type");
      }
    }
  }
}
function ky(n, e) {
  return e - n;
}
function Im(n, e) {
  let t = [];
  return r(e), t.sort(ky);
  function r(i) {
    let o = n[i];
    if (o.length == 1 && !o[0].term)
      return r(o[0].to);
    t.push(i);
    for (let s = 0; s < o.length; s++) {
      let { term: l, to: a } = o[s];
      !l && t.indexOf(a) == -1 && r(a);
    }
  }
}
function yx(n) {
  let e = /* @__PURE__ */ Object.create(null);
  return t(Im(n, 0));
  function t(r) {
    let i = [];
    r.forEach((s) => {
      n[s].forEach(({ term: l, to: a }) => {
        if (!l)
          return;
        let c;
        for (let d = 0; d < i.length; d++)
          i[d][0] == l && (c = i[d][1]);
        Im(n, a).forEach((d) => {
          c || i.push([l, c = []]), c.indexOf(d) == -1 && c.push(d);
        });
      });
    });
    let o = e[r.join(",")] = new hi(r.indexOf(n.length - 1) > -1);
    for (let s = 0; s < i.length; s++) {
      let l = i[s][1].sort(ky);
      o.next.push({ type: i[s][0], next: e[l.join(",")] || t(l) });
    }
    return o;
  }
}
function _x(n, e) {
  for (let t = 0, r = [n]; t < r.length; t++) {
    let i = r[t], o = !i.validEnd, s = [];
    for (let l = 0; l < i.next.length; l++) {
      let { type: a, next: c } = i.next[l];
      s.push(a.name), o && !(a.isText || a.hasRequiredAttrs()) && (o = !1), r.indexOf(c) == -1 && r.push(c);
    }
    o && e.err("Only non-generatable nodes (" + s.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
  }
}
function vy(n) {
  let e = /* @__PURE__ */ Object.create(null);
  for (let t in n) {
    let r = n[t];
    if (!r.hasDefault)
      return null;
    e[t] = r.default;
  }
  return e;
}
function Cy(n, e) {
  let t = /* @__PURE__ */ Object.create(null);
  for (let r in n) {
    let i = e && e[r];
    if (i === void 0) {
      let o = n[r];
      if (o.hasDefault)
        i = o.default;
      else
        throw new RangeError("No value supplied for attribute " + r);
    }
    t[r] = i;
  }
  return t;
}
function Sy(n, e, t, r) {
  for (let i in e)
    if (!(i in n))
      throw new RangeError(`Unsupported attribute ${i} for ${t} of type ${i}`);
  for (let i in n) {
    let o = n[i];
    o.validate && o.validate(e[i]);
  }
}
function Ey(n, e) {
  let t = /* @__PURE__ */ Object.create(null);
  if (e)
    for (let r in e)
      t[r] = new kx(n, r, e[r]);
  return t;
}
let Lm = class xy {
  /**
  @internal
  */
  constructor(e, t, r) {
    this.name = e, this.schema = t, this.spec = r, this.markSet = null, this.groups = r.group ? r.group.split(" ") : [], this.attrs = Ey(e, r.attrs), this.defaultAttrs = vy(this.attrs), this.contentMatch = null, this.inlineContent = null, this.isBlock = !(r.inline || e == "text"), this.isText = e == "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 == hi.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(e) {
    return this.groups.indexOf(e) > -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 e in this.attrs)
      if (this.attrs[e].isRequired)
        return !0;
    return !1;
  }
  /**
  Indicates whether this node allows some of the same content as
  the given node type.
  */
  compatibleContent(e) {
    return this == e || this.contentMatch.compatible(e.contentMatch);
  }
  /**
  @internal
  */
  computeAttrs(e) {
    return !e && this.defaultAttrs ? this.defaultAttrs : Cy(this.attrs, e);
  }
  /**
  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(e = null, t, r) {
    if (this.isText)
      throw new Error("NodeType.create can't construct text nodes");
    return new Qn(this, this.computeAttrs(e), A.from(t), ue.setFrom(r));
  }
  /**
  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(e = null, t, r) {
    return t = A.from(t), this.checkContent(t), new Qn(this, this.computeAttrs(e), t, ue.setFrom(r));
  }
  /**
  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(e = null, t, r) {
    if (e = this.computeAttrs(e), t = A.from(t), t.size) {
      let s = this.contentMatch.fillBefore(t);
      if (!s)
        return null;
      t = s.append(t);
    }
    let i = this.contentMatch.matchFragment(t), o = i && i.fillBefore(A.empty, !0);
    return o ? new Qn(this, e, t.append(o), ue.setFrom(r)) : null;
  }
  /**
  Returns true if the given fragment is valid content for this node
  type.
  */
  validContent(e) {
    let t = this.contentMatch.matchFragment(e);
    if (!t || !t.validEnd)
      return !1;
    for (let r = 0; r < e.childCount; r++)
      if (!this.allowsMarks(e.child(r).marks))
        return !1;
    return !0;
  }
  /**
  Throws a RangeError if the given fragment is not valid content for this
  node type.
  @internal
  */
  checkContent(e) {
    if (!this.validContent(e))
      throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0, 50)}`);
  }
  /**
  @internal
  */
  checkAttrs(e) {
    Sy(this.attrs, e, "node", this.name);
  }
  /**
  Check whether the given mark type is allowed in this node.
  */
  allowsMarkType(e) {
    return this.markSet == null || this.markSet.indexOf(e) > -1;
  }
  /**
  Test whether the given set of marks are allowed in this node.
  */
  allowsMarks(e) {
    if (this.markSet == null)
      return !0;
    for (let t = 0; t < e.length; t++)
      if (!this.allowsMarkType(e[t].type))
        return !1;
    return !0;
  }
  /**
  Removes the marks that are not allowed in this node from the given set.
  */
  allowedMarks(e) {
    if (this.markSet == null)
      return e;
    let t;
    for (let r = 0; r < e.length; r++)
      this.allowsMarkType(e[r].type) ? t && t.push(e[r]) : t || (t = e.slice(0, r));
    return t ? t.length ? t : ue.none : e;
  }
  /**
  @internal
  */
  static compile(e, t) {
    let r = /* @__PURE__ */ Object.create(null);
    e.forEach((o, s) => r[o] = new xy(o, t, s));
    let i = t.spec.topNode || "doc";
    if (!r[i])
      throw new RangeError("Schema is missing its top node type ('" + i + "')");
    if (!r.text)
      throw new RangeError("Every schema needs a 'text' type");
    for (let o in r.text.attrs)
      throw new RangeError("The text node type should not have attributes");
    return r;
  }
};
function wx(n, e, t) {
  let r = t.split("|");
  return (i) => {
    let o = i === null ? "null" : typeof i;
    if (r.indexOf(o) < 0)
      throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${o}`);
  };
}
class kx {
  constructor(e, t, r) {
    this.hasDefault = Object.prototype.hasOwnProperty.call(r, "default"), this.default = r.default, this.validate = typeof r.validate == "string" ? wx(e, t, r.validate) : r.validate;
  }
  get isRequired() {
    return !this.hasDefault;
  }
}
class uc {
  /**
  @internal
  */
  constructor(e, t, r, i) {
    this.name = e, this.rank = t, this.schema = r, this.spec = i, this.attrs = Ey(e, i.attrs), this.excluded = null;
    let o = vy(this.attrs);
    this.instance = o ? new ue(this, o) : 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(e = null) {
    return !e && this.instance ? this.instance : new ue(this, Cy(this.attrs, e));
  }
  /**
  @internal
  */
  static compile(e, t) {
    let r = /* @__PURE__ */ Object.create(null), i = 0;
    return e.forEach((o, s) => r[o] = new uc(o, i++, t, s)), r;
  }
  /**
  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(e) {
    for (var t = 0; t < e.length; t++)
      e[t].type == this && (e = e.slice(0, t).concat(e.slice(t + 1)), t--);
    return e;
  }
  /**
  Tests whether there is a mark of this type in the given set.
  */
  isInSet(e) {
    for (let t = 0; t < e.length; t++)
      if (e[t].type == this)
        return e[t];
  }
  /**
  @internal
  */
  checkAttrs(e) {
    Sy(this.attrs, e, "mark", this.name);
  }
  /**
  Queries whether a given mark type is
  [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
  */
  excludes(e) {
    return this.excluded.indexOf(e) > -1;
  }
}
class Dy {
  /**
  Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
  */
  constructor(e) {
    this.linebreakReplacement = null, this.cached = /* @__PURE__ */ Object.create(null);
    let t = this.spec = {};
    for (let i in e)
      t[i] = e[i];
    t.nodes = We.from(e.nodes), t.marks = We.from(e.marks || {}), this.nodes = Lm.compile(this.spec.nodes, this), this.marks = uc.compile(this.spec.marks, this);
    let r = /* @__PURE__ */ Object.create(null);
    for (let i in this.nodes) {
      if (i in this.marks)
        throw new RangeError(i + " can not be both a node and a mark");
      let o = this.nodes[i], s = o.spec.content || "", l = o.spec.marks;
      if (o.contentMatch = r[s] || (r[s] = hi.parse(s, this.nodes)), o.inlineContent = o.contentMatch.inlineContent, o.spec.linebreakReplacement) {
        if (this.linebreakReplacement)
          throw new RangeError("Multiple linebreak nodes defined");
        if (!o.isInline || !o.isLeaf)
          throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
        this.linebreakReplacement = o;
      }
      o.markSet = l == "_" ? null : l ? Rm(this, l.split(" ")) : l == "" || !o.inlineContent ? [] : null;
    }
    for (let i in this.marks) {
      let o = this.marks[i], s = o.spec.excludes;
      o.excluded = s == null ? [o] : s == "" ? [] : Rm(this, s.split(" "));
    }
    this.nodeFromJSON = (i) => Qn.fromJSON(this, i), this.markFromJSON = (i) => ue.fromJSON(this, i), 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(e, t = null, r, i) {
    if (typeof e == "string")
      e = this.nodeType(e);
    else if (e instanceof Lm) {
      if (e.schema != this)
        throw new RangeError("Node type from different schema used (" + e.name + ")");
    } else throw new RangeError("Invalid node type: " + e);
    return e.createChecked(t, r, i);
  }
  /**
  Create a text node in the schema. Empty text nodes are not
  allowed.
  */
  text(e, t) {
    let r = this.nodes.text;
    return new ma(r, r.defaultAttrs, e, ue.setFrom(t));
  }
  /**
  Create a mark with the given type and attributes.
  */
  mark(e, t) {
    return typeof e == "string" && (e = this.marks[e]), e.create(t);
  }
  /**
  @internal
  */
  nodeType(e) {
    let t = this.nodes[e];
    if (!t)
      throw new RangeError("Unknown node type: " + e);
    return t;
  }
}
function Rm(n, e) {
  let t = [];
  for (let r = 0; r < e.length; r++) {
    let i = e[r], o = n.marks[i], s = o;
    if (o)
      t.push(o);
    else
      for (let l in n.marks) {
        let a = n.marks[l];
        (i == "_" || a.spec.group && a.spec.group.split(" ").indexOf(i) > -1) && t.push(s = a);
      }
    if (!s)
      throw new SyntaxError("Unknown mark type: '" + e[r] + "'");
  }
  return t;
}
function vx(n) {
  return n.tag != null;
}
function Cx(n) {
  return n.style != null;
}
let On = class yu {
  /**
  Create a parser that targets the given schema, using the given
  parsing rules.
  */
  constructor(e, t) {
    this.schema = e, this.rules = t, this.tags = [], this.styles = [];
    let r = this.matchedStyles = [];
    t.forEach((i) => {
      if (vx(i))
        this.tags.push(i);
      else if (Cx(i)) {
        let o = /[^=]*/.exec(i.style)[0];
        r.indexOf(o) < 0 && r.push(o), this.styles.push(i);
      }
    }), this.normalizeLists = !this.tags.some((i) => {
      if (!/^(ul|ol)\b/.test(i.tag) || !i.node)
        return !1;
      let o = e.nodes[i.node];
      return o.contentMatch.matchType(o);
    });
  }
  /**
  Parse a document from the content of a DOM node.
  */
  parse(e, t = {}) {
    let r = new Pm(this, t, !1);
    return r.addAll(e, ue.none, t.from, t.to), r.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(e, t = {}) {
    let r = new Pm(this, t, !0);
    return r.addAll(e, ue.none, t.from, t.to), O.maxOpen(r.finish());
  }
  /**
  @internal
  */
  matchTag(e, t, r) {
    for (let i = r ? this.tags.indexOf(r) + 1 : 0; i < this.tags.length; i++) {
      let o = this.tags[i];
      if (xx(e, o.tag) && (o.namespace === void 0 || e.namespaceURI == o.namespace) && (!o.context || t.matchesContext(o.context))) {
        if (o.getAttrs) {
          let s = o.getAttrs(e);
          if (s === !1)
            continue;
          o.attrs = s || void 0;
        }
        return o;
      }
    }
  }
  /**
  @internal
  */
  matchStyle(e, t, r, i) {
    for (let o = i ? this.styles.indexOf(i) + 1 : 0; o < this.styles.length; o++) {
      let s = this.styles[o], l = s.style;
      if (!(l.indexOf(e) != 0 || s.context && !r.matchesContext(s.context) || // Test that the style string either precisely matches the prop,
      // or has an '=' sign after the prop, followed by the given
      // value.
      l.length > e.length && (l.charCodeAt(e.length) != 61 || l.slice(e.length + 1) != t))) {
        if (s.getAttrs) {
          let a = s.getAttrs(t);
          if (a === !1)
            continue;
          s.attrs = a || void 0;
        }
        return s;
      }
    }
  }
  /**
  @internal
  */
  static schemaRules(e) {
    let t = [];
    function r(i) {
      let o = i.priority == null ? 50 : i.priority, s = 0;
      for (; s < t.length; s++) {
        let l = t[s];
        if ((l.priority == null ? 50 : l.priority) < o)
          break;
      }
      t.splice(s, 0, i);
    }
    for (let i in e.marks) {
      let o = e.marks[i].spec.parseDOM;
      o && o.forEach((s) => {
        r(s = zm(s)), s.mark || s.ignore || s.clearMark || (s.mark = i);
      });
    }
    for (let i in e.nodes) {
      let o = e.nodes[i].spec.parseDOM;
      o && o.forEach((s) => {
        r(s = zm(s)), s.node || s.ignore || s.mark || (s.node = i);
      });
    }
    return t;
  }
  /**
  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(e) {
    return e.cached.domParser || (e.cached.domParser = new yu(e, yu.schemaRules(e)));
  }
};
const Ay = {
  address: !0,
  article: !0,
  aside: !0,
  blockquote: !0,
  canvas: !0,
  dd: !0,
  div: !0,
  dl: !0,
  fieldset: !0,
  figcaption: !0,
  figure: !0,
  footer: !0,
  form: !0,
  h1: !0,
  h2: !0,
  h3: !0,
  h4: !0,
  h5: !0,
  h6: !0,
  header: !0,
  hgroup: !0,
  hr: !0,
  li: !0,
  noscript: !0,
  ol: !0,
  output: !0,
  p: !0,
  pre: !0,
  section: !0,
  table: !0,
  tfoot: !0,
  ul: !0
}, Sx = {
  head: !0,
  noscript: !0,
  object: !0,
  script: !0,
  style: !0,
  title: !0
}, Ty = { ol: !0, ul: !0 }, hs = 1, _u = 2, Yo = 4;
function Bm(n, e, t) {
  return e != null ? (e ? hs : 0) | (e === "full" ? _u : 0) : n && n.whitespace == "pre" ? hs | _u : t & ~Yo;
}
class _l {
  constructor(e, t, r, i, o, s) {
    this.type = e, this.attrs = t, this.marks = r, this.solid = i, this.options = s, this.content = [], this.activeMarks = ue.none, this.match = o || (s & Yo ? null : e.contentMatch);
  }
  findWrapping(e) {
    if (!this.match) {
      if (!this.type)
        return [];
      let t = this.type.contentMatch.fillBefore(A.from(e));
      if (t)
        this.match = this.type.contentMatch.matchFragment(t);
      else {
        let r = this.type.contentMatch, i;
        return (i = r.findWrapping(e.type)) ? (this.match = r, i) : null;
      }
    }
    return this.match.findWrapping(e.type);
  }
  finish(e) {
    if (!(this.options & hs)) {
      let r = this.content[this.content.length - 1], i;
      if (r && r.isText && (i = /[ \t\r\n\u000c]+$/.exec(r.text))) {
        let o = r;
        r.text.length == i[0].length ? this.content.pop() : this.content[this.content.length - 1] = o.withText(o.text.slice(0, o.text.length - i[0].length));
      }
    }
    let t = A.from(this.content);
    return !e && this.match && (t = t.append(this.match.fillBefore(A.empty, !0))), this.type ? this.type.create(this.attrs, t, this.marks) : t;
  }
  inlineContext(e) {
    return this.type ? this.type.inlineContent : this.content.length ? this.content[0].isInline : e.parentNode && !Ay.hasOwnProperty(e.parentNode.nodeName.toLowerCase());
  }
}
class Pm {
  constructor(e, t, r) {
    this.parser = e, this.options = t, this.isOpen = r, this.open = 0, this.localPreserveWS = !1;
    let i = t.topNode, o, s = Bm(null, t.preserveWhitespace, 0) | (r ? Yo : 0);
    i ? o = new _l(i.type, i.attrs, ue.none, !0, t.topMatch || i.type.contentMatch, s) : r ? o = new _l(null, null, ue.none, !0, null, s) : o = new _l(e.schema.topNodeType, null, ue.none, !0, null, s), this.nodes = [o], this.find = t.findPositions, this.needsBlock = !1;
  }
  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(e, t) {
    e.nodeType == 3 ? this.addTextNode(e, t) : e.nodeType == 1 && this.addElement(e, t);
  }
  addTextNode(e, t) {
    let r = e.nodeValue, i = this.top, o = i.options & _u ? "full" : this.localPreserveWS || (i.options & hs) > 0;
    if (o === "full" || i.inlineContext(e) || /[^ \t\r\n\u000c]/.test(r)) {
      if (o)
        o !== "full" ? r = r.replace(/\r?\n|\r/g, " ") : r = r.replace(/\r\n?/g, `
`);
      else if (r = r.replace(/[ \t\r\n\u000c]+/g, " "), /^[ \t\r\n\u000c]/.test(r) && this.open == this.nodes.length - 1) {
        let s = i.content[i.content.length - 1], l = e.previousSibling;
        (!s || l && l.nodeName == "BR" || s.isText && /[ \t\r\n\u000c]$/.test(s.text)) && (r = r.slice(1));
      }
      r && this.insertNode(this.parser.schema.text(r), t, !/\S/.test(r)), this.findInText(e);
    } else
      this.findInside(e);
  }
  // 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(e, t, r) {
    let i = this.localPreserveWS, o = this.top;
    (e.tagName == "PRE" || /pre/.test(e.style && e.style.whiteSpace)) && (this.localPreserveWS = !0);
    let s = e.nodeName.toLowerCase(), l;
    Ty.hasOwnProperty(s) && this.parser.normalizeLists && Ex(e);
    let a = this.options.ruleFromNode && this.options.ruleFromNode(e) || (l = this.parser.matchTag(e, this, r));
    e: if (a ? a.ignore : Sx.hasOwnProperty(s))
      this.findInside(e), this.ignoreFallback(e, t);
    else if (!a || a.skip || a.closeParent) {
      a && a.closeParent ? this.open = Math.max(0, this.open - 1) : a && a.skip.nodeType && (e = a.skip);
      let c, d = this.needsBlock;
      if (Ay.hasOwnProperty(s))
        o.content.length && o.content[0].isInline && this.open && (this.open--, o = this.top), c = !0, o.type || (this.needsBlock = !0);
      else if (!e.firstChild) {
        this.leafFallback(e, t);
        break e;
      }
      let u = a && a.skip ? t : this.readStyles(e, t);
      u && this.addAll(e, u), c && this.sync(o), this.needsBlock = d;
    } else {
      let c = this.readStyles(e, t);
      c && this.addElementByRule(e, a, c, a.consuming === !1 ? l : void 0);
    }
    this.localPreserveWS = i;
  }
  // Called for leaf DOM nodes that would otherwise be ignored
  leafFallback(e, t) {
    e.nodeName == "BR" && this.top.type && this.top.type.inlineContent && this.addTextNode(e.ownerDocument.createTextNode(`
`), t);
  }
  // Called for ignored nodes
  ignoreFallback(e, t) {
    e.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent) && this.findPlace(this.parser.schema.text("-"), t, !0);
  }
  // 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(e, t) {
    let r = e.style;
    if (r && r.length)
      for (let i = 0; i < this.parser.matchedStyles.length; i++) {
        let o = this.parser.matchedStyles[i], s = r.getPropertyValue(o);
        if (s)
          for (let l = void 0; ; ) {
            let a = this.parser.matchStyle(o, s, this, l);
            if (!a)
              break;
            if (a.ignore)
              return null;
            if (a.clearMark ? t = t.filter((c) => !a.clearMark(c)) : t = t.concat(this.parser.schema.marks[a.mark].create(a.attrs)), a.consuming === !1)
              l = a;
            else
              break;
          }
      }
    return t;
  }
  // 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(e, t, r, i) {
    let o, s;
    if (t.node)
      if (s = this.parser.schema.nodes[t.node], s.isLeaf)
        this.insertNode(s.create(t.attrs), r, e.nodeName == "BR") || this.leafFallback(e, r);
      else {
        let a = this.enter(s, t.attrs || null, r, t.preserveWhitespace);
        a && (o = !0, r = a);
      }
    else {
      let a = this.parser.schema.marks[t.mark];
      r = r.concat(a.create(t.attrs));
    }
    let l = this.top;
    if (s && s.isLeaf)
      this.findInside(e);
    else if (i)
      this.addElement(e, r, i);
    else if (t.getContent)
      this.findInside(e), t.getContent(e, this.parser.schema).forEach((a) => this.insertNode(a, r, !1));
    else {
      let a = e;
      typeof t.contentElement == "string" ? a = e.querySelector(t.contentElement) : typeof t.contentElement == "function" ? a = t.contentElement(e) : t.contentElement && (a = t.contentElement), this.findAround(e, a, !0), this.addAll(a, r), this.findAround(e, a, !1);
    }
    o && this.sync(l) && 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(e, t, r, i) {
    let o = r || 0;
    for (let s = r ? e.childNodes[r] : e.firstChild, l = i == null ? null : e.childNodes[i]; s != l; s = s.nextSibling, ++o)
      this.findAtPoint(e, o), this.addDOM(s, t);
    this.findAtPoint(e, o);
  }
  // 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(e, t, r) {
    let i, o;
    for (let s = this.open, l = 0; s >= 0; s--) {
      let a = this.nodes[s], c = a.findWrapping(e);
      if (c && (!i || i.length > c.length + l) && (i = c, o = a, !c.length))
        break;
      if (a.solid) {
        if (r)
          break;
        l += 2;
      }
    }
    if (!i)
      return null;
    this.sync(o);
    for (let s = 0; s < i.length; s++)
      t = this.enterInner(i[s], null, t, !1);
    return t;
  }
  // Try to insert the given node, adjusting the context when needed.
  insertNode(e, t, r) {
    if (e.isInline && this.needsBlock && !this.top.type) {
      let o = this.textblockFromContext();
      o && (t = this.enterInner(o, null, t));
    }
    let i = this.findPlace(e, t, r);
    if (i) {
      this.closeExtra();
      let o = this.top;
      o.match && (o.match = o.match.matchType(e.type));
      let s = ue.none;
      for (let l of i.concat(e.marks))
        (o.type ? o.type.allowsMarkType(l.type) : Hm(l.type, e.type)) && (s = l.addToSet(s));
      return o.content.push(e.mark(s)), !0;
    }
    return !1;
  }
  // Try to start a node of the given type, adjusting the context when
  // necessary.
  enter(e, t, r, i) {
    let o = this.findPlace(e.create(t), r, !1);
    return o && (o = this.enterInner(e, t, r, !0, i)), o;
  }
  // Open a node of the given type
  enterInner(e, t, r, i = !1, o) {
    this.closeExtra();
    let s = this.top;
    s.match = s.match && s.match.matchType(e);
    let l = Bm(e, o, s.options);
    s.options & Yo && s.content.length == 0 && (l |= Yo);
    let a = ue.none;
    return r = r.filter((c) => (s.type ? s.type.allowsMarkType(c.type) : Hm(c.type, e)) ? (a = c.addToSet(a), !1) : !0), this.nodes.push(new _l(e, t, a, i, null, l)), this.open++, r;
  }
  // Make sure all nodes above this.open are finished and added to
  // their parents
  closeExtra(e = !1) {
    let t = this.nodes.length - 1;
    if (t > this.open) {
      for (; t > this.open; t--)
        this.nodes[t - 1].content.push(this.nodes[t].finish(e));
      this.nodes.length = this.open + 1;
    }
  }
  finish() {
    return this.open = 0, this.closeExtra(this.isOpen), this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
  }
  sync(e) {
    for (let t = this.open; t >= 0; t--) {
      if (this.nodes[t] == e)
        return this.open = t, !0;
      this.localPreserveWS && (this.nodes[t].options |= hs);
    }
    return !1;
  }
  get currentPos() {
    this.closeExtra();
    let e = 0;
    for (let t = this.open; t >= 0; t--) {
      let r = this.nodes[t].content;
      for (let i = r.length - 1; i >= 0; i--)
        e += r[i].nodeSize;
      t && e++;
    }
    return e;
  }
  findAtPoint(e, t) {
    if (this.find)
      for (let r = 0; r < this.find.length; r++)
        this.find[r].node == e && this.find[r].offset == t && (this.find[r].pos = this.currentPos);
  }
  findInside(e) {
    if (this.find)
      for (let t = 0; t < this.find.length; t++)
        this.find[t].pos == null && e.nodeType == 1 && e.contains(this.find[t].node) && (this.find[t].pos = this.currentPos);
  }
  findAround(e, t, r) {
    if (e != t && this.find)
      for (let i = 0; i < this.find.length; i++)
        this.find[i].pos == null && e.nodeType == 1 && e.contains(this.find[i].node) && t.compareDocumentPosition(this.find[i].node) & (r ? 2 : 4) && (this.find[i].pos = this.currentPos);
  }
  findInText(e) {
    if (this.find)
      for (let t = 0; t < this.find.length; t++)
        this.find[t].node == e && (this.find[t].pos = this.currentPos - (e.nodeValue.length - this.find[t].offset));
  }
  // Determines whether the given context string matches this context.
  matchesContext(e) {
    if (e.indexOf("|") > -1)
      return e.split(/\s*\|\s*/).some(this.matchesContext, this);
    let t = e.split("/"), r = this.options.context, i = !this.isOpen && (!r || r.parent.type == this.nodes[0].type), o = -(r ? r.depth + 1 : 0) + (i ? 0 : 1), s = (l, a) => {
      for (; l >= 0; l--) {
        let c = t[l];
        if (c == "") {
          if (l == t.length - 1 || l == 0)
            continue;
          for (; a >= o; a--)
            if (s(l - 1, a))
              return !0;
          return !1;
        } else {
          let d = a > 0 || a == 0 && i ? this.nodes[a].type : r && a >= o ? r.node(a - o).type : null;
          if (!d || d.name != c && !d.isInGroup(c))
            return !1;
          a--;
        }
      }
      return !0;
    };
    return s(t.length - 1, this.open);
  }
  textblockFromContext() {
    let e = this.options.context;
    if (e)
      for (let t = e.depth; t >= 0; t--) {
        let r = e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;
        if (r && r.isTextblock && r.defaultAttrs)
          return r;
      }
    for (let t in this.parser.schema.nodes) {
      let r = this.parser.schema.nodes[t];
      if (r.isTextblock && r.defaultAttrs)
        return r;
    }
  }
}
function Ex(n) {
  for (let e = n.firstChild, t = null; e; e = e.nextSibling) {
    let r = e.nodeType == 1 ? e.nodeName.toLowerCase() : null;
    r && Ty.hasOwnProperty(r) && t ? (t.appendChild(e), e = t) : r == "li" ? t = e : r && (t = null);
  }
}
function xx(n, e) {
  return (n.matches || n.msMatchesSelector || n.webkitMatchesSelector || n.mozMatchesSelector).call(n, e);
}
function zm(n) {
  let e = {};
  for (let t in n)
    e[t] = n[t];
  return e;
}
function Hm(n, e) {
  let t = e.schema.nodes;
  for (let r in t) {
    let i = t[r];
    if (!i.allowsMarkType(n))
      continue;
    let o = [], s = (l) => {
      o.push(l);
      for (let a = 0; a < l.edgeCount; a++) {
        let { type: c, next: d } = l.edge(a);
        if (c == e || o.indexOf(d) < 0 && s(d))
          return !0;
      }
    };
    if (s(i.contentMatch))
      return !0;
  }
}
class sr {
  /**
  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(e, t) {
    this.nodes = e, this.marks = t;
  }
  /**
  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(e, t = {}, r) {
    r || (r = md(t).createDocumentFragment());
    let i = r, o = [];
    return e.forEach((s) => {
      if (o.length || s.marks.length) {
        let l = 0, a = 0;
        for (; l < o.length && a < s.marks.length; ) {
          let c = s.marks[a];
          if (!this.marks[c.type.name]) {
            a++;
            continue;
          }
          if (!c.eq(o[l][0]) || c.type.spec.spanning === !1)
            break;
          l++, a++;
        }
        for (; l < o.length; )
          i = o.pop()[1];
        for (; a < s.marks.length; ) {
          let c = s.marks[a++], d = this.serializeMark(c, s.isInline, t);
          d && (o.push([c, i]), i.appendChild(d.dom), i = d.contentDOM || d.dom);
        }
      }
      i.appendChild(this.serializeNodeInner(s, t));
    }), r;
  }
  /**
  @internal
  */
  serializeNodeInner(e, t) {
    let { dom: r, contentDOM: i } = Gl(md(t), this.nodes[e.type.name](e), null, e.attrs);
    if (i) {
      if (e.isLeaf)
        throw new RangeError("Content hole not allowed in a leaf node spec");
      this.serializeFragment(e.content, t, i);
    }
    return r;
  }
  /**
  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(e, t = {}) {
    let r = this.serializeNodeInner(e, t);
    for (let i = e.marks.length - 1; i >= 0; i--) {
      let o = this.serializeMark(e.marks[i], e.isInline, t);
      o && ((o.contentDOM || o.dom).appendChild(r), r = o.dom);
    }
    return r;
  }
  /**
  @internal
  */
  serializeMark(e, t, r = {}) {
    let i = this.marks[e.type.name];
    return i && Gl(md(r), i(e, t), null, e.attrs);
  }
  static renderSpec(e, t, r = null, i) {
    return Gl(e, t, r, i);
  }
  /**
  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(e) {
    return e.cached.domSerializer || (e.cached.domSerializer = new sr(this.nodesFromSchema(e), this.marksFromSchema(e)));
  }
  /**
  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(e) {
    let t = Vm(e.nodes);
    return t.text || (t.text = (r) => r.text), t;
  }
  /**
  Gather the serializers in a schema's mark specs into an object.
  */
  static marksFromSchema(e) {
    return Vm(e.marks);
  }
}
function Vm(n) {
  let e = {};
  for (let t in n) {
    let r = n[t].spec.toDOM;
    r && (e[t] = r);
  }
  return e;
}
function md(n) {
  return n.document || window.document;
}
const Um = /* @__PURE__ */ new WeakMap();
function Dx(n) {
  let e = Um.get(n);
  return e === void 0 && Um.set(n, e = Ax(n)), e;
}
function Ax(n) {
  let e = null;
  function t(r) {
    if (r && typeof r == "object")
      if (Array.isArray(r))
        if (typeof r[0] == "string")
          e || (e = []), e.push(r);
        else
          for (let i = 0; i < r.length; i++)
            t(r[i]);
      else
        for (let i in r)
          t(r[i]);
  }
  return t(n), e;
}
function Gl(n, e, t, r) {
  if (typeof e == "string")
    return { dom: n.createTextNode(e) };
  if (e.nodeType != null)
    return { dom: e };
  if (e.dom && e.dom.nodeType != null)
    return e;
  let i = e[0], o;
  if (typeof i != "string")
    throw new RangeError("Invalid array passed to renderSpec");
  if (r && (o = Dx(r)) && o.indexOf(e) > -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 s = i.indexOf(" ");
  s > 0 && (t = i.slice(0, s), i = i.slice(s + 1));
  let l, a = t ? n.createElementNS(t, i) : n.createElement(i), c = e[1], d = 1;
  if (c && typeof c == "object" && c.nodeType == null && !Array.isArray(c)) {
    d = 2;
    for (let u in c)
      if (c[u] != null) {
        let h = u.indexOf(" ");
        h > 0 ? a.setAttributeNS(u.slice(0, h), u.slice(h + 1), c[u]) : u == "style" && a.style ? a.style.cssText = c[u] : a.setAttribute(u, c[u]);
      }
  }
  for (let u = d; u < e.length; u++) {
    let h = e[u];
    if (h === 0) {
      if (u < e.length - 1 || u > d)
        throw new RangeError("Content hole must be the only child of its parent node");
      return { dom: a, contentDOM: a };
    } else {
      let { dom: f, contentDOM: p } = Gl(n, h, t, r);
      if (a.appendChild(f), p) {
        if (l)
          throw new RangeError("Multiple content holes");
        l = p;
      }
    }
  }
  return { dom: a, contentDOM: l };
}
const My = 65535, Oy = Math.pow(2, 16);
function Tx(n, e) {
  return n + e * Oy;
}
function qm(n) {
  return n & My;
}
function Mx(n) {
  return (n - (n & My)) / Oy;
}
const Fy = 1, Ny = 2, Kl = 4, $y = 8;
class wu {
  /**
  @internal
  */
  constructor(e, t, r) {
    this.pos = e, this.delInfo = t, this.recover = r;
  }
  /**
  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 & $y) > 0;
  }
  /**
  Tells you whether the token before the mapped position was deleted.
  */
  get deletedBefore() {
    return (this.delInfo & (Fy | Kl)) > 0;
  }
  /**
  True when the token after the mapped position was deleted.
  */
  get deletedAfter() {
    return (this.delInfo & (Ny | Kl)) > 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 & Kl) > 0;
  }
}
class xt {
  /**
  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(e, t = !1) {
    if (this.ranges = e, this.inverted = t, !e.length && xt.empty)
      return xt.empty;
  }
  /**
  @internal
  */
  recover(e) {
    let t = 0, r = qm(e);
    if (!this.inverted)
      for (let i = 0; i < r; i++)
        t += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];
    return this.ranges[r * 3] + t + Mx(e);
  }
  mapResult(e, t = 1) {
    return this._map(e, t, !1);
  }
  map(e, t = 1) {
    return this._map(e, t, !0);
  }
  /**
  @internal
  */
  _map(e, t, r) {
    let i = 0, o = this.inverted ? 2 : 1, s = this.inverted ? 1 : 2;
    for (let l = 0; l < this.ranges.length; l += 3) {
      let a = this.ranges[l] - (this.inverted ? i : 0);
      if (a > e)
        break;
      let c = this.ranges[l + o], d = this.ranges[l + s], u = a + c;
      if (e <= u) {
        let h = c ? e == a ? -1 : e == u ? 1 : t : t, f = a + i + (h < 0 ? 0 : d);
        if (r)
          return f;
        let p = e == (t < 0 ? a : u) ? null : Tx(l / 3, e - a), m = e == a ? Ny : e == u ? Fy : Kl;
        return (t < 0 ? e != a : e != u) && (m |= $y), new wu(f, m, p);
      }
      i += d - c;
    }
    return r ? e + i : new wu(e + i, 0, null);
  }
  /**
  @internal
  */
  touches(e, t) {
    let r = 0, i = qm(t), o = this.inverted ? 2 : 1, s = this.inverted ? 1 : 2;
    for (let l = 0; l < this.ranges.length; l += 3) {
      let a = this.ranges[l] - (this.inverted ? r : 0);
      if (a > e)
        break;
      let c = this.ranges[l + o], d = a + c;
      if (e <= d && l == i * 3)
        return !0;
      r += this.ranges[l + s] - c;
    }
    return !1;
  }
  /**
  Calls the given function on each of the changed ranges included in
  this map.
  */
  forEach(e) {
    let t = this.inverted ? 2 : 1, r = this.inverted ? 1 : 2;
    for (let i = 0, o = 0; i < this.ranges.length; i += 3) {
      let s = this.ranges[i], l = s - (this.inverted ? o : 0), a = s + (this.inverted ? 0 : o), c = this.ranges[i + t], d = this.ranges[i + r];
      e(l, l + c, a, a + d), o += d - c;
    }
  }
  /**
  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 xt(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(e) {
    return e == 0 ? xt.empty : new xt(e < 0 ? [0, -e, 0] : [0, 0, e]);
  }
}
xt.empty = new xt([]);
class ro {
  /**
  Create a new mapping with the given position maps.
  */
  constructor(e, t, r = 0, i = e ? e.length : 0) {
    this.mirror = t, this.from = r, this.to = i, this._maps = e || [], this.ownData = !(e || t);
  }
  /**
  The step maps in this mapping.
  */
  get maps() {
    return this._maps;
  }
  /**
  Create a mapping that maps only through a part of this one.
  */
  slice(e = 0, t = this.maps.length) {
    return new ro(this._maps, this.mirror, e, t);
  }
  /**
  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(e, t) {
    this.ownData || (this._maps = this._maps.slice(), this.mirror = this.mirror && this.mirror.slice(), this.ownData = !0), this.to = this._maps.push(e), t != null && this.setMirror(this._maps.length - 1, t);
  }
  /**
  Add all the step maps in a given mapping to this one (preserving
  mirroring information).
  */
  appendMapping(e) {
    for (let t = 0, r = this._maps.length; t < e._maps.length; t++) {
      let i = e.getMirror(t);
      this.appendMap(e._maps[t], i != null && i < t ? r + i : 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(e) {
    if (this.mirror) {
      for (let t = 0; t < this.mirror.length; t++)
        if (this.mirror[t] == e)
          return this.mirror[t + (t % 2 ? -1 : 1)];
    }
  }
  /**
  @internal
  */
  setMirror(e, t) {
    this.mirror || (this.mirror = []), this.mirror.push(e, t);
  }
  /**
  Append the inverse of the given mapping to this one.
  */
  appendMappingInverted(e) {
    for (let t = e.maps.length - 1, r = this._maps.length + e._maps.length; t >= 0; t--) {
      let i = e.getMirror(t);
      this.appendMap(e._maps[t].invert(), i != null && i > t ? r - i - 1 : void 0);
    }
  }
  /**
  Create an inverted version of this mapping.
  */
  invert() {
    let e = new ro();
    return e.appendMappingInverted(this), e;
  }
  /**
  Map a position through this mapping.
  */
  map(e, t = 1) {
    if (this.mirror)
      return this._map(e, t, !0);
    for (let r = this.from; r < this.to; r++)
      e = this._maps[r].map(e, t);
    return e;
  }
  /**
  Map a position through this mapping, returning a mapping
  result.
  */
  mapResult(e, t = 1) {
    return this._map(e, t, !1);
  }
  /**
  @internal
  */
  _map(e, t, r) {
    let i = 0;
    for (let o = this.from; o < this.to; o++) {
      let s = this._maps[o], l = s.mapResult(e, t);
      if (l.recover != null) {
        let a = this.getMirror(o);
        if (a != null && a > o && a < this.to) {
          o = a, e = this._maps[a].recover(l.recover);
          continue;
        }
      }
      i |= l.delInfo, e = l.pos;
    }
    return r ? e : new wu(e, i, null);
  }
}
const gd = /* @__PURE__ */ Object.create(null);
class st {
  /**
  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 xt.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(e) {
    return null;
  }
  /**
  Deserialize a step from its JSON representation. Will call
  through to the step class' own implementation of this method.
  */
  static fromJSON(e, t) {
    if (!t || !t.stepType)
      throw new RangeError("Invalid input for Step.fromJSON");
    let r = gd[t.stepType];
    if (!r)
      throw new RangeError(`No step type ${t.stepType} defined`);
    return r.fromJSON(e, t);
  }
  /**
  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(e, t) {
    if (e in gd)
      throw new RangeError("Duplicate use of step JSON ID " + e);
    return gd[e] = t, t.prototype.jsonID = e, t;
  }
}
class Oe {
  /**
  @internal
  */
  constructor(e, t) {
    this.doc = e, this.failed = t;
  }
  /**
  Create a successful step result.
  */
  static ok(e) {
    return new Oe(e, null);
  }
  /**
  Create a failed step result.
  */
  static fail(e) {
    return new Oe(null, e);
  }
  /**
  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(e, t, r, i) {
    try {
      return Oe.ok(e.replace(t, r, i));
    } catch (o) {
      if (o instanceof ha)
        return Oe.fail(o.message);
      throw o;
    }
  }
}
function Th(n, e, t) {
  let r = [];
  for (let i = 0; i < n.childCount; i++) {
    let o = n.child(i);
    o.content.size && (o = o.copy(Th(o.content, e, o))), o.isInline && (o = e(o, t, i)), r.push(o);
  }
  return A.fromArray(r);
}
class Sr extends st {
  /**
  Create a mark step.
  */
  constructor(e, t, r) {
    super(), this.from = e, this.to = t, this.mark = r;
  }
  apply(e) {
    let t = e.slice(this.from, this.to), r = e.resolve(this.from), i = r.node(r.sharedDepth(this.to)), o = new O(Th(t.content, (s, l) => !s.isAtom || !l.type.allowsMarkType(this.mark.type) ? s : s.mark(this.mark.addToSet(s.marks)), i), t.openStart, t.openEnd);
    return Oe.fromReplace(e, this.from, this.to, o);
  }
  invert() {
    return new Mn(this.from, this.to, this.mark);
  }
  map(e) {
    let t = e.mapResult(this.from, 1), r = e.mapResult(this.to, -1);
    return t.deleted && r.deleted || t.pos >= r.pos ? null : new Sr(t.pos, r.pos, this.mark);
  }
  merge(e) {
    return e instanceof Sr && e.mark.eq(this.mark) && this.from <= e.to && this.to >= e.from ? new Sr(Math.min(this.from, e.from), Math.max(this.to, e.to), this.mark) : null;
  }
  toJSON() {
    return {
      stepType: "addMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.from != "number" || typeof t.to != "number")
      throw new RangeError("Invalid input for AddMarkStep.fromJSON");
    return new Sr(t.from, t.to, e.markFromJSON(t.mark));
  }
}
st.jsonID("addMark", Sr);
class Mn extends st {
  /**
  Create a mark-removing step.
  */
  constructor(e, t, r) {
    super(), this.from = e, this.to = t, this.mark = r;
  }
  apply(e) {
    let t = e.slice(this.from, this.to), r = new O(Th(t.content, (i) => i.mark(this.mark.removeFromSet(i.marks)), e), t.openStart, t.openEnd);
    return Oe.fromReplace(e, this.from, this.to, r);
  }
  invert() {
    return new Sr(this.from, this.to, this.mark);
  }
  map(e) {
    let t = e.mapResult(this.from, 1), r = e.mapResult(this.to, -1);
    return t.deleted && r.deleted || t.pos >= r.pos ? null : new Mn(t.pos, r.pos, this.mark);
  }
  merge(e) {
    return e instanceof Mn && e.mark.eq(this.mark) && this.from <= e.to && this.to >= e.from ? new Mn(Math.min(this.from, e.from), Math.max(this.to, e.to), this.mark) : null;
  }
  toJSON() {
    return {
      stepType: "removeMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.from != "number" || typeof t.to != "number")
      throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
    return new Mn(t.from, t.to, e.markFromJSON(t.mark));
  }
}
st.jsonID("removeMark", Mn);
class Er extends st {
  /**
  Create a node mark step.
  */
  constructor(e, t) {
    super(), this.pos = e, this.mark = t;
  }
  apply(e) {
    let t = e.nodeAt(this.pos);
    if (!t)
      return Oe.fail("No node at mark step's position");
    let r = t.type.create(t.attrs, null, this.mark.addToSet(t.marks));
    return Oe.fromReplace(e, this.pos, this.pos + 1, new O(A.from(r), 0, t.isLeaf ? 0 : 1));
  }
  invert(e) {
    let t = e.nodeAt(this.pos);
    if (t) {
      let r = this.mark.addToSet(t.marks);
      if (r.length == t.marks.length) {
        for (let i = 0; i < t.marks.length; i++)
          if (!t.marks[i].isInSet(r))
            return new Er(this.pos, t.marks[i]);
        return new Er(this.pos, this.mark);
      }
    }
    return new fi(this.pos, this.mark);
  }
  map(e) {
    let t = e.mapResult(this.pos, 1);
    return t.deletedAfter ? null : new Er(t.pos, this.mark);
  }
  toJSON() {
    return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.pos != "number")
      throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
    return new Er(t.pos, e.markFromJSON(t.mark));
  }
}
st.jsonID("addNodeMark", Er);
class fi extends st {
  /**
  Create a mark-removing step.
  */
  constructor(e, t) {
    super(), this.pos = e, this.mark = t;
  }
  apply(e) {
    let t = e.nodeAt(this.pos);
    if (!t)
      return Oe.fail("No node at mark step's position");
    let r = t.type.create(t.attrs, null, this.mark.removeFromSet(t.marks));
    return Oe.fromReplace(e, this.pos, this.pos + 1, new O(A.from(r), 0, t.isLeaf ? 0 : 1));
  }
  invert(e) {
    let t = e.nodeAt(this.pos);
    return !t || !this.mark.isInSet(t.marks) ? this : new Er(this.pos, this.mark);
  }
  map(e) {
    let t = e.mapResult(this.pos, 1);
    return t.deletedAfter ? null : new fi(t.pos, this.mark);
  }
  toJSON() {
    return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.pos != "number")
      throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
    return new fi(t.pos, e.markFromJSON(t.mark));
  }
}
st.jsonID("removeNodeMark", fi);
class Me extends st {
  /**
  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(e, t, r, i = !1) {
    super(), this.from = e, this.to = t, this.slice = r, this.structure = i;
  }
  apply(e) {
    return this.structure && ku(e, this.from, this.to) ? Oe.fail("Structure replace would overwrite content") : Oe.fromReplace(e, this.from, this.to, this.slice);
  }
  getMap() {
    return new xt([this.from, this.to - this.from, this.slice.size]);
  }
  invert(e) {
    return new Me(this.from, this.from + this.slice.size, e.slice(this.from, this.to));
  }
  map(e) {
    let t = e.mapResult(this.from, 1), r = e.mapResult(this.to, -1);
    return t.deletedAcross && r.deletedAcross ? null : new Me(t.pos, Math.max(t.pos, r.pos), this.slice, this.structure);
  }
  merge(e) {
    if (!(e instanceof Me) || e.structure || this.structure)
      return null;
    if (this.from + this.slice.size == e.from && !this.slice.openEnd && !e.slice.openStart) {
      let t = this.slice.size + e.slice.size == 0 ? O.empty : new O(this.slice.content.append(e.slice.content), this.slice.openStart, e.slice.openEnd);
      return new Me(this.from, this.to + (e.to - e.from), t, this.structure);
    } else if (e.to == this.from && !this.slice.openStart && !e.slice.openEnd) {
      let t = this.slice.size + e.slice.size == 0 ? O.empty : new O(e.slice.content.append(this.slice.content), e.slice.openStart, this.slice.openEnd);
      return new Me(e.from, this.to, t, this.structure);
    } else
      return null;
  }
  toJSON() {
    let e = { stepType: "replace", from: this.from, to: this.to };
    return this.slice.size && (e.slice = this.slice.toJSON()), this.structure && (e.structure = !0), e;
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.from != "number" || typeof t.to != "number")
      throw new RangeError("Invalid input for ReplaceStep.fromJSON");
    return new Me(t.from, t.to, O.fromJSON(e, t.slice), !!t.structure);
  }
}
st.jsonID("replace", Me);
class Ae extends st {
  /**
  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(e, t, r, i, o, s, l = !1) {
    super(), this.from = e, this.to = t, this.gapFrom = r, this.gapTo = i, this.slice = o, this.insert = s, this.structure = l;
  }
  apply(e) {
    if (this.structure && (ku(e, this.from, this.gapFrom) || ku(e, this.gapTo, this.to)))
      return Oe.fail("Structure gap-replace would overwrite content");
    let t = e.slice(this.gapFrom, this.gapTo);
    if (t.openStart || t.openEnd)
      return Oe.fail("Gap is not a flat range");
    let r = this.slice.insertAt(this.insert, t.content);
    return r ? Oe.fromReplace(e, this.from, this.to, r) : Oe.fail("Content does not fit in gap");
  }
  getMap() {
    return new xt([
      this.from,
      this.gapFrom - this.from,
      this.insert,
      this.gapTo,
      this.to - this.gapTo,
      this.slice.size - this.insert
    ]);
  }
  invert(e) {
    let t = this.gapTo - this.gapFrom;
    return new Ae(this.from, this.from + this.slice.size + t, this.from + this.insert, this.from + this.insert + t, e.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  }
  map(e) {
    let t = e.mapResult(this.from, 1), r = e.mapResult(this.to, -1), i = this.from == this.gapFrom ? t.pos : e.map(this.gapFrom, -1), o = this.to == this.gapTo ? r.pos : e.map(this.gapTo, 1);
    return t.deletedAcross && r.deletedAcross || i < t.pos || o > r.pos ? null : new Ae(t.pos, r.pos, i, o, this.slice, this.insert, this.structure);
  }
  toJSON() {
    let e = {
      stepType: "replaceAround",
      from: this.from,
      to: this.to,
      gapFrom: this.gapFrom,
      gapTo: this.gapTo,
      insert: this.insert
    };
    return this.slice.size && (e.slice = this.slice.toJSON()), this.structure && (e.structure = !0), e;
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.from != "number" || typeof t.to != "number" || typeof t.gapFrom != "number" || typeof t.gapTo != "number" || typeof t.insert != "number")
      throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
    return new Ae(t.from, t.to, t.gapFrom, t.gapTo, O.fromJSON(e, t.slice), t.insert, !!t.structure);
  }
}
st.jsonID("replaceAround", Ae);
function ku(n, e, t) {
  let r = n.resolve(e), i = t - e, o = r.depth;
  for (; i > 0 && o > 0 && r.indexAfter(o) == r.node(o).childCount; )
    o--, i--;
  if (i > 0) {
    let s = r.node(o).maybeChild(r.indexAfter(o));
    for (; i > 0; ) {
      if (!s || s.isLeaf)
        return !0;
      s = s.firstChild, i--;
    }
  }
  return !1;
}
function Ox(n, e, t, r) {
  let i = [], o = [], s, l;
  n.doc.nodesBetween(e, t, (a, c, d) => {
    if (!a.isInline)
      return;
    let u = a.marks;
    if (!r.isInSet(u) && d.type.allowsMarkType(r.type)) {
      let h = Math.max(c, e), f = Math.min(c + a.nodeSize, t), p = r.addToSet(u);
      for (let m = 0; m < u.length; m++)
        u[m].isInSet(p) || (s && s.to == h && s.mark.eq(u[m]) ? s.to = f : i.push(s = new Mn(h, f, u[m])));
      l && l.to == h ? l.to = f : o.push(l = new Sr(h, f, r));
    }
  }), i.forEach((a) => n.step(a)), o.forEach((a) => n.step(a));
}
function Fx(n, e, t, r) {
  let i = [], o = 0;
  n.doc.nodesBetween(e, t, (s, l) => {
    if (!s.isInline)
      return;
    o++;
    let a = null;
    if (r instanceof uc) {
      let c = s.marks, d;
      for (; d = r.isInSet(c); )
        (a || (a = [])).push(d), c = d.removeFromSet(c);
    } else r ? r.isInSet(s.marks) && (a = [r]) : a = s.marks;
    if (a && a.length) {
      let c = Math.min(l + s.nodeSize, t);
      for (let d = 0; d < a.length; d++) {
        let u = a[d], h;
        for (let f = 0; f < i.length; f++) {
          let p = i[f];
          p.step == o - 1 && u.eq(i[f].style) && (h = p);
        }
        h ? (h.to = c, h.step = o) : i.push({ style: u, from: Math.max(l, e), to: c, step: o });
      }
    }
  }), i.forEach((s) => n.step(new Mn(s.from, s.to, s.style)));
}
function Mh(n, e, t, r = t.contentMatch, i = !0) {
  let o = n.doc.nodeAt(e), s = [], l = e + 1;
  for (let a = 0; a < o.childCount; a++) {
    let c = o.child(a), d = l + c.nodeSize, u = r.matchType(c.type);
    if (!u)
      s.push(new Me(l, d, O.empty));
    else {
      r = u;
      for (let h = 0; h < c.marks.length; h++)
        t.allowsMarkType(c.marks[h].type) || n.step(new Mn(l, d, c.marks[h]));
      if (i && c.isText && t.whitespace != "pre") {
        let h, f = /\r?\n|\r/g, p;
        for (; h = f.exec(c.text); )
          p || (p = new O(A.from(t.schema.text(" ", t.allowedMarks(c.marks))), 0, 0)), s.push(new Me(l + h.index, l + h.index + h[0].length, p));
      }
    }
    l = d;
  }
  if (!r.validEnd) {
    let a = r.fillBefore(A.empty, !0);
    n.replace(l, l, new O(a, 0, 0));
  }
  for (let a = s.length - 1; a >= 0; a--)
    n.step(s[a]);
}
function Nx(n, e, t) {
  return (e == 0 || n.canReplace(e, n.childCount)) && (t == n.childCount || n.canReplace(0, t));
}
function go(n) {
  let t = n.parent.content.cutByIndex(n.startIndex, n.endIndex);
  for (let r = n.depth; ; --r) {
    let i = n.$from.node(r), o = n.$from.index(r), s = n.$to.indexAfter(r);
    if (r < n.depth && i.canReplace(o, s, t))
      return r;
    if (r == 0 || i.type.spec.isolating || !Nx(i, o, s))
      break;
  }
  return null;
}
function $x(n, e, t) {
  let { $from: r, $to: i, depth: o } = e, s = r.before(o + 1), l = i.after(o + 1), a = s, c = l, d = A.empty, u = 0;
  for (let p = o, m = !1; p > t; p--)
    m || r.index(p) > 0 ? (m = !0, d = A.from(r.node(p).copy(d)), u++) : a--;
  let h = A.empty, f = 0;
  for (let p = o, m = !1; p > t; p--)
    m || i.after(p + 1) < i.end(p) ? (m = !0, h = A.from(i.node(p).copy(h)), f++) : c++;
  n.step(new Ae(a, c, s, l, new O(d.append(h), u, f), d.size - u, !0));
}
function Iy(n, e, t = null, r = n) {
  let i = Ix(n, e), o = i && Lx(r, e);
  return o ? i.map(jm).concat({ type: e, attrs: t }).concat(o.map(jm)) : null;
}
function jm(n) {
  return { type: n, attrs: null };
}
function Ix(n, e) {
  let { parent: t, startIndex: r, endIndex: i } = n, o = t.contentMatchAt(r).findWrapping(e);
  if (!o)
    return null;
  let s = o.length ? o[0] : e;
  return t.canReplaceWith(r, i, s) ? o : null;
}
function Lx(n, e) {
  let { parent: t, startIndex: r, endIndex: i } = n, o = t.child(r), s = e.contentMatch.findWrapping(o.type);
  if (!s)
    return null;
  let a = (s.length ? s[s.length - 1] : e).contentMatch;
  for (let c = r; a && c < i; c++)
    a = a.matchType(t.child(c).type);
  return !a || !a.validEnd ? null : s;
}
function Rx(n, e, t) {
  let r = A.empty;
  for (let s = t.length - 1; s >= 0; s--) {
    if (r.size) {
      let l = t[s].type.contentMatch.matchFragment(r);
      if (!l || !l.validEnd)
        throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
    }
    r = A.from(t[s].type.create(t[s].attrs, r));
  }
  let i = e.start, o = e.end;
  n.step(new Ae(i, o, i, o, new O(r, 0, 0), t.length, !0));
}
function Bx(n, e, t, r, i) {
  if (!r.isTextblock)
    throw new RangeError("Type given to setBlockType should be a textblock");
  let o = n.steps.length;
  n.doc.nodesBetween(e, t, (s, l) => {
    let a = typeof i == "function" ? i(s) : i;
    if (s.isTextblock && !s.hasMarkup(r, a) && Px(n.doc, n.mapping.slice(o).map(l), r)) {
      let c = null;
      if (r.schema.linebreakReplacement) {
        let f = r.whitespace == "pre", p = !!r.contentMatch.matchType(r.schema.linebreakReplacement);
        f && !p ? c = !1 : !f && p && (c = !0);
      }
      c === !1 && Ry(n, s, l, o), Mh(n, n.mapping.slice(o).map(l, 1), r, void 0, c === null);
      let d = n.mapping.slice(o), u = d.map(l, 1), h = d.map(l + s.nodeSize, 1);
      return n.step(new Ae(u, h, u + 1, h - 1, new O(A.from(r.create(a, null, s.marks)), 0, 0), 1, !0)), c === !0 && Ly(n, s, l, o), !1;
    }
  });
}
function Ly(n, e, t, r) {
  e.forEach((i, o) => {
    if (i.isText) {
      let s, l = /\r?\n|\r/g;
      for (; s = l.exec(i.text); ) {
        let a = n.mapping.slice(r).map(t + 1 + o + s.index);
        n.replaceWith(a, a + 1, e.type.schema.linebreakReplacement.create());
      }
    }
  });
}
function Ry(n, e, t, r) {
  e.forEach((i, o) => {
    if (i.type == i.type.schema.linebreakReplacement) {
      let s = n.mapping.slice(r).map(t + 1 + o);
      n.replaceWith(s, s + 1, e.type.schema.text(`
`));
    }
  });
}
function Px(n, e, t) {
  let r = n.resolve(e), i = r.index();
  return r.parent.canReplaceWith(i, i + 1, t);
}
function zx(n, e, t, r, i) {
  let o = n.doc.nodeAt(e);
  if (!o)
    throw new RangeError("No node at given position");
  t || (t = o.type);
  let s = t.create(r, null, i || o.marks);
  if (o.isLeaf)
    return n.replaceWith(e, e + o.nodeSize, s);
  if (!t.validContent(o.content))
    throw new RangeError("Invalid content for node type " + t.name);
  n.step(new Ae(e, e + o.nodeSize, e + 1, e + o.nodeSize - 1, new O(A.from(s), 0, 0), 1, !0));
}
function er(n, e, t = 1, r) {
  let i = n.resolve(e), o = i.depth - t, s = r && r[r.length - 1] || i.parent;
  if (o < 0 || i.parent.type.spec.isolating || !i.parent.canReplace(i.index(), i.parent.childCount) || !s.type.validContent(i.parent.content.cutByIndex(i.index(), i.parent.childCount)))
    return !1;
  for (let c = i.depth - 1, d = t - 2; c > o; c--, d--) {
    let u = i.node(c), h = i.index(c);
    if (u.type.spec.isolating)
      return !1;
    let f = u.content.cutByIndex(h, u.childCount), p = r && r[d + 1];
    p && (f = f.replaceChild(0, p.type.create(p.attrs)));
    let m = r && r[d] || u;
    if (!u.canReplace(h + 1, u.childCount) || !m.type.validContent(f))
      return !1;
  }
  let l = i.indexAfter(o), a = r && r[0];
  return i.node(o).canReplaceWith(l, l, a ? a.type : i.node(o + 1).type);
}
function Hx(n, e, t = 1, r) {
  let i = n.doc.resolve(e), o = A.empty, s = A.empty;
  for (let l = i.depth, a = i.depth - t, c = t - 1; l > a; l--, c--) {
    o = A.from(i.node(l).copy(o));
    let d = r && r[c];
    s = A.from(d ? d.type.create(d.attrs, s) : i.node(l).copy(s));
  }
  n.step(new Me(e, e, new O(o.append(s), t, t), !0));
}
function Ei(n, e) {
  let t = n.resolve(e), r = t.index();
  return By(t.nodeBefore, t.nodeAfter) && t.parent.canReplace(r, r + 1);
}
function Vx(n, e) {
  e.content.size || n.type.compatibleContent(e.type);
  let t = n.contentMatchAt(n.childCount), { linebreakReplacement: r } = n.type.schema;
  for (let i = 0; i < e.childCount; i++) {
    let o = e.child(i), s = o.type == r ? n.type.schema.nodes.text : o.type;
    if (t = t.matchType(s), !t || !n.type.allowsMarks(o.marks))
      return !1;
  }
  return t.validEnd;
}
function By(n, e) {
  return !!(n && e && !n.isLeaf && Vx(n, e));
}
function hc(n, e, t = -1) {
  let r = n.resolve(e);
  for (let i = r.depth; ; i--) {
    let o, s, l = r.index(i);
    if (i == r.depth ? (o = r.nodeBefore, s = r.nodeAfter) : t > 0 ? (o = r.node(i + 1), l++, s = r.node(i).maybeChild(l)) : (o = r.node(i).maybeChild(l - 1), s = r.node(i + 1)), o && !o.isTextblock && By(o, s) && r.node(i).canReplace(l, l + 1))
      return e;
    if (i == 0)
      break;
    e = t < 0 ? r.before(i) : r.after(i);
  }
}
function Ux(n, e, t) {
  let r = null, { linebreakReplacement: i } = n.doc.type.schema, o = n.doc.resolve(e - t), s = o.node().type;
  if (i && s.inlineContent) {
    let d = s.whitespace == "pre", u = !!s.contentMatch.matchType(i);
    d && !u ? r = !1 : !d && u && (r = !0);
  }
  let l = n.steps.length;
  if (r === !1) {
    let d = n.doc.resolve(e + t);
    Ry(n, d.node(), d.before(), l);
  }
  s.inlineContent && Mh(n, e + t - 1, s, o.node().contentMatchAt(o.index()), r == null);
  let a = n.mapping.slice(l), c = a.map(e - t);
  if (n.step(new Me(c, a.map(e + t, -1), O.empty, !0)), r === !0) {
    let d = n.doc.resolve(c);
    Ly(n, d.node(), d.before(), n.steps.length);
  }
  return n;
}
function qx(n, e, t) {
  let r = n.resolve(e);
  if (r.parent.canReplaceWith(r.index(), r.index(), t))
    return e;
  if (r.parentOffset == 0)
    for (let i = r.depth - 1; i >= 0; i--) {
      let o = r.index(i);
      if (r.node(i).canReplaceWith(o, o, t))
        return r.before(i + 1);
      if (o > 0)
        return null;
    }
  if (r.parentOffset == r.parent.content.size)
    for (let i = r.depth - 1; i >= 0; i--) {
      let o = r.indexAfter(i);
      if (r.node(i).canReplaceWith(o, o, t))
        return r.after(i + 1);
      if (o < r.node(i).childCount)
        return null;
    }
  return null;
}
function Py(n, e, t) {
  let r = n.resolve(e);
  if (!t.content.size)
    return e;
  let i = t.content;
  for (let o = 0; o < t.openStart; o++)
    i = i.firstChild.content;
  for (let o = 1; o <= (t.openStart == 0 && t.size ? 2 : 1); o++)
    for (let s = r.depth; s >= 0; s--) {
      let l = s == r.depth ? 0 : r.pos <= (r.start(s + 1) + r.end(s + 1)) / 2 ? -1 : 1, a = r.index(s) + (l > 0 ? 1 : 0), c = r.node(s), d = !1;
      if (o == 1)
        d = c.canReplace(a, a, i);
      else {
        let u = c.contentMatchAt(a).findWrapping(i.firstChild.type);
        d = u && c.canReplaceWith(a, a, u[0]);
      }
      if (d)
        return l == 0 ? r.pos : l < 0 ? r.before(s + 1) : r.after(s + 1);
    }
  return null;
}
function fc(n, e, t = e, r = O.empty) {
  if (e == t && !r.size)
    return null;
  let i = n.resolve(e), o = n.resolve(t);
  return zy(i, o, r) ? new Me(e, t, r) : new jx(i, o, r).fit();
}
function zy(n, e, t) {
  return !t.openStart && !t.openEnd && n.start() == e.start() && n.parent.canReplace(n.index(), e.index(), t.content);
}
class jx {
  constructor(e, t, r) {
    this.$from = e, this.$to = t, this.unplaced = r, this.frontier = [], this.placed = A.empty;
    for (let i = 0; i <= e.depth; i++) {
      let o = e.node(i);
      this.frontier.push({
        type: o.type,
        match: o.contentMatchAt(e.indexAfter(i))
      });
    }
    for (let i = e.depth; i > 0; i--)
      this.placed = A.from(e.node(i).copy(this.placed));
  }
  get depth() {
    return this.frontier.length - 1;
  }
  fit() {
    for (; this.unplaced.size; ) {
      let c = this.findFittable();
      c ? this.placeNodes(c) : this.openMore() || this.dropNode();
    }
    let e = this.mustMoveInline(), t = this.placed.size - this.depth - this.$from.depth, r = this.$from, i = this.close(e < 0 ? this.$to : r.doc.resolve(e));
    if (!i)
      return null;
    let o = this.placed, s = r.depth, l = i.depth;
    for (; s && l && o.childCount == 1; )
      o = o.firstChild.content, s--, l--;
    let a = new O(o, s, l);
    return e > -1 ? new Ae(r.pos, e, this.$to.pos, this.$to.end(), a, t) : a.size || r.pos != this.$to.pos ? new Me(r.pos, i.pos, a) : 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 e = this.unplaced.openStart;
    for (let t = this.unplaced.content, r = 0, i = this.unplaced.openEnd; r < e; r++) {
      let o = t.firstChild;
      if (t.childCount > 1 && (i = 0), o.type.spec.isolating && i <= r) {
        e = r;
        break;
      }
      t = o.content;
    }
    for (let t = 1; t <= 2; t++)
      for (let r = t == 1 ? e : this.unplaced.openStart; r >= 0; r--) {
        let i, o = null;
        r ? (o = bd(this.unplaced.content, r - 1).firstChild, i = o.content) : i = this.unplaced.content;
        let s = i.firstChild;
        for (let l = this.depth; l >= 0; l--) {
          let { type: a, match: c } = this.frontier[l], d, u = null;
          if (t == 1 && (s ? c.matchType(s.type) || (u = c.fillBefore(A.from(s), !1)) : o && a.compatibleContent(o.type)))
            return { sliceDepth: r, frontierDepth: l, parent: o, inject: u };
          if (t == 2 && s && (d = c.findWrapping(s.type)))
            return { sliceDepth: r, frontierDepth: l, parent: o, wrap: d };
          if (o && c.matchType(o.type))
            break;
        }
      }
  }
  openMore() {
    let { content: e, openStart: t, openEnd: r } = this.unplaced, i = bd(e, t);
    return !i.childCount || i.firstChild.isLeaf ? !1 : (this.unplaced = new O(e, t + 1, Math.max(r, i.size + t >= e.size - r ? t + 1 : 0)), !0);
  }
  dropNode() {
    let { content: e, openStart: t, openEnd: r } = this.unplaced, i = bd(e, t);
    if (i.childCount <= 1 && t > 0) {
      let o = e.size - t <= t + i.size;
      this.unplaced = new O(Bo(e, t - 1, 1), t - 1, o ? t - 1 : r);
    } else
      this.unplaced = new O(Bo(e, t, 1), t, r);
  }
  // Move content from the unplaced slice at `sliceDepth` to the
  // frontier node at `frontierDepth`. Close that frontier node when
  // applicable.
  placeNodes({ sliceDepth: e, frontierDepth: t, parent: r, inject: i, wrap: o }) {
    for (; this.depth > t; )
      this.closeFrontierNode();
    if (o)
      for (let m = 0; m < o.length; m++)
        this.openFrontierNode(o[m]);
    let s = this.unplaced, l = r ? r.content : s.content, a = s.openStart - e, c = 0, d = [], { match: u, type: h } = this.frontier[t];
    if (i) {
      for (let m = 0; m < i.childCount; m++)
        d.push(i.child(m));
      u = u.matchFragment(i);
    }
    let f = l.size + e - (s.content.size - s.openEnd);
    for (; c < l.childCount; ) {
      let m = l.child(c), g = u.matchType(m.type);
      if (!g)
        break;
      c++, (c > 1 || a == 0 || m.content.size) && (u = g, d.push(Hy(m.mark(h.allowedMarks(m.marks)), c == 1 ? a : 0, c == l.childCount ? f : -1)));
    }
    let p = c == l.childCount;
    p || (f = -1), this.placed = Po(this.placed, t, A.from(d)), this.frontier[t].match = u, p && f < 0 && r && r.type == this.frontier[this.depth].type && this.frontier.length > 1 && this.closeFrontierNode();
    for (let m = 0, g = l; m < f; m++) {
      let y = g.lastChild;
      this.frontier.push({ type: y.type, match: y.contentMatchAt(y.childCount) }), g = y.content;
    }
    this.unplaced = p ? e == 0 ? O.empty : new O(Bo(s.content, e - 1, 1), e - 1, f < 0 ? s.openEnd : e - 1) : new O(Bo(s.content, e, c), s.openStart, s.openEnd);
  }
  mustMoveInline() {
    if (!this.$to.parent.isTextblock)
      return -1;
    let e = this.frontier[this.depth], t;
    if (!e.type.isTextblock || !yd(this.$to, this.$to.depth, e.type, e.match, !1) || this.$to.depth == this.depth && (t = this.findCloseLevel(this.$to)) && t.depth == this.depth)
      return -1;
    let { depth: r } = this.$to, i = this.$to.after(r);
    for (; r > 1 && i == this.$to.end(--r); )
      ++i;
    return i;
  }
  findCloseLevel(e) {
    e: for (let t = Math.min(this.depth, e.depth); t >= 0; t--) {
      let { match: r, type: i } = this.frontier[t], o = t < e.depth && e.end(t + 1) == e.pos + (e.depth - (t + 1)), s = yd(e, t, i, r, o);
      if (s) {
        for (let l = t - 1; l >= 0; l--) {
          let { match: a, type: c } = this.frontier[l], d = yd(e, l, c, a, !0);
          if (!d || d.childCount)
            continue e;
        }
        return { depth: t, fit: s, move: o ? e.doc.resolve(e.after(t + 1)) : e };
      }
    }
  }
  close(e) {
    let t = this.findCloseLevel(e);
    if (!t)
      return null;
    for (; this.depth > t.depth; )
      this.closeFrontierNode();
    t.fit.childCount && (this.placed = Po(this.placed, t.depth, t.fit)), e = t.move;
    for (let r = t.depth + 1; r <= e.depth; r++) {
      let i = e.node(r), o = i.type.contentMatch.fillBefore(i.content, !0, e.index(r));
      this.openFrontierNode(i.type, i.attrs, o);
    }
    return e;
  }
  openFrontierNode(e, t = null, r) {
    let i = this.frontier[this.depth];
    i.match = i.match.matchType(e), this.placed = Po(this.placed, this.depth, A.from(e.create(t, r))), this.frontier.push({ type: e, match: e.contentMatch });
  }
  closeFrontierNode() {
    let t = this.frontier.pop().match.fillBefore(A.empty, !0);
    t.childCount && (this.placed = Po(this.placed, this.frontier.length, t));
  }
}
function Bo(n, e, t) {
  return e == 0 ? n.cutByIndex(t, n.childCount) : n.replaceChild(0, n.firstChild.copy(Bo(n.firstChild.content, e - 1, t)));
}
function Po(n, e, t) {
  return e == 0 ? n.append(t) : n.replaceChild(n.childCount - 1, n.lastChild.copy(Po(n.lastChild.content, e - 1, t)));
}
function bd(n, e) {
  for (let t = 0; t < e; t++)
    n = n.firstChild.content;
  return n;
}
function Hy(n, e, t) {
  if (e <= 0)
    return n;
  let r = n.content;
  return e > 1 && (r = r.replaceChild(0, Hy(r.firstChild, e - 1, r.childCount == 1 ? t - 1 : 0))), e > 0 && (r = n.type.contentMatch.fillBefore(r).append(r), t <= 0 && (r = r.append(n.type.contentMatch.matchFragment(r).fillBefore(A.empty, !0)))), n.copy(r);
}
function yd(n, e, t, r, i) {
  let o = n.node(e), s = i ? n.indexAfter(e) : n.index(e);
  if (s == o.childCount && !t.compatibleContent(o.type))
    return null;
  let l = r.fillBefore(o.content, !0, s);
  return l && !Wx(t, o.content, s) ? l : null;
}
function Wx(n, e, t) {
  for (let r = t; r < e.childCount; r++)
    if (!n.allowsMarks(e.child(r).marks))
      return !0;
  return !1;
}
function Gx(n) {
  return n.spec.defining || n.spec.definingForContent;
}
function Kx(n, e, t, r) {
  if (!r.size)
    return n.deleteRange(e, t);
  let i = n.doc.resolve(e), o = n.doc.resolve(t);
  if (zy(i, o, r))
    return n.step(new Me(e, t, r));
  let s = Uy(i, n.doc.resolve(t));
  s[s.length - 1] == 0 && s.pop();
  let l = -(i.depth + 1);
  s.unshift(l);
  for (let h = i.depth, f = i.pos - 1; h > 0; h--, f--) {
    let p = i.node(h).type.spec;
    if (p.defining || p.definingAsContext || p.isolating)
      break;
    s.indexOf(h) > -1 ? l = h : i.before(h) == f && s.splice(1, 0, -h);
  }
  let a = s.indexOf(l), c = [], d = r.openStart;
  for (let h = r.content, f = 0; ; f++) {
    let p = h.firstChild;
    if (c.push(p), f == r.openStart)
      break;
    h = p.content;
  }
  for (let h = d - 1; h >= 0; h--) {
    let f = c[h], p = Gx(f.type);
    if (p && !f.sameMarkup(i.node(Math.abs(l) - 1)))
      d = h;
    else if (p || !f.type.isTextblock)
      break;
  }
  for (let h = r.openStart; h >= 0; h--) {
    let f = (h + d + 1) % (r.openStart + 1), p = c[f];
    if (p)
      for (let m = 0; m < s.length; m++) {
        let g = s[(m + a) % s.length], y = !0;
        g < 0 && (y = !1, g = -g);
        let _ = i.node(g - 1), b = i.index(g - 1);
        if (_.canReplaceWith(b, b, p.type, p.marks))
          return n.replace(i.before(g), y ? o.after(g) : t, new O(Vy(r.content, 0, r.openStart, f), f, r.openEnd));
      }
  }
  let u = n.steps.length;
  for (let h = s.length - 1; h >= 0 && (n.replace(e, t, r), !(n.steps.length > u)); h--) {
    let f = s[h];
    f < 0 || (e = i.before(f), t = o.after(f));
  }
}
function Vy(n, e, t, r, i) {
  if (e < t) {
    let o = n.firstChild;
    n = n.replaceChild(0, o.copy(Vy(o.content, e + 1, t, r, o)));
  }
  if (e > r) {
    let o = i.contentMatchAt(0), s = o.fillBefore(n).append(n);
    n = s.append(o.matchFragment(s).fillBefore(A.empty, !0));
  }
  return n;
}
function Jx(n, e, t, r) {
  if (!r.isInline && e == t && n.doc.resolve(e).parent.content.size) {
    let i = qx(n.doc, e, r.type);
    i != null && (e = t = i);
  }
  n.replaceRange(e, t, new O(A.from(r), 0, 0));
}
function Yx(n, e, t) {
  let r = n.doc.resolve(e), i = n.doc.resolve(t), o = Uy(r, i);
  for (let s = 0; s < o.length; s++) {
    let l = o[s], a = s == o.length - 1;
    if (a && l == 0 || r.node(l).type.contentMatch.validEnd)
      return n.delete(r.start(l), i.end(l));
    if (l > 0 && (a || r.node(l - 1).canReplace(r.index(l - 1), i.indexAfter(l - 1))))
      return n.delete(r.before(l), i.after(l));
  }
  for (let s = 1; s <= r.depth && s <= i.depth; s++)
    if (e - r.start(s) == r.depth - s && t > r.end(s) && i.end(s) - t != i.depth - s && r.start(s - 1) == i.start(s - 1) && r.node(s - 1).canReplace(r.index(s - 1), i.index(s - 1)))
      return n.delete(r.before(s), t);
  n.delete(e, t);
}
function Uy(n, e) {
  let t = [], r = Math.min(n.depth, e.depth);
  for (let i = r; i >= 0; i--) {
    let o = n.start(i);
    if (o < n.pos - (n.depth - i) || e.end(i) > e.pos + (e.depth - i) || n.node(i).type.spec.isolating || e.node(i).type.spec.isolating)
      break;
    (o == e.start(i) || i == n.depth && i == e.depth && n.parent.inlineContent && e.parent.inlineContent && i && e.start(i - 1) == o - 1) && t.push(i);
  }
  return t;
}
class Ji extends st {
  /**
  Construct an attribute step.
  */
  constructor(e, t, r) {
    super(), this.pos = e, this.attr = t, this.value = r;
  }
  apply(e) {
    let t = e.nodeAt(this.pos);
    if (!t)
      return Oe.fail("No node at attribute step's position");
    let r = /* @__PURE__ */ Object.create(null);
    for (let o in t.attrs)
      r[o] = t.attrs[o];
    r[this.attr] = this.value;
    let i = t.type.create(r, null, t.marks);
    return Oe.fromReplace(e, this.pos, this.pos + 1, new O(A.from(i), 0, t.isLeaf ? 0 : 1));
  }
  getMap() {
    return xt.empty;
  }
  invert(e) {
    return new Ji(this.pos, this.attr, e.nodeAt(this.pos).attrs[this.attr]);
  }
  map(e) {
    let t = e.mapResult(this.pos, 1);
    return t.deletedAfter ? null : new Ji(t.pos, this.attr, this.value);
  }
  toJSON() {
    return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
  }
  static fromJSON(e, t) {
    if (typeof t.pos != "number" || typeof t.attr != "string")
      throw new RangeError("Invalid input for AttrStep.fromJSON");
    return new Ji(t.pos, t.attr, t.value);
  }
}
st.jsonID("attr", Ji);
class fs extends st {
  /**
  Construct an attribute step.
  */
  constructor(e, t) {
    super(), this.attr = e, this.value = t;
  }
  apply(e) {
    let t = /* @__PURE__ */ Object.create(null);
    for (let i in e.attrs)
      t[i] = e.attrs[i];
    t[this.attr] = this.value;
    let r = e.type.create(t, e.content, e.marks);
    return Oe.ok(r);
  }
  getMap() {
    return xt.empty;
  }
  invert(e) {
    return new fs(this.attr, e.attrs[this.attr]);
  }
  map(e) {
    return this;
  }
  toJSON() {
    return { stepType: "docAttr", attr: this.attr, value: this.value };
  }
  static fromJSON(e, t) {
    if (typeof t.attr != "string")
      throw new RangeError("Invalid input for DocAttrStep.fromJSON");
    return new fs(t.attr, t.value);
  }
}
st.jsonID("docAttr", fs);
let io = class extends Error {
};
io = function n(e) {
  let t = Error.call(this, e);
  return t.__proto__ = n.prototype, t;
};
io.prototype = Object.create(Error.prototype);
io.prototype.constructor = io;
io.prototype.name = "TransformError";
class Oh {
  /**
  Create a transform that starts with the given document.
  */
  constructor(e) {
    this.doc = e, this.steps = [], this.docs = [], this.mapping = new ro();
  }
  /**
  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(e) {
    let t = this.maybeStep(e);
    if (t.failed)
      throw new io(t.failed);
    return this;
  }
  /**
  Try to apply a step in this transformation, ignoring it if it
  fails. Returns the step result.
  */
  maybeStep(e) {
    let t = e.apply(this.doc);
    return t.failed || this.addStep(e, t.doc), t;
  }
  /**
  True when the document has been changed (when there are any
  steps).
  */
  get docChanged() {
    return this.steps.length > 0;
  }
  /**
  @internal
  */
  addStep(e, t) {
    this.docs.push(this.doc), this.steps.push(e), this.mapping.appendMap(e.getMap()), this.doc = t;
  }
  /**
  Replace the part of the document between `from` and `to` with the
  given `slice`.
  */
  replace(e, t = e, r = O.empty) {
    let i = fc(this.doc, e, t, r);
    return i && this.step(i), this;
  }
  /**
  Replace the given range with the given content, which may be a
  fragment, node, or array of nodes.
  */
  replaceWith(e, t, r) {
    return this.replace(e, t, new O(A.from(r), 0, 0));
  }
  /**
  Delete the content between the given positions.
  */
  delete(e, t) {
    return this.replace(e, t, O.empty);
  }
  /**
  Insert the given content at the given position.
  */
  insert(e, t) {
    return this.replaceWith(e, e, t);
  }
  /**
  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(e, t, r) {
    return Kx(this, e, t, r), 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(e, t, r) {
    return Jx(this, e, t, r), this;
  }
  /**
  Delete the given range, expanding it to cover fully covered
  parent nodes until a valid replace is found.
  */
  deleteRange(e, t) {
    return Yx(this, e, t), 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(e, t) {
    return $x(this, e, t), this;
  }
  /**
  Join the blocks around the given position. If depth is 2, their
  last and first siblings are also joined, and so on.
  */
  join(e, t = 1) {
    return Ux(this, e, t), 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(e, t) {
    return Rx(this, e, t), this;
  }
  /**
  Set the type of all textblocks (partly) between `from` and `to` to
  the given node type with the given attributes.
  */
  setBlockType(e, t = e, r, i = null) {
    return Bx(this, e, t, r, i), 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(e, t, r = null, i) {
    return zx(this, e, t, r, i), 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(e, t, r) {
    return this.step(new Ji(e, t, r)), this;
  }
  /**
  Set a single attribute on the document to a new value.
  */
  setDocAttribute(e, t) {
    return this.step(new fs(e, t)), this;
  }
  /**
  Add a mark to the node at position `pos`.
  */
  addNodeMark(e, t) {
    return this.step(new Er(e, t)), this;
  }
  /**
  Remove a mark (or all marks of the given type) from the node at
  position `pos`.
  */
  removeNodeMark(e, t) {
    let r = this.doc.nodeAt(e);
    if (!r)
      throw new RangeError("No node at position " + e);
    if (t instanceof ue)
      t.isInSet(r.marks) && this.step(new fi(e, t));
    else {
      let i = r.marks, o, s = [];
      for (; o = t.isInSet(i); )
        s.push(new fi(e, o)), i = o.removeFromSet(i);
      for (let l = s.length - 1; l >= 0; l--)
        this.step(s[l]);
    }
    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(e, t = 1, r) {
    return Hx(this, e, t, r), this;
  }
  /**
  Add the given mark to the inline content between `from` and `to`.
  */
  addMark(e, t, r) {
    return Ox(this, e, t, r), 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(e, t, r) {
    return Fx(this, e, t, r), 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(e, t, r) {
    return Mh(this, e, t, r), this;
  }
}
const _d = /* @__PURE__ */ Object.create(null);
class V {
  /**
  Initialize a selection with the head and anchor and ranges. If no
  ranges are given, constructs a single range across `$anchor` and
  `$head`.
  */
  constructor(e, t, r) {
    this.$anchor = e, this.$head = t, this.ranges = r || [new qy(e.min(t), e.max(t))];
  }
  /**
  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 e = this.ranges;
    for (let t = 0; t < e.length; t++)
      if (e[t].$from.pos != e[t].$to.pos)
        return !1;
    return !0;
  }
  /**
  Get the content of this selection as a slice.
  */
  content() {
    return this.$from.doc.slice(this.from, this.to, !0);
  }
  /**
  Replace the selection with a slice or, if no slice is given,
  delete the selection. Will append to the given transaction.
  */
  replace(e, t = O.empty) {
    let r = t.content.lastChild, i = null;
    for (let l = 0; l < t.openEnd; l++)
      i = r, r = r.lastChild;
    let o = e.steps.length, s = this.ranges;
    for (let l = 0; l < s.length; l++) {
      let { $from: a, $to: c } = s[l], d = e.mapping.slice(o);
      e.replaceRange(d.map(a.pos), d.map(c.pos), l ? O.empty : t), l == 0 && Km(e, o, (r ? r.isInline : i && i.isTextblock) ? -1 : 1);
    }
  }
  /**
  Replace the selection with the given node, appending the changes
  to the given transaction.
  */
  replaceWith(e, t) {
    let r = e.steps.length, i = this.ranges;
    for (let o = 0; o < i.length; o++) {
      let { $from: s, $to: l } = i[o], a = e.mapping.slice(r), c = a.map(s.pos), d = a.map(l.pos);
      o ? e.deleteRange(c, d) : (e.replaceRangeWith(c, d, t), Km(e, r, t.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(e, t, r = !1) {
    let i = e.parent.inlineContent ? new L(e) : Hi(e.node(0), e.parent, e.pos, e.index(), t, r);
    if (i)
      return i;
    for (let o = e.depth - 1; o >= 0; o--) {
      let s = t < 0 ? Hi(e.node(0), e.node(o), e.before(o + 1), e.index(o), t, r) : Hi(e.node(0), e.node(o), e.after(o + 1), e.index(o) + 1, t, r);
      if (s)
        return s;
    }
    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(e, t = 1) {
    return this.findFrom(e, t) || this.findFrom(e, -t) || new wt(e.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(e) {
    return Hi(e, e, 0, 0, 1) || new wt(e);
  }
  /**
  Find the cursor or leaf node selection closest to the end of the
  given document.
  */
  static atEnd(e) {
    return Hi(e, e, e.content.size, e.childCount, -1) || new wt(e);
  }
  /**
  Deserialize the JSON representation of a selection. Must be
  implemented for custom classes (as a static class method).
  */
  static fromJSON(e, t) {
    if (!t || !t.type)
      throw new RangeError("Invalid input for Selection.fromJSON");
    let r = _d[t.type];
    if (!r)
      throw new RangeError(`No selection type ${t.type} defined`);
    return r.fromJSON(e, t);
  }
  /**
  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(e, t) {
    if (e in _d)
      throw new RangeError("Duplicate use of selection JSON ID " + e);
    return _d[e] = t, t.prototype.jsonID = e, t;
  }
  /**
  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 L.between(this.$anchor, this.$head).getBookmark();
  }
}
V.prototype.visible = !0;
class qy {
  /**
  Create a range.
  */
  constructor(e, t) {
    this.$from = e, this.$to = t;
  }
}
let Wm = !1;
function Gm(n) {
  !Wm && !n.parent.inlineContent && (Wm = !0, console.warn("TextSelection endpoint not pointing into a node with inline content (" + n.parent.type.name + ")"));
}
class L extends V {
  /**
  Construct a text selection between the given points.
  */
  constructor(e, t = e) {
    Gm(e), Gm(t), super(e, t);
  }
  /**
  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(e, t) {
    let r = e.resolve(t.map(this.head));
    if (!r.parent.inlineContent)
      return V.near(r);
    let i = e.resolve(t.map(this.anchor));
    return new L(i.parent.inlineContent ? i : r, r);
  }
  replace(e, t = O.empty) {
    if (super.replace(e, t), t == O.empty) {
      let r = this.$from.marksAcross(this.$to);
      r && e.ensureMarks(r);
    }
  }
  eq(e) {
    return e instanceof L && e.anchor == this.anchor && e.head == this.head;
  }
  getBookmark() {
    return new pc(this.anchor, this.head);
  }
  toJSON() {
    return { type: "text", anchor: this.anchor, head: this.head };
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.anchor != "number" || typeof t.head != "number")
      throw new RangeError("Invalid input for TextSelection.fromJSON");
    return new L(e.resolve(t.anchor), e.resolve(t.head));
  }
  /**
  Create a text selection from non-resolved positions.
  */
  static create(e, t, r = t) {
    let i = e.resolve(t);
    return new this(i, r == t ? i : e.resolve(r));
  }
  /**
  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(e, t, r) {
    let i = e.pos - t.pos;
    if ((!r || i) && (r = i >= 0 ? 1 : -1), !t.parent.inlineContent) {
      let o = V.findFrom(t, r, !0) || V.findFrom(t, -r, !0);
      if (o)
        t = o.$head;
      else
        return V.near(t, r);
    }
    return e.parent.inlineContent || (i == 0 ? e = t : (e = (V.findFrom(e, -r, !0) || V.findFrom(e, r, !0)).$anchor, e.pos < t.pos != i < 0 && (e = t))), new L(e, t);
  }
}
V.jsonID("text", L);
class pc {
  constructor(e, t) {
    this.anchor = e, this.head = t;
  }
  map(e) {
    return new pc(e.map(this.anchor), e.map(this.head));
  }
  resolve(e) {
    return L.between(e.resolve(this.anchor), e.resolve(this.head));
  }
}
class P extends V {
  /**
  Create a node selection. Does not verify the validity of its
  argument.
  */
  constructor(e) {
    let t = e.nodeAfter, r = e.node(0).resolve(e.pos + t.nodeSize);
    super(e, r), this.node = t;
  }
  map(e, t) {
    let { deleted: r, pos: i } = t.mapResult(this.anchor), o = e.resolve(i);
    return r ? V.near(o) : new P(o);
  }
  content() {
    return new O(A.from(this.node), 0, 0);
  }
  eq(e) {
    return e instanceof P && e.anchor == this.anchor;
  }
  toJSON() {
    return { type: "node", anchor: this.anchor };
  }
  getBookmark() {
    return new Fh(this.anchor);
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.anchor != "number")
      throw new RangeError("Invalid input for NodeSelection.fromJSON");
    return new P(e.resolve(t.anchor));
  }
  /**
  Create a node selection from non-resolved positions.
  */
  static create(e, t) {
    return new P(e.resolve(t));
  }
  /**
  Determines whether the given node may be selected as a node
  selection.
  */
  static isSelectable(e) {
    return !e.isText && e.type.spec.selectable !== !1;
  }
}
P.prototype.visible = !1;
V.jsonID("node", P);
class Fh {
  constructor(e) {
    this.anchor = e;
  }
  map(e) {
    let { deleted: t, pos: r } = e.mapResult(this.anchor);
    return t ? new pc(r, r) : new Fh(r);
  }
  resolve(e) {
    let t = e.resolve(this.anchor), r = t.nodeAfter;
    return r && P.isSelectable(r) ? new P(t) : V.near(t);
  }
}
class wt extends V {
  /**
  Create an all-selection over the given document.
  */
  constructor(e) {
    super(e.resolve(0), e.resolve(e.content.size));
  }
  replace(e, t = O.empty) {
    if (t == O.empty) {
      e.delete(0, e.doc.content.size);
      let r = V.atStart(e.doc);
      r.eq(e.selection) || e.setSelection(r);
    } else
      super.replace(e, t);
  }
  toJSON() {
    return { type: "all" };
  }
  /**
  @internal
  */
  static fromJSON(e) {
    return new wt(e);
  }
  map(e) {
    return new wt(e);
  }
  eq(e) {
    return e instanceof wt;
  }
  getBookmark() {
    return Xx;
  }
}
V.jsonID("all", wt);
const Xx = {
  map() {
    return this;
  },
  resolve(n) {
    return new wt(n);
  }
};
function Hi(n, e, t, r, i, o = !1) {
  if (e.inlineContent)
    return L.create(n, t);
  for (let s = r - (i > 0 ? 0 : 1); i > 0 ? s < e.childCount : s >= 0; s += i) {
    let l = e.child(s);
    if (l.isAtom) {
      if (!o && P.isSelectable(l))
        return P.create(n, t - (i < 0 ? l.nodeSize : 0));
    } else {
      let a = Hi(n, l, t + i, i < 0 ? l.childCount : 0, i, o);
      if (a)
        return a;
    }
    t += l.nodeSize * i;
  }
  return null;
}
function Km(n, e, t) {
  let r = n.steps.length - 1;
  if (r < e)
    return;
  let i = n.steps[r];
  if (!(i instanceof Me || i instanceof Ae))
    return;
  let o = n.mapping.maps[r], s;
  o.forEach((l, a, c, d) => {
    s == null && (s = d);
  }), n.setSelection(V.near(n.doc.resolve(s), t));
}
const Jm = 1, wl = 2, Ym = 4;
let Zx = class extends Oh {
  /**
  @internal
  */
  constructor(e) {
    super(e.doc), this.curSelectionFor = 0, this.updated = 0, this.meta = /* @__PURE__ */ Object.create(null), this.time = Date.now(), this.curSelection = e.selection, this.storedMarks = e.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() {
    return this.curSelectionFor < this.steps.length && (this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)), this.curSelectionFor = this.steps.length), this.curSelection;
  }
  /**
  Update the transaction's current selection. Will determine the
  selection that the editor gets when the transaction is applied.
  */
  setSelection(e) {
    if (e.$from.doc != this.doc)
      throw new RangeError("Selection passed to setSelection must point at the current document");
    return this.curSelection = e, this.curSelectionFor = this.steps.length, this.updated = (this.updated | Jm) & ~wl, this.storedMarks = null, this;
  }
  /**
  Whether the selection was explicitly updated by this transaction.
  */
  get selectionSet() {
    return (this.updated & Jm) > 0;
  }
  /**
  Set the current stored marks.
  */
  setStoredMarks(e) {
    return this.storedMarks = e, this.updated |= wl, 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(e) {
    return ue.sameSet(this.storedMarks || this.selection.$from.marks(), e) || this.setStoredMarks(e), this;
  }
  /**
  Add a mark to the set of stored marks.
  */
  addStoredMark(e) {
    return this.ensureMarks(e.addToSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Remove a mark or mark type from the set of stored marks.
  */
  removeStoredMark(e) {
    return this.ensureMarks(e.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Whether the stored marks were explicitly set for this transaction.
  */
  get storedMarksSet() {
    return (this.updated & wl) > 0;
  }
  /**
  @internal
  */
  addStep(e, t) {
    super.addStep(e, t), this.updated = this.updated & ~wl, this.storedMarks = null;
  }
  /**
  Update the timestamp for the transaction.
  */
  setTime(e) {
    return this.time = e, this;
  }
  /**
  Replace the current selection with the given slice.
  */
  replaceSelection(e) {
    return this.selection.replace(this, e), 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(e, t = !0) {
    let r = this.selection;
    return t && (e = e.mark(this.storedMarks || (r.empty ? r.$from.marks() : r.$from.marksAcross(r.$to) || ue.none))), r.replaceWith(this, e), this;
  }
  /**
  Delete the selection.
  */
  deleteSelection() {
    return this.selection.replace(this), this;
  }
  /**
  Replace the given range, or the selection if no range is given,
  with a text node containing the given string.
  */
  insertText(e, t, r) {
    let i = this.doc.type.schema;
    if (t == null)
      return e ? this.replaceSelectionWith(i.text(e), !0) : this.deleteSelection();
    {
      if (r == null && (r = t), r = r ?? t, !e)
        return this.deleteRange(t, r);
      let o = this.storedMarks;
      if (!o) {
        let s = this.doc.resolve(t);
        o = r == t ? s.marks() : s.marksAcross(this.doc.resolve(r));
      }
      return this.replaceRangeWith(t, r, i.text(e, o)), this.selection.empty || this.setSelection(V.near(this.selection.$to)), this;
    }
  }
  /**
  Store a metadata property in this transaction, keyed either by
  name or by plugin.
  */
  setMeta(e, t) {
    return this.meta[typeof e == "string" ? e : e.key] = t, this;
  }
  /**
  Retrieve a metadata property for a given name or plugin.
  */
  getMeta(e) {
    return this.meta[typeof e == "string" ? e : e.key];
  }
  /**
  Returns true if this transaction doesn't contain any metadata,
  and can thus safely be extended.
  */
  get isGeneric() {
    for (let e in this.meta)
      return !1;
    return !0;
  }
  /**
  Indicate that the editor should scroll the selection into view
  when updated to the state produced by this transaction.
  */
  scrollIntoView() {
    return this.updated |= Ym, this;
  }
  /**
  True when this transaction has had `scrollIntoView` called on it.
  */
  get scrolledIntoView() {
    return (this.updated & Ym) > 0;
  }
};
function Xm(n, e) {
  return !e || !n ? n : n.bind(e);
}
class zo {
  constructor(e, t, r) {
    this.name = e, this.init = Xm(t.init, r), this.apply = Xm(t.apply, r);
  }
}
const Qx = [
  new zo("doc", {
    init(n) {
      return n.doc || n.schema.topNodeType.createAndFill();
    },
    apply(n) {
      return n.doc;
    }
  }),
  new zo("selection", {
    init(n, e) {
      return n.selection || V.atStart(e.doc);
    },
    apply(n) {
      return n.selection;
    }
  }),
  new zo("storedMarks", {
    init(n) {
      return n.storedMarks || null;
    },
    apply(n, e, t, r) {
      return r.selection.$cursor ? n.storedMarks : null;
    }
  }),
  new zo("scrollToSelection", {
    init() {
      return 0;
    },
    apply(n, e) {
      return n.scrolledIntoView ? e + 1 : e;
    }
  })
];
class wd {
  constructor(e, t) {
    this.schema = e, this.plugins = [], this.pluginsByKey = /* @__PURE__ */ Object.create(null), this.fields = Qx.slice(), t && t.forEach((r) => {
      if (this.pluginsByKey[r.key])
        throw new RangeError("Adding different instances of a keyed plugin (" + r.key + ")");
      this.plugins.push(r), this.pluginsByKey[r.key] = r, r.spec.state && this.fields.push(new zo(r.key, r.spec.state, r));
    });
  }
}
class Zr {
  /**
  @internal
  */
  constructor(e) {
    this.config = e;
  }
  /**
  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(e) {
    return this.applyTransaction(e).state;
  }
  /**
  @internal
  */
  filterTransaction(e, t = -1) {
    for (let r = 0; r < this.config.plugins.length; r++)
      if (r != t) {
        let i = this.config.plugins[r];
        if (i.spec.filterTransaction && !i.spec.filterTransaction.call(i, e, this))
          return !1;
      }
    return !0;
  }
  /**
  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(e) {
    if (!this.filterTransaction(e))
      return { state: this, transactions: [] };
    let t = [e], r = this.applyInner(e), i = null;
    for (; ; ) {
      let o = !1;
      for (let s = 0; s < this.config.plugins.length; s++) {
        let l = this.config.plugins[s];
        if (l.spec.appendTransaction) {
          let a = i ? i[s].n : 0, c = i ? i[s].state : this, d = a < t.length && l.spec.appendTransaction.call(l, a ? t.slice(a) : t, c, r);
          if (d && r.filterTransaction(d, s)) {
            if (d.setMeta("appendedTransaction", e), !i) {
              i = [];
              for (let u = 0; u < this.config.plugins.length; u++)
                i.push(u < s ? { state: r, n: t.length } : { state: this, n: 0 });
            }
            t.push(d), r = r.applyInner(d), o = !0;
          }
          i && (i[s] = { state: r, n: t.length });
        }
      }
      if (!o)
        return { state: r, transactions: t };
    }
  }
  /**
  @internal
  */
  applyInner(e) {
    if (!e.before.eq(this.doc))
      throw new RangeError("Applying a mismatched transaction");
    let t = new Zr(this.config), r = this.config.fields;
    for (let i = 0; i < r.length; i++) {
      let o = r[i];
      t[o.name] = o.apply(e, this[o.name], this, t);
    }
    return t;
  }
  /**
  Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.
  */
  get tr() {
    return new Zx(this);
  }
  /**
  Create a new state.
  */
  static create(e) {
    let t = new wd(e.doc ? e.doc.type.schema : e.schema, e.plugins), r = new Zr(t);
    for (let i = 0; i < t.fields.length; i++)
      r[t.fields[i].name] = t.fields[i].init(e, r);
    return r;
  }
  /**
  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(e) {
    let t = new wd(this.schema, e.plugins), r = t.fields, i = new Zr(t);
    for (let o = 0; o < r.length; o++) {
      let s = r[o].name;
      i[s] = this.hasOwnProperty(s) ? this[s] : r[o].init(e, i);
    }
    return i;
  }
  /**
  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(e) {
    let t = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
    if (this.storedMarks && (t.storedMarks = this.storedMarks.map((r) => r.toJSON())), e && typeof e == "object")
      for (let r in e) {
        if (r == "doc" || r == "selection")
          throw new RangeError("The JSON fields `doc` and `selection` are reserved");
        let i = e[r], o = i.spec.state;
        o && o.toJSON && (t[r] = o.toJSON.call(i, this[i.key]));
      }
    return t;
  }
  /**
  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(e, t, r) {
    if (!t)
      throw new RangeError("Invalid input for EditorState.fromJSON");
    if (!e.schema)
      throw new RangeError("Required config field 'schema' missing");
    let i = new wd(e.schema, e.plugins), o = new Zr(i);
    return i.fields.forEach((s) => {
      if (s.name == "doc")
        o.doc = Qn.fromJSON(e.schema, t.doc);
      else if (s.name == "selection")
        o.selection = V.fromJSON(o.doc, t.selection);
      else if (s.name == "storedMarks")
        t.storedMarks && (o.storedMarks = t.storedMarks.map(e.schema.markFromJSON));
      else {
        if (r)
          for (let l in r) {
            let a = r[l], c = a.spec.state;
            if (a.key == s.name && c && c.fromJSON && Object.prototype.hasOwnProperty.call(t, l)) {
              o[s.name] = c.fromJSON.call(a, e, t[l], o);
              return;
            }
          }
        o[s.name] = s.init(e, o);
      }
    }), o;
  }
}
function jy(n, e, t) {
  for (let r in n) {
    let i = n[r];
    i instanceof Function ? i = i.bind(e) : r == "handleDOMEvents" && (i = jy(i, e, {})), t[r] = i;
  }
  return t;
}
class G {
  /**
  Create a plugin.
  */
  constructor(e) {
    this.spec = e, this.props = {}, e.props && jy(e.props, this, this.props), this.key = e.key ? e.key.key : Wy("plugin");
  }
  /**
  Extract the plugin's state field from an editor state.
  */
  getState(e) {
    return e[this.key];
  }
}
const kd = /* @__PURE__ */ Object.create(null);
function Wy(n) {
  return n in kd ? n + "$" + ++kd[n] : (kd[n] = 0, n + "$");
}
class te {
  /**
  Create a plugin key.
  */
  constructor(e = "key") {
    this.key = Wy(e);
  }
  /**
  Get the active plugin with this key, if any, from an editor
  state.
  */
  get(e) {
    return e.config.pluginsByKey[this.key];
  }
  /**
  Get the plugin's state from an editor state.
  */
  getState(e) {
    return e[this.key];
  }
}
const Ge = function(n) {
  for (var e = 0; ; e++)
    if (n = n.previousSibling, !n)
      return e;
}, oo = function(n) {
  let e = n.assignedSlot || n.parentNode;
  return e && e.nodeType == 11 ? e.host : e;
};
let vu = null;
const Yn = function(n, e, t) {
  let r = vu || (vu = document.createRange());
  return r.setEnd(n, t ?? n.nodeValue.length), r.setStart(n, e || 0), r;
}, eD = function() {
  vu = null;
}, pi = function(n, e, t, r) {
  return t && (Zm(n, e, t, r, -1) || Zm(n, e, t, r, 1));
}, tD = /^(img|br|input|textarea|hr)$/i;
function Zm(n, e, t, r, i) {
  for (var o; ; ) {
    if (n == t && e == r)
      return !0;
    if (e == (i < 0 ? 0 : Ht(n))) {
      let s = n.parentNode;
      if (!s || s.nodeType != 1 || Ps(n) || tD.test(n.nodeName) || n.contentEditable == "false")
        return !1;
      e = Ge(n) + (i < 0 ? 0 : 1), n = s;
    } else if (n.nodeType == 1) {
      let s = n.childNodes[e + (i < 0 ? -1 : 0)];
      if (s.nodeType == 1 && s.contentEditable == "false")
        if (!((o = s.pmViewDesc) === null || o === void 0) && o.ignoreForSelection)
          e += i;
        else
          return !1;
      else
        n = s, e = i < 0 ? Ht(n) : 0;
    } else
      return !1;
  }
}
function Ht(n) {
  return n.nodeType == 3 ? n.nodeValue.length : n.childNodes.length;
}
function nD(n, e) {
  for (; ; ) {
    if (n.nodeType == 3 && e)
      return n;
    if (n.nodeType == 1 && e > 0) {
      if (n.contentEditable == "false")
        return null;
      n = n.childNodes[e - 1], e = Ht(n);
    } else if (n.parentNode && !Ps(n))
      e = Ge(n), n = n.parentNode;
    else
      return null;
  }
}
function rD(n, e) {
  for (; ; ) {
    if (n.nodeType == 3 && e < n.nodeValue.length)
      return n;
    if (n.nodeType == 1 && e < n.childNodes.length) {
      if (n.contentEditable == "false")
        return null;
      n = n.childNodes[e], e = 0;
    } else if (n.parentNode && !Ps(n))
      e = Ge(n) + 1, n = n.parentNode;
    else
      return null;
  }
}
function iD(n, e, t) {
  for (let r = e == 0, i = e == Ht(n); r || i; ) {
    if (n == t)
      return !0;
    let o = Ge(n);
    if (n = n.parentNode, !n)
      return !1;
    r = r && o == 0, i = i && o == Ht(n);
  }
}
function Ps(n) {
  let e;
  for (let t = n; t && !(e = t.pmViewDesc); t = t.parentNode)
    ;
  return e && e.node && e.node.isBlock && (e.dom == n || e.contentDOM == n);
}
const mc = function(n) {
  return n.focusNode && pi(n.focusNode, n.focusOffset, n.anchorNode, n.anchorOffset);
};
function Gr(n, e) {
  let t = document.createEvent("Event");
  return t.initEvent("keydown", !0, !0), t.keyCode = n, t.key = t.code = e, t;
}
function oD(n) {
  let e = n.activeElement;
  for (; e && e.shadowRoot; )
    e = e.shadowRoot.activeElement;
  return e;
}
function sD(n, e, t) {
  if (n.caretPositionFromPoint)
    try {
      let r = n.caretPositionFromPoint(e, t);
      if (r)
        return { node: r.offsetNode, offset: Math.min(Ht(r.offsetNode), r.offset) };
    } catch {
    }
  if (n.caretRangeFromPoint) {
    let r = n.caretRangeFromPoint(e, t);
    if (r)
      return { node: r.startContainer, offset: Math.min(Ht(r.startContainer), r.startOffset) };
  }
}
const Nn = typeof navigator < "u" ? navigator : null, Qm = typeof document < "u" ? document : null, Pr = Nn && Nn.userAgent || "", Cu = /Edge\/(\d+)/.exec(Pr), Gy = /MSIE \d/.exec(Pr), Su = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Pr), kt = !!(Gy || Su || Cu), Ar = Gy ? document.documentMode : Su ? +Su[1] : Cu ? +Cu[1] : 0, hn = !kt && /gecko\/(\d+)/i.test(Pr);
hn && +(/Firefox\/(\d+)/.exec(Pr) || [0, 0])[1];
const Eu = !kt && /Chrome\/(\d+)/.exec(Pr), nt = !!Eu, Ky = Eu ? +Eu[1] : 0, ht = !kt && !!Nn && /Apple Computer/.test(Nn.vendor), so = ht && (/Mobile\/\w+/.test(Pr) || !!Nn && Nn.maxTouchPoints > 2), zt = so || (Nn ? /Mac/.test(Nn.platform) : !1), lD = Nn ? /Win/.test(Nn.platform) : !1, Xn = /Android \d/.test(Pr), zs = !!Qm && "webkitFontSmoothing" in Qm.documentElement.style, aD = zs ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;
function cD(n) {
  let e = n.defaultView && n.defaultView.visualViewport;
  return e ? {
    left: 0,
    right: e.width,
    top: 0,
    bottom: e.height
  } : {
    left: 0,
    right: n.documentElement.clientWidth,
    top: 0,
    bottom: n.documentElement.clientHeight
  };
}
function Vn(n, e) {
  return typeof n == "number" ? n : n[e];
}
function dD(n) {
  let e = n.getBoundingClientRect(), t = e.width / n.offsetWidth || 1, r = e.height / n.offsetHeight || 1;
  return {
    left: e.left,
    right: e.left + n.clientWidth * t,
    top: e.top,
    bottom: e.top + n.clientHeight * r
  };
}
function eg(n, e, t) {
  let r = n.someProp("scrollThreshold") || 0, i = n.someProp("scrollMargin") || 5, o = n.dom.ownerDocument;
  for (let s = t || n.dom; s; ) {
    if (s.nodeType != 1) {
      s = oo(s);
      continue;
    }
    let l = s, a = l == o.body, c = a ? cD(o) : dD(l), d = 0, u = 0;
    if (e.top < c.top + Vn(r, "top") ? u = -(c.top - e.top + Vn(i, "top")) : e.bottom > c.bottom - Vn(r, "bottom") && (u = e.bottom - e.top > c.bottom - c.top ? e.top + Vn(i, "top") - c.top : e.bottom - c.bottom + Vn(i, "bottom")), e.left < c.left + Vn(r, "left") ? d = -(c.left - e.left + Vn(i, "left")) : e.right > c.right - Vn(r, "right") && (d = e.right - c.right + Vn(i, "right")), d || u)
      if (a)
        o.defaultView.scrollBy(d, u);
      else {
        let f = l.scrollLeft, p = l.scrollTop;
        u && (l.scrollTop += u), d && (l.scrollLeft += d);
        let m = l.scrollLeft - f, g = l.scrollTop - p;
        e = { left: e.left - m, top: e.top - g, right: e.right - m, bottom: e.bottom - g };
      }
    let h = a ? "fixed" : getComputedStyle(s).position;
    if (/^(fixed|sticky)$/.test(h))
      break;
    s = h == "absolute" ? s.offsetParent : oo(s);
  }
}
function uD(n) {
  let e = n.dom.getBoundingClientRect(), t = Math.max(0, e.top), r, i;
  for (let o = (e.left + e.right) / 2, s = t + 1; s < Math.min(innerHeight, e.bottom); s += 5) {
    let l = n.root.elementFromPoint(o, s);
    if (!l || l == n.dom || !n.dom.contains(l))
      continue;
    let a = l.getBoundingClientRect();
    if (a.top >= t - 20) {
      r = l, i = a.top;
      break;
    }
  }
  return { refDOM: r, refTop: i, stack: Jy(n.dom) };
}
function Jy(n) {
  let e = [], t = n.ownerDocument;
  for (let r = n; r && (e.push({ dom: r, top: r.scrollTop, left: r.scrollLeft }), n != t); r = oo(r))
    ;
  return e;
}
function hD({ refDOM: n, refTop: e, stack: t }) {
  let r = n ? n.getBoundingClientRect().top : 0;
  Yy(t, r == 0 ? 0 : r - e);
}
function Yy(n, e) {
  for (let t = 0; t < n.length; t++) {
    let { dom: r, top: i, left: o } = n[t];
    r.scrollTop != i + e && (r.scrollTop = i + e), r.scrollLeft != o && (r.scrollLeft = o);
  }
}
let Pi = null;
function fD(n) {
  if (n.setActive)
    return n.setActive();
  if (Pi)
    return n.focus(Pi);
  let e = Jy(n);
  n.focus(Pi == null ? {
    get preventScroll() {
      return Pi = { preventScroll: !0 }, !0;
    }
  } : void 0), Pi || (Pi = !1, Yy(e, 0));
}
function Xy(n, e) {
  let t, r = 2e8, i, o = 0, s = e.top, l = e.top, a, c;
  for (let d = n.firstChild, u = 0; d; d = d.nextSibling, u++) {
    let h;
    if (d.nodeType == 1)
      h = d.getClientRects();
    else if (d.nodeType == 3)
      h = Yn(d).getClientRects();
    else
      continue;
    for (let f = 0; f < h.length; f++) {
      let p = h[f];
      if (p.top <= s && p.bottom >= l) {
        s = Math.max(p.bottom, s), l = Math.min(p.top, l);
        let m = p.left > e.left ? p.left - e.left : p.right < e.left ? e.left - p.right : 0;
        if (m < r) {
          t = d, r = m, i = m && t.nodeType == 3 ? {
            left: p.right < e.left ? p.right : p.left,
            top: e.top
          } : e, d.nodeType == 1 && m && (o = u + (e.left >= (p.left + p.right) / 2 ? 1 : 0));
          continue;
        }
      } else p.top > e.top && !a && p.left <= e.left && p.right >= e.left && (a = d, c = { left: Math.max(p.left, Math.min(p.right, e.left)), top: p.top });
      !t && (e.left >= p.right && e.top >= p.top || e.left >= p.left && e.top >= p.bottom) && (o = u + 1);
    }
  }
  return !t && a && (t = a, i = c, r = 0), t && t.nodeType == 3 ? pD(t, i) : !t || r && t.nodeType == 1 ? { node: n, offset: o } : Xy(t, i);
}
function pD(n, e) {
  let t = n.nodeValue.length, r = document.createRange();
  for (let i = 0; i < t; i++) {
    r.setEnd(n, i + 1), r.setStart(n, i);
    let o = mr(r, 1);
    if (o.top != o.bottom && Nh(e, o))
      return { node: n, offset: i + (e.left >= (o.left + o.right) / 2 ? 1 : 0) };
  }
  return { node: n, offset: 0 };
}
function Nh(n, e) {
  return n.left >= e.left - 1 && n.left <= e.right + 1 && n.top >= e.top - 1 && n.top <= e.bottom + 1;
}
function mD(n, e) {
  let t = n.parentNode;
  return t && /^li$/i.test(t.nodeName) && e.left < n.getBoundingClientRect().left ? t : n;
}
function gD(n, e, t) {
  let { node: r, offset: i } = Xy(e, t), o = -1;
  if (r.nodeType == 1 && !r.firstChild) {
    let s = r.getBoundingClientRect();
    o = s.left != s.right && t.left > (s.left + s.right) / 2 ? 1 : -1;
  }
  return n.docView.posFromDOM(r, i, o);
}
function bD(n, e, t, r) {
  let i = -1;
  for (let o = e, s = !1; o != n.dom; ) {
    let l = n.docView.nearestDesc(o, !0), a;
    if (!l)
      return null;
    if (l.dom.nodeType == 1 && (l.node.isBlock && l.parent || !l.contentDOM) && // Ignore elements with zero-size bounding rectangles
    ((a = l.dom.getBoundingClientRect()).width || a.height) && (l.node.isBlock && l.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName) && (!s && a.left > r.left || a.top > r.top ? i = l.posBefore : (!s && a.right < r.left || a.bottom < r.top) && (i = l.posAfter), s = !0), !l.contentDOM && i < 0 && !l.node.isText))
      return (l.node.isBlock ? r.top < (a.top + a.bottom) / 2 : r.left < (a.left + a.right) / 2) ? l.posBefore : l.posAfter;
    o = l.dom.parentNode;
  }
  return i > -1 ? i : n.docView.posFromDOM(e, t, -1);
}
function Zy(n, e, t) {
  let r = n.childNodes.length;
  if (r && t.top < t.bottom)
    for (let i = Math.max(0, Math.min(r - 1, Math.floor(r * (e.top - t.top) / (t.bottom - t.top)) - 2)), o = i; ; ) {
      let s = n.childNodes[o];
      if (s.nodeType == 1) {
        let l = s.getClientRects();
        for (let a = 0; a < l.length; a++) {
          let c = l[a];
          if (Nh(e, c))
            return Zy(s, e, c);
        }
      }
      if ((o = (o + 1) % r) == i)
        break;
    }
  return n;
}
function yD(n, e) {
  let t = n.dom.ownerDocument, r, i = 0, o = sD(t, e.left, e.top);
  o && ({ node: r, offset: i } = o);
  let s = (n.root.elementFromPoint ? n.root : t).elementFromPoint(e.left, e.top), l;
  if (!s || !n.dom.contains(s.nodeType != 1 ? s.parentNode : s)) {
    let c = n.dom.getBoundingClientRect();
    if (!Nh(e, c) || (s = Zy(n.dom, e, c), !s))
      return null;
  }
  if (ht)
    for (let c = s; r && c; c = oo(c))
      c.draggable && (r = void 0);
  if (s = mD(s, e), r) {
    if (hn && r.nodeType == 1 && (i = Math.min(i, r.childNodes.length), i < r.childNodes.length)) {
      let d = r.childNodes[i], u;
      d.nodeName == "IMG" && (u = d.getBoundingClientRect()).right <= e.left && u.bottom > e.top && i++;
    }
    let c;
    zs && i && r.nodeType == 1 && (c = r.childNodes[i - 1]).nodeType == 1 && c.contentEditable == "false" && c.getBoundingClientRect().top >= e.top && i--, r == n.dom && i == r.childNodes.length - 1 && r.lastChild.nodeType == 1 && e.top > r.lastChild.getBoundingClientRect().bottom ? l = n.state.doc.content.size : (i == 0 || r.nodeType != 1 || r.childNodes[i - 1].nodeName != "BR") && (l = bD(n, r, i, e));
  }
  l == null && (l = gD(n, s, e));
  let a = n.docView.nearestDesc(s, !0);
  return { pos: l, inside: a ? a.posAtStart - a.border : -1 };
}
function tg(n) {
  return n.top < n.bottom || n.left < n.right;
}
function mr(n, e) {
  let t = n.getClientRects();
  if (t.length) {
    let r = t[e < 0 ? 0 : t.length - 1];
    if (tg(r))
      return r;
  }
  return Array.prototype.find.call(t, tg) || n.getBoundingClientRect();
}
const _D = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
function Qy(n, e, t) {
  let { node: r, offset: i, atom: o } = n.docView.domFromPos(e, t < 0 ? -1 : 1), s = zs || hn;
  if (r.nodeType == 3)
    if (s && (_D.test(r.nodeValue) || (t < 0 ? !i : i == r.nodeValue.length))) {
      let a = mr(Yn(r, i, i), t);
      if (hn && i && /\s/.test(r.nodeValue[i - 1]) && i < r.nodeValue.length) {
        let c = mr(Yn(r, i - 1, i - 1), -1);
        if (c.top == a.top) {
          let d = mr(Yn(r, i, i + 1), -1);
          if (d.top != a.top)
            return $o(d, d.left < c.left);
        }
      }
      return a;
    } else {
      let a = i, c = i, d = t < 0 ? 1 : -1;
      return t < 0 && !i ? (c++, d = -1) : t >= 0 && i == r.nodeValue.length ? (a--, d = 1) : t < 0 ? a-- : c++, $o(mr(Yn(r, a, c), d), d < 0);
    }
  if (!n.state.doc.resolve(e - (o || 0)).parent.inlineContent) {
    if (o == null && i && (t < 0 || i == Ht(r))) {
      let a = r.childNodes[i - 1];
      if (a.nodeType == 1)
        return vd(a.getBoundingClientRect(), !1);
    }
    if (o == null && i < Ht(r)) {
      let a = r.childNodes[i];
      if (a.nodeType == 1)
        return vd(a.getBoundingClientRect(), !0);
    }
    return vd(r.getBoundingClientRect(), t >= 0);
  }
  if (o == null && i && (t < 0 || i == Ht(r))) {
    let a = r.childNodes[i - 1], c = a.nodeType == 3 ? Yn(a, Ht(a) - (s ? 0 : 1)) : a.nodeType == 1 && (a.nodeName != "BR" || !a.nextSibling) ? a : null;
    if (c)
      return $o(mr(c, 1), !1);
  }
  if (o == null && i < Ht(r)) {
    let a = r.childNodes[i];
    for (; a.pmViewDesc && a.pmViewDesc.ignoreForCoords; )
      a = a.nextSibling;
    let c = a ? a.nodeType == 3 ? Yn(a, 0, s ? 0 : 1) : a.nodeType == 1 ? a : null : null;
    if (c)
      return $o(mr(c, -1), !0);
  }
  return $o(mr(r.nodeType == 3 ? Yn(r) : r, -t), t >= 0);
}
function $o(n, e) {
  if (n.width == 0)
    return n;
  let t = e ? n.left : n.right;
  return { top: n.top, bottom: n.bottom, left: t, right: t };
}
function vd(n, e) {
  if (n.height == 0)
    return n;
  let t = e ? n.top : n.bottom;
  return { top: t, bottom: t, left: n.left, right: n.right };
}
function e_(n, e, t) {
  let r = n.state, i = n.root.activeElement;
  r != e && n.updateState(e), i != n.dom && n.focus();
  try {
    return t();
  } finally {
    r != e && n.updateState(r), i != n.dom && i && i.focus();
  }
}
function wD(n, e, t) {
  let r = e.selection, i = t == "up" ? r.$from : r.$to;
  return e_(n, e, () => {
    let { node: o } = n.docView.domFromPos(i.pos, t == "up" ? -1 : 1);
    for (; ; ) {
      let l = n.docView.nearestDesc(o, !0);
      if (!l)
        break;
      if (l.node.isBlock) {
        o = l.contentDOM || l.dom;
        break;
      }
      o = l.dom.parentNode;
    }
    let s = Qy(n, i.pos, 1);
    for (let l = o.firstChild; l; l = l.nextSibling) {
      let a;
      if (l.nodeType == 1)
        a = l.getClientRects();
      else if (l.nodeType == 3)
        a = Yn(l, 0, l.nodeValue.length).getClientRects();
      else
        continue;
      for (let c = 0; c < a.length; c++) {
        let d = a[c];
        if (d.bottom > d.top + 1 && (t == "up" ? s.top - d.top > (d.bottom - s.top) * 2 : d.bottom - s.bottom > (s.bottom - d.top) * 2))
          return !1;
      }
    }
    return !0;
  });
}
const kD = /[\u0590-\u08ac]/;
function vD(n, e, t) {
  let { $head: r } = e.selection;
  if (!r.parent.isTextblock)
    return !1;
  let i = r.parentOffset, o = !i, s = i == r.parent.content.size, l = n.domSelection();
  return l ? !kD.test(r.parent.textContent) || !l.modify ? t == "left" || t == "backward" ? o : s : e_(n, e, () => {
    let { focusNode: a, focusOffset: c, anchorNode: d, anchorOffset: u } = n.domSelectionRange(), h = l.caretBidiLevel;
    l.modify("move", t, "character");
    let f = r.depth ? n.docView.domAfterPos(r.before()) : n.dom, { focusNode: p, focusOffset: m } = n.domSelectionRange(), g = p && !f.contains(p.nodeType == 1 ? p : p.parentNode) || a == p && c == m;
    try {
      l.collapse(d, u), a && (a != d || c != u) && l.extend && l.extend(a, c);
    } catch {
    }
    return h != null && (l.caretBidiLevel = h), g;
  }) : r.pos == r.start() || r.pos == r.end();
}
let ng = null, rg = null, ig = !1;
function CD(n, e, t) {
  return ng == e && rg == t ? ig : (ng = e, rg = t, ig = t == "up" || t == "down" ? wD(n, e, t) : vD(n, e, t));
}
const Gt = 0, og = 1, Qr = 2, $n = 3;
class Hs {
  constructor(e, t, r, i) {
    this.parent = e, this.children = t, this.dom = r, this.contentDOM = i, this.dirty = Gt, r.pmViewDesc = this;
  }
  // Used to check whether a given description corresponds to a
  // widget/mark/node.
  matchesWidget(e) {
    return !1;
  }
  matchesMark(e) {
    return !1;
  }
  matchesNode(e, t, r) {
    return !1;
  }
  matchesHack(e) {
    return !1;
  }
  // 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(e) {
    return !1;
  }
  // The size of the content represented by this desc.
  get size() {
    let e = 0;
    for (let t = 0; t < this.children.length; t++)
      e += this.children[t].size;
    return e;
  }
  // For block nodes, this represents the space taken up by their
  // start/end tokens.
  get border() {
    return 0;
  }
  destroy() {
    this.parent = void 0, this.dom.pmViewDesc == this && (this.dom.pmViewDesc = void 0);
    for (let e = 0; e < this.children.length; e++)
      this.children[e].destroy();
  }
  posBeforeChild(e) {
    for (let t = 0, r = this.posAtStart; ; t++) {
      let i = this.children[t];
      if (i == e)
        return r;
      r += i.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(e, t, r) {
    if (this.contentDOM && this.contentDOM.contains(e.nodeType == 1 ? e : e.parentNode))
      if (r < 0) {
        let o, s;
        if (e == this.contentDOM)
          o = e.childNodes[t - 1];
        else {
          for (; e.parentNode != this.contentDOM; )
            e = e.parentNode;
          o = e.previousSibling;
        }
        for (; o && !((s = o.pmViewDesc) && s.parent == this); )
          o = o.previousSibling;
        return o ? this.posBeforeChild(s) + s.size : this.posAtStart;
      } else {
        let o, s;
        if (e == this.contentDOM)
          o = e.childNodes[t];
        else {
          for (; e.parentNode != this.contentDOM; )
            e = e.parentNode;
          o = e.nextSibling;
        }
        for (; o && !((s = o.pmViewDesc) && s.parent == this); )
          o = o.nextSibling;
        return o ? this.posBeforeChild(s) : this.posAtEnd;
      }
    let i;
    if (e == this.dom && this.contentDOM)
      i = t > Ge(this.contentDOM);
    else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM))
      i = e.compareDocumentPosition(this.contentDOM) & 2;
    else if (this.dom.firstChild) {
      if (t == 0)
        for (let o = e; ; o = o.parentNode) {
          if (o == this.dom) {
            i = !1;
            break;
          }
          if (o.previousSibling)
            break;
        }
      if (i == null && t == e.childNodes.length)
        for (let o = e; ; o = o.parentNode) {
          if (o == this.dom) {
            i = !0;
            break;
          }
          if (o.nextSibling)
            break;
        }
    }
    return i ?? r > 0 ? this.posAtEnd : this.posAtStart;
  }
  nearestDesc(e, t = !1) {
    for (let r = !0, i = e; i; i = i.parentNode) {
      let o = this.getDesc(i), s;
      if (o && (!t || o.node))
        if (r && (s = o.nodeDOM) && !(s.nodeType == 1 ? s.contains(e.nodeType == 1 ? e : e.parentNode) : s == e))
          r = !1;
        else
          return o;
    }
  }
  getDesc(e) {
    let t = e.pmViewDesc;
    for (let r = t; r; r = r.parent)
      if (r == this)
        return t;
  }
  posFromDOM(e, t, r) {
    for (let i = e; i; i = i.parentNode) {
      let o = this.getDesc(i);
      if (o)
        return o.localPosFromDOM(e, t, r);
    }
    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(e) {
    for (let t = 0, r = 0; t < this.children.length; t++) {
      let i = this.children[t], o = r + i.size;
      if (r == e && o != r) {
        for (; !i.border && i.children.length; )
          for (let s = 0; s < i.children.length; s++) {
            let l = i.children[s];
            if (l.size) {
              i = l;
              break;
            }
          }
        return i;
      }
      if (e < o)
        return i.descAt(e - r - i.border);
      r = o;
    }
  }
  domFromPos(e, t) {
    if (!this.contentDOM)
      return { node: this.dom, offset: 0, atom: e + 1 };
    let r = 0, i = 0;
    for (let o = 0; r < this.children.length; r++) {
      let s = this.children[r], l = o + s.size;
      if (l > e || s instanceof n_) {
        i = e - o;
        break;
      }
      o = l;
    }
    if (i)
      return this.children[r].domFromPos(i - this.children[r].border, t);
    for (let o; r && !(o = this.children[r - 1]).size && o instanceof t_ && o.side >= 0; r--)
      ;
    if (t <= 0) {
      let o, s = !0;
      for (; o = r ? this.children[r - 1] : null, !(!o || o.dom.parentNode == this.contentDOM); r--, s = !1)
        ;
      return o && t && s && !o.border && !o.domAtom ? o.domFromPos(o.size, t) : { node: this.contentDOM, offset: o ? Ge(o.dom) + 1 : 0 };
    } else {
      let o, s = !0;
      for (; o = r < this.children.length ? this.children[r] : null, !(!o || o.dom.parentNode == this.contentDOM); r++, s = !1)
        ;
      return o && s && !o.border && !o.domAtom ? o.domFromPos(0, t) : { node: this.contentDOM, offset: o ? Ge(o.dom) : this.contentDOM.childNodes.length };
    }
  }
  // Used to find a DOM range in a single parent for a given changed
  // range.
  parseRange(e, t, r = 0) {
    if (this.children.length == 0)
      return { node: this.contentDOM, from: e, to: t, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };
    let i = -1, o = -1;
    for (let s = r, l = 0; ; l++) {
      let a = this.children[l], c = s + a.size;
      if (i == -1 && e <= c) {
        let d = s + a.border;
        if (e >= d && t <= c - a.border && a.node && a.contentDOM && this.contentDOM.contains(a.contentDOM))
          return a.parseRange(e, t, d);
        e = s;
        for (let u = l; u > 0; u--) {
          let h = this.children[u - 1];
          if (h.size && h.dom.parentNode == this.contentDOM && !h.emptyChildAt(1)) {
            i = Ge(h.dom) + 1;
            break;
          }
          e -= h.size;
        }
        i == -1 && (i = 0);
      }
      if (i > -1 && (c > t || l == this.children.length - 1)) {
        t = c;
        for (let d = l + 1; d < this.children.length; d++) {
          let u = this.children[d];
          if (u.size && u.dom.parentNode == this.contentDOM && !u.emptyChildAt(-1)) {
            o = Ge(u.dom);
            break;
          }
          t += u.size;
        }
        o == -1 && (o = this.contentDOM.childNodes.length);
        break;
      }
      s = c;
    }
    return { node: this.contentDOM, from: e, to: t, fromOffset: i, toOffset: o };
  }
  emptyChildAt(e) {
    if (this.border || !this.contentDOM || !this.children.length)
      return !1;
    let t = this.children[e < 0 ? 0 : this.children.length - 1];
    return t.size == 0 || t.emptyChildAt(e);
  }
  domAfterPos(e) {
    let { node: t, offset: r } = this.domFromPos(e, 0);
    if (t.nodeType != 1 || r == t.childNodes.length)
      throw new RangeError("No node after pos " + e);
    return t.childNodes[r];
  }
  // 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(e, t, r, i = !1) {
    let o = Math.min(e, t), s = Math.max(e, t);
    for (let f = 0, p = 0; f < this.children.length; f++) {
      let m = this.children[f], g = p + m.size;
      if (o > p && s < g)
        return m.setSelection(e - p - m.border, t - p - m.border, r, i);
      p = g;
    }
    let l = this.domFromPos(e, e ? -1 : 1), a = t == e ? l : this.domFromPos(t, t ? -1 : 1), c = r.root.getSelection(), d = r.domSelectionRange(), u = !1;
    if ((hn || ht) && e == t) {
      let { node: f, offset: p } = l;
      if (f.nodeType == 3) {
        if (u = !!(p && f.nodeValue[p - 1] == `
`), u && p == f.nodeValue.length)
          for (let m = f, g; m; m = m.parentNode) {
            if (g = m.nextSibling) {
              g.nodeName == "BR" && (l = a = { node: g.parentNode, offset: Ge(g) + 1 });
              break;
            }
            let y = m.pmViewDesc;
            if (y && y.node && y.node.isBlock)
              break;
          }
      } else {
        let m = f.childNodes[p - 1];
        u = m && (m.nodeName == "BR" || m.contentEditable == "false");
      }
    }
    if (hn && d.focusNode && d.focusNode != a.node && d.focusNode.nodeType == 1) {
      let f = d.focusNode.childNodes[d.focusOffset];
      f && f.contentEditable == "false" && (i = !0);
    }
    if (!(i || u && ht) && pi(l.node, l.offset, d.anchorNode, d.anchorOffset) && pi(a.node, a.offset, d.focusNode, d.focusOffset))
      return;
    let h = !1;
    if ((c.extend || e == t) && !u) {
      c.collapse(l.node, l.offset);
      try {
        e != t && c.extend(a.node, a.offset), h = !0;
      } catch {
      }
    }
    if (!h) {
      if (e > t) {
        let p = l;
        l = a, a = p;
      }
      let f = document.createRange();
      f.setEnd(a.node, a.offset), f.setStart(l.node, l.offset), c.removeAllRanges(), c.addRange(f);
    }
  }
  ignoreMutation(e) {
    return !this.contentDOM && e.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(e, t) {
    for (let r = 0, i = 0; i < this.children.length; i++) {
      let o = this.children[i], s = r + o.size;
      if (r == s ? e <= s && t >= r : e < s && t > r) {
        let l = r + o.border, a = s - o.border;
        if (e >= l && t <= a) {
          this.dirty = e == r || t == s ? Qr : og, e == l && t == a && (o.contentLost || o.dom.parentNode != this.contentDOM) ? o.dirty = $n : o.markDirty(e - l, t - l);
          return;
        } else
          o.dirty = o.dom == o.contentDOM && o.dom.parentNode == this.contentDOM && !o.children.length ? Qr : $n;
      }
      r = s;
    }
    this.dirty = Qr;
  }
  markParentsDirty() {
    let e = 1;
    for (let t = this.parent; t; t = t.parent, e++) {
      let r = e == 1 ? Qr : og;
      t.dirty < r && (t.dirty = r);
    }
  }
  get domAtom() {
    return !1;
  }
  get ignoreForCoords() {
    return !1;
  }
  get ignoreForSelection() {
    return !1;
  }
  isText(e) {
    return !1;
  }
}
class t_ extends Hs {
  constructor(e, t, r, i) {
    let o, s = t.type.toDOM;
    if (typeof s == "function" && (s = s(r, () => {
      if (!o)
        return i;
      if (o.parent)
        return o.parent.posBeforeChild(o);
    })), !t.type.spec.raw) {
      if (s.nodeType != 1) {
        let l = document.createElement("span");
        l.appendChild(s), s = l;
      }
      s.contentEditable = "false", s.classList.add("ProseMirror-widget");
    }
    super(e, [], s, null), this.widget = t, this.widget = t, o = this;
  }
  matchesWidget(e) {
    return this.dirty == Gt && e.type.eq(this.widget.type);
  }
  parseRule() {
    return { ignore: !0 };
  }
  stopEvent(e) {
    let t = this.widget.spec.stopEvent;
    return t ? t(e) : !1;
  }
  ignoreMutation(e) {
    return e.type != "selection" || this.widget.spec.ignoreSelection;
  }
  destroy() {
    this.widget.type.destroy(this.dom), super.destroy();
  }
  get domAtom() {
    return !0;
  }
  get ignoreForSelection() {
    return !!this.widget.type.spec.relaxedSide;
  }
  get side() {
    return this.widget.type.side;
  }
}
class SD extends Hs {
  constructor(e, t, r, i) {
    super(e, [], t, null), this.textDOM = r, this.text = i;
  }
  get size() {
    return this.text.length;
  }
  localPosFromDOM(e, t) {
    return e != this.textDOM ? this.posAtStart + (t ? this.size : 0) : this.posAtStart + t;
  }
  domFromPos(e) {
    return { node: this.textDOM, offset: e };
  }
  ignoreMutation(e) {
    return e.type === "characterData" && e.target.nodeValue == e.oldValue;
  }
}
class mi extends Hs {
  constructor(e, t, r, i, o) {
    super(e, [], r, i), this.mark = t, this.spec = o;
  }
  static create(e, t, r, i) {
    let o = i.nodeViews[t.type.name], s = o && o(t, i, r);
    return (!s || !s.dom) && (s = sr.renderSpec(document, t.type.spec.toDOM(t, r), null, t.attrs)), new mi(e, t, s.dom, s.contentDOM || s.dom, s);
  }
  parseRule() {
    return this.dirty & $n || this.mark.type.spec.reparseInView ? null : { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };
  }
  matchesMark(e) {
    return this.dirty != $n && this.mark.eq(e);
  }
  markDirty(e, t) {
    if (super.markDirty(e, t), this.dirty != Gt) {
      let r = this.parent;
      for (; !r.node; )
        r = r.parent;
      r.dirty < this.dirty && (r.dirty = this.dirty), this.dirty = Gt;
    }
  }
  slice(e, t, r) {
    let i = mi.create(this.parent, this.mark, !0, r), o = this.children, s = this.size;
    t < s && (o = Du(o, t, s, r)), e > 0 && (o = Du(o, 0, e, r));
    for (let l = 0; l < o.length; l++)
      o[l].parent = i;
    return i.children = o, i;
  }
  ignoreMutation(e) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(e) : super.ignoreMutation(e);
  }
  destroy() {
    this.spec.destroy && this.spec.destroy(), super.destroy();
  }
}
class Tr extends Hs {
  constructor(e, t, r, i, o, s, l, a, c) {
    super(e, [], o, s), this.node = t, this.outerDeco = r, this.innerDeco = i, this.nodeDOM = l;
  }
  // 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(e, t, r, i, o, s) {
    let l = o.nodeViews[t.type.name], a, c = l && l(t, o, () => {
      if (!a)
        return s;
      if (a.parent)
        return a.parent.posBeforeChild(a);
    }, r, i), d = c && c.dom, u = c && c.contentDOM;
    if (t.isText) {
      if (!d)
        d = document.createTextNode(t.text);
      else if (d.nodeType != 3)
        throw new RangeError("Text must be rendered as a DOM text node");
    } else d || ({ dom: d, contentDOM: u } = sr.renderSpec(document, t.type.spec.toDOM(t), null, t.attrs));
    !u && !t.isText && d.nodeName != "BR" && (d.hasAttribute("contenteditable") || (d.contentEditable = "false"), t.type.spec.draggable && (d.draggable = !0));
    let h = d;
    return d = o_(d, r, t), c ? a = new ED(e, t, r, i, d, u || null, h, c, o, s + 1) : t.isText ? new gc(e, t, r, i, d, h, o) : new Tr(e, t, r, i, d, u || null, h, o, s + 1);
  }
  parseRule() {
    if (this.node.type.spec.reparseInView)
      return null;
    let e = { node: this.node.type.name, attrs: this.node.attrs };
    if (this.node.type.whitespace == "pre" && (e.preserveWhitespace = "full"), !this.contentDOM)
      e.getContent = () => this.node.content;
    else if (!this.contentLost)
      e.contentElement = this.contentDOM;
    else {
      for (let t = this.children.length - 1; t >= 0; t--) {
        let r = this.children[t];
        if (this.dom.contains(r.dom.parentNode)) {
          e.contentElement = r.dom.parentNode;
          break;
        }
      }
      e.contentElement || (e.getContent = () => A.empty);
    }
    return e;
  }
  matchesNode(e, t, r) {
    return this.dirty == Gt && e.eq(this.node) && ga(t, this.outerDeco) && r.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(e, t) {
    let r = this.node.inlineContent, i = t, o = e.composing ? this.localCompositionInfo(e, t) : null, s = o && o.pos > -1 ? o : null, l = o && o.pos < 0, a = new DD(this, s && s.node, e);
    MD(this.node, this.innerDeco, (c, d, u) => {
      c.spec.marks ? a.syncToMarks(c.spec.marks, r, e) : c.type.side >= 0 && !u && a.syncToMarks(d == this.node.childCount ? ue.none : this.node.child(d).marks, r, e), a.placeWidget(c, e, i);
    }, (c, d, u, h) => {
      a.syncToMarks(c.marks, r, e);
      let f;
      a.findNodeMatch(c, d, u, h) || l && e.state.selection.from > i && e.state.selection.to < i + c.nodeSize && (f = a.findIndexWithChild(o.node)) > -1 && a.updateNodeAt(c, d, u, f, e) || a.updateNextNode(c, d, u, e, h, i) || a.addNode(c, d, u, e, i), i += c.nodeSize;
    }), a.syncToMarks([], r, e), this.node.isTextblock && a.addTextblockHacks(), a.destroyRest(), (a.changed || this.dirty == Qr) && (s && this.protectLocalComposition(e, s), r_(this.contentDOM, this.children, e), so && OD(this.dom));
  }
  localCompositionInfo(e, t) {
    let { from: r, to: i } = e.state.selection;
    if (!(e.state.selection instanceof L) || r < t || i > t + this.node.content.size)
      return null;
    let o = e.input.compositionNode;
    if (!o || !this.dom.contains(o.parentNode))
      return null;
    if (this.node.inlineContent) {
      let s = o.nodeValue, l = FD(this.node.content, s, r - t, i - t);
      return l < 0 ? null : { node: o, pos: l, text: s };
    } else
      return { node: o, pos: -1, text: "" };
  }
  protectLocalComposition(e, { node: t, pos: r, text: i }) {
    if (this.getDesc(t))
      return;
    let o = t;
    for (; o.parentNode != this.contentDOM; o = o.parentNode) {
      for (; o.previousSibling; )
        o.parentNode.removeChild(o.previousSibling);
      for (; o.nextSibling; )
        o.parentNode.removeChild(o.nextSibling);
      o.pmViewDesc && (o.pmViewDesc = void 0);
    }
    let s = new SD(this, o, t, i);
    e.input.compositionNodes.push(s), this.children = Du(this.children, r, r + i.length, e, s);
  }
  // If this desc must be updated to match the given node decoration,
  // do so and return true.
  update(e, t, r, i) {
    return this.dirty == $n || !e.sameMarkup(this.node) ? !1 : (this.updateInner(e, t, r, i), !0);
  }
  updateInner(e, t, r, i) {
    this.updateOuterDeco(t), this.node = e, this.innerDeco = r, this.contentDOM && this.updateChildren(i, this.posAtStart), this.dirty = Gt;
  }
  updateOuterDeco(e) {
    if (ga(e, this.outerDeco))
      return;
    let t = this.nodeDOM.nodeType != 1, r = this.dom;
    this.dom = i_(this.dom, this.nodeDOM, xu(this.outerDeco, this.node, t), xu(e, this.node, t)), this.dom != r && (r.pmViewDesc = void 0, this.dom.pmViewDesc = this), this.outerDeco = e;
  }
  // Mark this node as being the selected node.
  selectNode() {
    this.nodeDOM.nodeType == 1 && this.nodeDOM.classList.add("ProseMirror-selectednode"), (this.contentDOM || !this.node.type.spec.draggable) && (this.dom.draggable = !0);
  }
  // Remove selected node marking from this node.
  deselectNode() {
    this.nodeDOM.nodeType == 1 && (this.nodeDOM.classList.remove("ProseMirror-selectednode"), (this.contentDOM || !this.node.type.spec.draggable) && this.dom.removeAttribute("draggable"));
  }
  get domAtom() {
    return this.node.isAtom;
  }
}
function sg(n, e, t, r, i) {
  o_(r, e, n);
  let o = new Tr(void 0, n, e, t, r, r, r, i, 0);
  return o.contentDOM && o.updateChildren(i, 0), o;
}
class gc extends Tr {
  constructor(e, t, r, i, o, s, l) {
    super(e, t, r, i, o, null, s, l, 0);
  }
  parseRule() {
    let e = this.nodeDOM.parentNode;
    for (; e && e != this.dom && !e.pmIsDeco; )
      e = e.parentNode;
    return { skip: e || !0 };
  }
  update(e, t, r, i) {
    return this.dirty == $n || this.dirty != Gt && !this.inParent() || !e.sameMarkup(this.node) ? !1 : (this.updateOuterDeco(t), (this.dirty != Gt || e.text != this.node.text) && e.text != this.nodeDOM.nodeValue && (this.nodeDOM.nodeValue = e.text, i.trackWrites == this.nodeDOM && (i.trackWrites = null)), this.node = e, this.dirty = Gt, !0);
  }
  inParent() {
    let e = this.parent.contentDOM;
    for (let t = this.nodeDOM; t; t = t.parentNode)
      if (t == e)
        return !0;
    return !1;
  }
  domFromPos(e) {
    return { node: this.nodeDOM, offset: e };
  }
  localPosFromDOM(e, t, r) {
    return e == this.nodeDOM ? this.posAtStart + Math.min(t, this.node.text.length) : super.localPosFromDOM(e, t, r);
  }
  ignoreMutation(e) {
    return e.type != "characterData" && e.type != "selection";
  }
  slice(e, t, r) {
    let i = this.node.cut(e, t), o = document.createTextNode(i.text);
    return new gc(this.parent, i, this.outerDeco, this.innerDeco, o, o, r);
  }
  markDirty(e, t) {
    super.markDirty(e, t), this.dom != this.nodeDOM && (e == 0 || t == this.nodeDOM.nodeValue.length) && (this.dirty = $n);
  }
  get domAtom() {
    return !1;
  }
  isText(e) {
    return this.node.text == e;
  }
}
class n_ extends Hs {
  parseRule() {
    return { ignore: !0 };
  }
  matchesHack(e) {
    return this.dirty == Gt && this.dom.nodeName == e;
  }
  get domAtom() {
    return !0;
  }
  get ignoreForCoords() {
    return this.dom.nodeName == "IMG";
  }
}
class ED extends Tr {
  constructor(e, t, r, i, o, s, l, a, c, d) {
    super(e, t, r, i, o, s, l, c, d), this.spec = a;
  }
  // 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(e, t, r, i) {
    if (this.dirty == $n)
      return !1;
    if (this.spec.update && (this.node.type == e.type || this.spec.multiType)) {
      let o = this.spec.update(e, t, r);
      return o && this.updateInner(e, t, r, i), o;
    } else return !this.contentDOM && !e.isLeaf ? !1 : super.update(e, t, r, i);
  }
  selectNode() {
    this.spec.selectNode ? this.spec.selectNode() : super.selectNode();
  }
  deselectNode() {
    this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();
  }
  setSelection(e, t, r, i) {
    this.spec.setSelection ? this.spec.setSelection(e, t, r.root) : super.setSelection(e, t, r, i);
  }
  destroy() {
    this.spec.destroy && this.spec.destroy(), super.destroy();
  }
  stopEvent(e) {
    return this.spec.stopEvent ? this.spec.stopEvent(e) : !1;
  }
  ignoreMutation(e) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(e) : super.ignoreMutation(e);
  }
}
function r_(n, e, t) {
  let r = n.firstChild, i = !1;
  for (let o = 0; o < e.length; o++) {
    let s = e[o], l = s.dom;
    if (l.parentNode == n) {
      for (; l != r; )
        r = lg(r), i = !0;
      r = r.nextSibling;
    } else
      i = !0, n.insertBefore(l, r);
    if (s instanceof mi) {
      let a = r ? r.previousSibling : n.lastChild;
      r_(s.contentDOM, s.children, t), r = a ? a.nextSibling : n.firstChild;
    }
  }
  for (; r; )
    r = lg(r), i = !0;
  i && t.trackWrites == n && (t.trackWrites = null);
}
const Xo = function(n) {
  n && (this.nodeName = n);
};
Xo.prototype = /* @__PURE__ */ Object.create(null);
const ei = [new Xo()];
function xu(n, e, t) {
  if (n.length == 0)
    return ei;
  let r = t ? ei[0] : new Xo(), i = [r];
  for (let o = 0; o < n.length; o++) {
    let s = n[o].type.attrs;
    if (s) {
      s.nodeName && i.push(r = new Xo(s.nodeName));
      for (let l in s) {
        let a = s[l];
        a != null && (t && i.length == 1 && i.push(r = new Xo(e.isInline ? "span" : "div")), l == "class" ? r.class = (r.class ? r.class + " " : "") + a : l == "style" ? r.style = (r.style ? r.style + ";" : "") + a : l != "nodeName" && (r[l] = a));
      }
    }
  }
  return i;
}
function i_(n, e, t, r) {
  if (t == ei && r == ei)
    return e;
  let i = e;
  for (let o = 0; o < r.length; o++) {
    let s = r[o], l = t[o];
    if (o) {
      let a;
      l && l.nodeName == s.nodeName && i != n && (a = i.parentNode) && a.nodeName.toLowerCase() == s.nodeName || (a = document.createElement(s.nodeName), a.pmIsDeco = !0, a.appendChild(i), l = ei[0]), i = a;
    }
    xD(i, l || ei[0], s);
  }
  return i;
}
function xD(n, e, t) {
  for (let r in e)
    r != "class" && r != "style" && r != "nodeName" && !(r in t) && n.removeAttribute(r);
  for (let r in t)
    r != "class" && r != "style" && r != "nodeName" && t[r] != e[r] && n.setAttribute(r, t[r]);
  if (e.class != t.class) {
    let r = e.class ? e.class.split(" ").filter(Boolean) : [], i = t.class ? t.class.split(" ").filter(Boolean) : [];
    for (let o = 0; o < r.length; o++)
      i.indexOf(r[o]) == -1 && n.classList.remove(r[o]);
    for (let o = 0; o < i.length; o++)
      r.indexOf(i[o]) == -1 && n.classList.add(i[o]);
    n.classList.length == 0 && n.removeAttribute("class");
  }
  if (e.style != t.style) {
    if (e.style) {
      let r = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, i;
      for (; i = r.exec(e.style); )
        n.style.removeProperty(i[1]);
    }
    t.style && (n.style.cssText += t.style);
  }
}
function o_(n, e, t) {
  return i_(n, n, ei, xu(e, t, n.nodeType != 1));
}
function ga(n, e) {
  if (n.length != e.length)
    return !1;
  for (let t = 0; t < n.length; t++)
    if (!n[t].type.eq(e[t].type))
      return !1;
  return !0;
}
function lg(n) {
  let e = n.nextSibling;
  return n.parentNode.removeChild(n), e;
}
class DD {
  constructor(e, t, r) {
    this.lock = t, this.view = r, this.index = 0, this.stack = [], this.changed = !1, this.top = e, this.preMatch = AD(e.node.content, e);
  }
  // Destroy and remove the children between the given indices in
  // `this.top`.
  destroyBetween(e, t) {
    if (e != t) {
      for (let r = e; r < t; r++)
        this.top.children[r].destroy();
      this.top.children.splice(e, t - e), this.changed = !0;
    }
  }
  // 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(e, t, r) {
    let i = 0, o = this.stack.length >> 1, s = Math.min(o, e.length);
    for (; i < s && (i == o - 1 ? this.top : this.stack[i + 1 << 1]).matchesMark(e[i]) && e[i].type.spec.spanning !== !1; )
      i++;
    for (; i < o; )
      this.destroyRest(), this.top.dirty = Gt, this.index = this.stack.pop(), this.top = this.stack.pop(), o--;
    for (; o < e.length; ) {
      this.stack.push(this.top, this.index + 1);
      let l = -1;
      for (let a = this.index; a < Math.min(this.index + 3, this.top.children.length); a++) {
        let c = this.top.children[a];
        if (c.matchesMark(e[o]) && !this.isLocked(c.dom)) {
          l = a;
          break;
        }
      }
      if (l > -1)
        l > this.index && (this.changed = !0, this.destroyBetween(this.index, l)), this.top = this.top.children[this.index];
      else {
        let a = mi.create(this.top, e[o], t, r);
        this.top.children.splice(this.index, 0, a), this.top = a, this.changed = !0;
      }
      this.index = 0, o++;
    }
  }
  // Try to find a node desc matching the given data. Skip over it and
  // return true when successful.
  findNodeMatch(e, t, r, i) {
    let o = -1, s;
    if (i >= this.preMatch.index && (s = this.preMatch.matches[i - this.preMatch.index]).parent == this.top && s.matchesNode(e, t, r))
      o = this.top.children.indexOf(s, this.index);
    else
      for (let l = this.index, a = Math.min(this.top.children.length, l + 5); l < a; l++) {
        let c = this.top.children[l];
        if (c.matchesNode(e, t, r) && !this.preMatch.matched.has(c)) {
          o = l;
          break;
        }
      }
    return o < 0 ? !1 : (this.destroyBetween(this.index, o), this.index++, !0);
  }
  updateNodeAt(e, t, r, i, o) {
    let s = this.top.children[i];
    return s.dirty == $n && s.dom == s.contentDOM && (s.dirty = Qr), s.update(e, t, r, o) ? (this.destroyBetween(this.index, i), this.index++, !0) : !1;
  }
  findIndexWithChild(e) {
    for (; ; ) {
      let t = e.parentNode;
      if (!t)
        return -1;
      if (t == this.top.contentDOM) {
        let r = e.pmViewDesc;
        if (r) {
          for (let i = this.index; i < this.top.children.length; i++)
            if (this.top.children[i] == r)
              return i;
        }
        return -1;
      }
      e = t;
    }
  }
  // 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(e, t, r, i, o, s) {
    for (let l = this.index; l < this.top.children.length; l++) {
      let a = this.top.children[l];
      if (a instanceof Tr) {
        let c = this.preMatch.matched.get(a);
        if (c != null && c != o)
          return !1;
        let d = a.dom, u, h = this.isLocked(d) && !(e.isText && a.node && a.node.isText && a.nodeDOM.nodeValue == e.text && a.dirty != $n && ga(t, a.outerDeco));
        if (!h && a.update(e, t, r, i))
          return this.destroyBetween(this.index, l), a.dom != d && (this.changed = !0), this.index++, !0;
        if (!h && (u = this.recreateWrapper(a, e, t, r, i, s)))
          return this.destroyBetween(this.index, l), this.top.children[this.index] = u, u.contentDOM && (u.dirty = Qr, u.updateChildren(i, s + 1), u.dirty = Gt), this.changed = !0, this.index++, !0;
        break;
      }
    }
    return !1;
  }
  // When a node with content is replaced by a different node with
  // identical content, move over its children.
  recreateWrapper(e, t, r, i, o, s) {
    if (e.dirty || t.isAtom || !e.children.length || !e.node.content.eq(t.content) || !ga(r, e.outerDeco) || !i.eq(e.innerDeco))
      return null;
    let l = Tr.create(this.top, t, r, i, o, s);
    if (l.contentDOM) {
      l.children = e.children, e.children = [];
      for (let a of l.children)
        a.parent = l;
    }
    return e.destroy(), l;
  }
  // Insert the node as a newly created node desc.
  addNode(e, t, r, i, o) {
    let s = Tr.create(this.top, e, t, r, i, o);
    s.contentDOM && s.updateChildren(i, o + 1), this.top.children.splice(this.index++, 0, s), this.changed = !0;
  }
  placeWidget(e, t, r) {
    let i = this.index < this.top.children.length ? this.top.children[this.index] : null;
    if (i && i.matchesWidget(e) && (e == i.widget || !i.widget.type.toDOM.parentNode))
      this.index++;
    else {
      let o = new t_(this.top, e, t, r);
      this.top.children.splice(this.index++, 0, o), this.changed = !0;
    }
  }
  // Make sure a textblock looks and behaves correctly in
  // contentEditable.
  addTextblockHacks() {
    let e = this.top.children[this.index - 1], t = this.top;
    for (; e instanceof mi; )
      t = e, e = t.children[t.children.length - 1];
    (!e || // Empty textblock
    !(e instanceof gc) || /\n$/.test(e.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(e.node.text)) && ((ht || nt) && e && e.dom.contentEditable == "false" && this.addHackNode("IMG", t), this.addHackNode("BR", this.top));
  }
  addHackNode(e, t) {
    if (t == this.top && this.index < t.children.length && t.children[this.index].matchesHack(e))
      this.index++;
    else {
      let r = document.createElement(e);
      e == "IMG" && (r.className = "ProseMirror-separator", r.alt = ""), e == "BR" && (r.className = "ProseMirror-trailingBreak");
      let i = new n_(this.top, [], r, null);
      t != this.top ? t.children.push(i) : t.children.splice(this.index++, 0, i), this.changed = !0;
    }
  }
  isLocked(e) {
    return this.lock && (e == this.lock || e.nodeType == 1 && e.contains(this.lock.parentNode));
  }
}
function AD(n, e) {
  let t = e, r = t.children.length, i = n.childCount, o = /* @__PURE__ */ new Map(), s = [];
  e: for (; i > 0; ) {
    let l;
    for (; ; )
      if (r) {
        let c = t.children[r - 1];
        if (c instanceof mi)
          t = c, r = c.children.length;
        else {
          l = c, r--;
          break;
        }
      } else {
        if (t == e)
          break e;
        r = t.parent.children.indexOf(t), t = t.parent;
      }
    let a = l.node;
    if (a) {
      if (a != n.child(i - 1))
        break;
      --i, o.set(l, i), s.push(l);
    }
  }
  return { index: i, matched: o, matches: s.reverse() };
}
function TD(n, e) {
  return n.type.side - e.type.side;
}
function MD(n, e, t, r) {
  let i = e.locals(n), o = 0;
  if (i.length == 0) {
    for (let c = 0; c < n.childCount; c++) {
      let d = n.child(c);
      r(d, i, e.forChild(o, d), c), o += d.nodeSize;
    }
    return;
  }
  let s = 0, l = [], a = null;
  for (let c = 0; ; ) {
    let d, u;
    for (; s < i.length && i[s].to == o; ) {
      let g = i[s++];
      g.widget && (d ? (u || (u = [d])).push(g) : d = g);
    }
    if (d)
      if (u) {
        u.sort(TD);
        for (let g = 0; g < u.length; g++)
          t(u[g], c, !!a);
      } else
        t(d, c, !!a);
    let h, f;
    if (a)
      f = -1, h = a, a = null;
    else if (c < n.childCount)
      f = c, h = n.child(c++);
    else
      break;
    for (let g = 0; g < l.length; g++)
      l[g].to <= o && l.splice(g--, 1);
    for (; s < i.length && i[s].from <= o && i[s].to > o; )
      l.push(i[s++]);
    let p = o + h.nodeSize;
    if (h.isText) {
      let g = p;
      s < i.length && i[s].from < g && (g = i[s].from);
      for (let y = 0; y < l.length; y++)
        l[y].to < g && (g = l[y].to);
      g < p && (a = h.cut(g - o), h = h.cut(0, g - o), p = g, f = -1);
    } else
      for (; s < i.length && i[s].to < p; )
        s++;
    let m = h.isInline && !h.isLeaf ? l.filter((g) => !g.inline) : l.slice();
    r(h, m, e.forChild(o, h), f), o = p;
  }
}
function OD(n) {
  if (n.nodeName == "UL" || n.nodeName == "OL") {
    let e = n.style.cssText;
    n.style.cssText = e + "; list-style: square !important", window.getComputedStyle(n).listStyle, n.style.cssText = e;
  }
}
function FD(n, e, t, r) {
  for (let i = 0, o = 0; i < n.childCount && o <= r; ) {
    let s = n.child(i++), l = o;
    if (o += s.nodeSize, !s.isText)
      continue;
    let a = s.text;
    for (; i < n.childCount; ) {
      let c = n.child(i++);
      if (o += c.nodeSize, !c.isText)
        break;
      a += c.text;
    }
    if (o >= t) {
      if (o >= r && a.slice(r - e.length - l, r - l) == e)
        return r - e.length;
      let c = l < r ? a.lastIndexOf(e, r - l - 1) : -1;
      if (c >= 0 && c + e.length + l >= t)
        return l + c;
      if (t == r && a.length >= r + e.length - l && a.slice(r - l, r - l + e.length) == e)
        return r;
    }
  }
  return -1;
}
function Du(n, e, t, r, i) {
  let o = [];
  for (let s = 0, l = 0; s < n.length; s++) {
    let a = n[s], c = l, d = l += a.size;
    c >= t || d <= e ? o.push(a) : (c < e && o.push(a.slice(0, e - c, r)), i && (o.push(i), i = void 0), d > t && o.push(a.slice(t - c, a.size, r)));
  }
  return o;
}
function $h(n, e = null) {
  let t = n.domSelectionRange(), r = n.state.doc;
  if (!t.focusNode)
    return null;
  let i = n.docView.nearestDesc(t.focusNode), o = i && i.size == 0, s = n.docView.posFromDOM(t.focusNode, t.focusOffset, 1);
  if (s < 0)
    return null;
  let l = r.resolve(s), a, c;
  if (mc(t)) {
    for (a = s; i && !i.node; )
      i = i.parent;
    let u = i.node;
    if (i && u.isAtom && P.isSelectable(u) && i.parent && !(u.isInline && iD(t.focusNode, t.focusOffset, i.dom))) {
      let h = i.posBefore;
      c = new P(s == h ? l : r.resolve(h));
    }
  } else {
    if (t instanceof n.dom.ownerDocument.defaultView.Selection && t.rangeCount > 1) {
      let u = s, h = s;
      for (let f = 0; f < t.rangeCount; f++) {
        let p = t.getRangeAt(f);
        u = Math.min(u, n.docView.posFromDOM(p.startContainer, p.startOffset, 1)), h = Math.max(h, n.docView.posFromDOM(p.endContainer, p.endOffset, -1));
      }
      if (u < 0)
        return null;
      [a, s] = h == n.state.selection.anchor ? [h, u] : [u, h], l = r.resolve(s);
    } else
      a = n.docView.posFromDOM(t.anchorNode, t.anchorOffset, 1);
    if (a < 0)
      return null;
  }
  let d = r.resolve(a);
  if (!c) {
    let u = e == "pointer" || n.state.selection.head < l.pos && !o ? 1 : -1;
    c = Ih(n, d, l, u);
  }
  return c;
}
function s_(n) {
  return n.editable ? n.hasFocus() : a_(n) && document.activeElement && document.activeElement.contains(n.dom);
}
function tr(n, e = !1) {
  let t = n.state.selection;
  if (l_(n, t), !!s_(n)) {
    if (!e && n.input.mouseDown && n.input.mouseDown.allowDefault && nt) {
      let r = n.domSelectionRange(), i = n.domObserver.currentSelection;
      if (r.anchorNode && i.anchorNode && pi(r.anchorNode, r.anchorOffset, i.anchorNode, i.anchorOffset)) {
        n.input.mouseDown.delayedSelectionSync = !0, n.domObserver.setCurSelection();
        return;
      }
    }
    if (n.domObserver.disconnectSelection(), n.cursorWrapper)
      $D(n);
    else {
      let { anchor: r, head: i } = t, o, s;
      ag && !(t instanceof L) && (t.$from.parent.inlineContent || (o = cg(n, t.from)), !t.empty && !t.$from.parent.inlineContent && (s = cg(n, t.to))), n.docView.setSelection(r, i, n, e), ag && (o && dg(o), s && dg(s)), t.visible ? n.dom.classList.remove("ProseMirror-hideselection") : (n.dom.classList.add("ProseMirror-hideselection"), "onselectionchange" in document && ND(n));
    }
    n.domObserver.setCurSelection(), n.domObserver.connectSelection();
  }
}
const ag = ht || nt && Ky < 63;
function cg(n, e) {
  let { node: t, offset: r } = n.docView.domFromPos(e, 0), i = r < t.childNodes.length ? t.childNodes[r] : null, o = r ? t.childNodes[r - 1] : null;
  if (ht && i && i.contentEditable == "false")
    return Cd(i);
  if ((!i || i.contentEditable == "false") && (!o || o.contentEditable == "false")) {
    if (i)
      return Cd(i);
    if (o)
      return Cd(o);
  }
}
function Cd(n) {
  return n.contentEditable = "true", ht && n.draggable && (n.draggable = !1, n.wasDraggable = !0), n;
}
function dg(n) {
  n.contentEditable = "false", n.wasDraggable && (n.draggable = !0, n.wasDraggable = null);
}
function ND(n) {
  let e = n.dom.ownerDocument;
  e.removeEventListener("selectionchange", n.input.hideSelectionGuard);
  let t = n.domSelectionRange(), r = t.anchorNode, i = t.anchorOffset;
  e.addEventListener("selectionchange", n.input.hideSelectionGuard = () => {
    (t.anchorNode != r || t.anchorOffset != i) && (e.removeEventListener("selectionchange", n.input.hideSelectionGuard), setTimeout(() => {
      (!s_(n) || n.state.selection.visible) && n.dom.classList.remove("ProseMirror-hideselection");
    }, 20));
  });
}
function $D(n) {
  let e = n.domSelection(), t = document.createRange();
  if (!e)
    return;
  let r = n.cursorWrapper.dom, i = r.nodeName == "IMG";
  i ? t.setStart(r.parentNode, Ge(r) + 1) : t.setStart(r, 0), t.collapse(!0), e.removeAllRanges(), e.addRange(t), !i && !n.state.selection.visible && kt && Ar <= 11 && (r.disabled = !0, r.disabled = !1);
}
function l_(n, e) {
  if (e instanceof P) {
    let t = n.docView.descAt(e.from);
    t != n.lastSelectedViewDesc && (ug(n), t && t.selectNode(), n.lastSelectedViewDesc = t);
  } else
    ug(n);
}
function ug(n) {
  n.lastSelectedViewDesc && (n.lastSelectedViewDesc.parent && n.lastSelectedViewDesc.deselectNode(), n.lastSelectedViewDesc = void 0);
}
function Ih(n, e, t, r) {
  return n.someProp("createSelectionBetween", (i) => i(n, e, t)) || L.between(e, t, r);
}
function hg(n) {
  return n.editable && !n.hasFocus() ? !1 : a_(n);
}
function a_(n) {
  let e = n.domSelectionRange();
  if (!e.anchorNode)
    return !1;
  try {
    return n.dom.contains(e.anchorNode.nodeType == 3 ? e.anchorNode.parentNode : e.anchorNode) && (n.editable || n.dom.contains(e.focusNode.nodeType == 3 ? e.focusNode.parentNode : e.focusNode));
  } catch {
    return !1;
  }
}
function ID(n) {
  let e = n.docView.domFromPos(n.state.selection.anchor, 0), t = n.domSelectionRange();
  return pi(e.node, e.offset, t.anchorNode, t.anchorOffset);
}
function Au(n, e) {
  let { $anchor: t, $head: r } = n.selection, i = e > 0 ? t.max(r) : t.min(r), o = i.parent.inlineContent ? i.depth ? n.doc.resolve(e > 0 ? i.after() : i.before()) : null : i;
  return o && V.findFrom(o, e);
}
function gr(n, e) {
  return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()), !0;
}
function fg(n, e, t) {
  let r = n.state.selection;
  if (r instanceof L)
    if (t.indexOf("s") > -1) {
      let { $head: i } = r, o = i.textOffset ? null : e < 0 ? i.nodeBefore : i.nodeAfter;
      if (!o || o.isText || !o.isLeaf)
        return !1;
      let s = n.state.doc.resolve(i.pos + o.nodeSize * (e < 0 ? -1 : 1));
      return gr(n, new L(r.$anchor, s));
    } else if (r.empty) {
      if (n.endOfTextblock(e > 0 ? "forward" : "backward")) {
        let i = Au(n.state, e);
        return i && i instanceof P ? gr(n, i) : !1;
      } else if (!(zt && t.indexOf("m") > -1)) {
        let i = r.$head, o = i.textOffset ? null : e < 0 ? i.nodeBefore : i.nodeAfter, s;
        if (!o || o.isText)
          return !1;
        let l = e < 0 ? i.pos - o.nodeSize : i.pos;
        return o.isAtom || (s = n.docView.descAt(l)) && !s.contentDOM ? P.isSelectable(o) ? gr(n, new P(e < 0 ? n.state.doc.resolve(i.pos - o.nodeSize) : i)) : zs ? gr(n, new L(n.state.doc.resolve(e < 0 ? l : l + o.nodeSize))) : !1 : !1;
      }
    } else return !1;
  else {
    if (r instanceof P && r.node.isInline)
      return gr(n, new L(e > 0 ? r.$to : r.$from));
    {
      let i = Au(n.state, e);
      return i ? gr(n, i) : !1;
    }
  }
}
function ba(n) {
  return n.nodeType == 3 ? n.nodeValue.length : n.childNodes.length;
}
function Zo(n, e) {
  let t = n.pmViewDesc;
  return t && t.size == 0 && (e < 0 || n.nextSibling || n.nodeName != "BR");
}
function zi(n, e) {
  return e < 0 ? LD(n) : RD(n);
}
function LD(n) {
  let e = n.domSelectionRange(), t = e.focusNode, r = e.focusOffset;
  if (!t)
    return;
  let i, o, s = !1;
  for (hn && t.nodeType == 1 && r < ba(t) && Zo(t.childNodes[r], -1) && (s = !0); ; )
    if (r > 0) {
      if (t.nodeType != 1)
        break;
      {
        let l = t.childNodes[r - 1];
        if (Zo(l, -1))
          i = t, o = --r;
        else if (l.nodeType == 3)
          t = l, r = t.nodeValue.length;
        else
          break;
      }
    } else {
      if (c_(t))
        break;
      {
        let l = t.previousSibling;
        for (; l && Zo(l, -1); )
          i = t.parentNode, o = Ge(l), l = l.previousSibling;
        if (l)
          t = l, r = ba(t);
        else {
          if (t = t.parentNode, t == n.dom)
            break;
          r = 0;
        }
      }
    }
  s ? Tu(n, t, r) : i && Tu(n, i, o);
}
function RD(n) {
  let e = n.domSelectionRange(), t = e.focusNode, r = e.focusOffset;
  if (!t)
    return;
  let i = ba(t), o, s;
  for (; ; )
    if (r < i) {
      if (t.nodeType != 1)
        break;
      let l = t.childNodes[r];
      if (Zo(l, 1))
        o = t, s = ++r;
      else
        break;
    } else {
      if (c_(t))
        break;
      {
        let l = t.nextSibling;
        for (; l && Zo(l, 1); )
          o = l.parentNode, s = Ge(l) + 1, l = l.nextSibling;
        if (l)
          t = l, r = 0, i = ba(t);
        else {
          if (t = t.parentNode, t == n.dom)
            break;
          r = i = 0;
        }
      }
    }
  o && Tu(n, o, s);
}
function c_(n) {
  let e = n.pmViewDesc;
  return e && e.node && e.node.isBlock;
}
function BD(n, e) {
  for (; n && e == n.childNodes.length && !Ps(n); )
    e = Ge(n) + 1, n = n.parentNode;
  for (; n && e < n.childNodes.length; ) {
    let t = n.childNodes[e];
    if (t.nodeType == 3)
      return t;
    if (t.nodeType == 1 && t.contentEditable == "false")
      break;
    n = t, e = 0;
  }
}
function PD(n, e) {
  for (; n && !e && !Ps(n); )
    e = Ge(n), n = n.parentNode;
  for (; n && e; ) {
    let t = n.childNodes[e - 1];
    if (t.nodeType == 3)
      return t;
    if (t.nodeType == 1 && t.contentEditable == "false")
      break;
    n = t, e = n.childNodes.length;
  }
}
function Tu(n, e, t) {
  if (e.nodeType != 3) {
    let o, s;
    (s = BD(e, t)) ? (e = s, t = 0) : (o = PD(e, t)) && (e = o, t = o.nodeValue.length);
  }
  let r = n.domSelection();
  if (!r)
    return;
  if (mc(r)) {
    let o = document.createRange();
    o.setEnd(e, t), o.setStart(e, t), r.removeAllRanges(), r.addRange(o);
  } else r.extend && r.extend(e, t);
  n.domObserver.setCurSelection();
  let { state: i } = n;
  setTimeout(() => {
    n.state == i && tr(n);
  }, 50);
}
function pg(n, e) {
  let t = n.state.doc.resolve(e);
  if (!(nt || lD) && t.parent.inlineContent) {
    let i = n.coordsAtPos(e);
    if (e > t.start()) {
      let o = n.coordsAtPos(e - 1), s = (o.top + o.bottom) / 2;
      if (s > i.top && s < i.bottom && Math.abs(o.left - i.left) > 1)
        return o.left < i.left ? "ltr" : "rtl";
    }
    if (e < t.end()) {
      let o = n.coordsAtPos(e + 1), s = (o.top + o.bottom) / 2;
      if (s > i.top && s < i.bottom && Math.abs(o.left - i.left) > 1)
        return o.left > i.left ? "ltr" : "rtl";
    }
  }
  return getComputedStyle(n.dom).direction == "rtl" ? "rtl" : "ltr";
}
function mg(n, e, t) {
  let r = n.state.selection;
  if (r instanceof L && !r.empty || t.indexOf("s") > -1 || zt && t.indexOf("m") > -1)
    return !1;
  let { $from: i, $to: o } = r;
  if (!i.parent.inlineContent || n.endOfTextblock(e < 0 ? "up" : "down")) {
    let s = Au(n.state, e);
    if (s && s instanceof P)
      return gr(n, s);
  }
  if (!i.parent.inlineContent) {
    let s = e < 0 ? i : o, l = r instanceof wt ? V.near(s, e) : V.findFrom(s, e);
    return l ? gr(n, l) : !1;
  }
  return !1;
}
function gg(n, e) {
  if (!(n.state.selection instanceof L))
    return !0;
  let { $head: t, $anchor: r, empty: i } = n.state.selection;
  if (!t.sameParent(r))
    return !0;
  if (!i)
    return !1;
  if (n.endOfTextblock(e > 0 ? "forward" : "backward"))
    return !0;
  let o = !t.textOffset && (e < 0 ? t.nodeBefore : t.nodeAfter);
  if (o && !o.isText) {
    let s = n.state.tr;
    return e < 0 ? s.delete(t.pos - o.nodeSize, t.pos) : s.delete(t.pos, t.pos + o.nodeSize), n.dispatch(s), !0;
  }
  return !1;
}
function bg(n, e, t) {
  n.domObserver.stop(), e.contentEditable = t, n.domObserver.start();
}
function zD(n) {
  if (!ht || n.state.selection.$head.parentOffset > 0)
    return !1;
  let { focusNode: e, focusOffset: t } = n.domSelectionRange();
  if (e && e.nodeType == 1 && t == 0 && e.firstChild && e.firstChild.contentEditable == "false") {
    let r = e.firstChild;
    bg(n, r, "true"), setTimeout(() => bg(n, r, "false"), 20);
  }
  return !1;
}
function HD(n) {
  let e = "";
  return n.ctrlKey && (e += "c"), n.metaKey && (e += "m"), n.altKey && (e += "a"), n.shiftKey && (e += "s"), e;
}
function VD(n, e) {
  let t = e.keyCode, r = HD(e);
  if (t == 8 || zt && t == 72 && r == "c")
    return gg(n, -1) || zi(n, -1);
  if (t == 46 && !e.shiftKey || zt && t == 68 && r == "c")
    return gg(n, 1) || zi(n, 1);
  if (t == 13 || t == 27)
    return !0;
  if (t == 37 || zt && t == 66 && r == "c") {
    let i = t == 37 ? pg(n, n.state.selection.from) == "ltr" ? -1 : 1 : -1;
    return fg(n, i, r) || zi(n, i);
  } else if (t == 39 || zt && t == 70 && r == "c") {
    let i = t == 39 ? pg(n, n.state.selection.from) == "ltr" ? 1 : -1 : 1;
    return fg(n, i, r) || zi(n, i);
  } else {
    if (t == 38 || zt && t == 80 && r == "c")
      return mg(n, -1, r) || zi(n, -1);
    if (t == 40 || zt && t == 78 && r == "c")
      return zD(n) || mg(n, 1, r) || zi(n, 1);
    if (r == (zt ? "m" : "c") && (t == 66 || t == 73 || t == 89 || t == 90))
      return !0;
  }
  return !1;
}
function Lh(n, e) {
  n.someProp("transformCopied", (f) => {
    e = f(e, n);
  });
  let t = [], { content: r, openStart: i, openEnd: o } = e;
  for (; i > 1 && o > 1 && r.childCount == 1 && r.firstChild.childCount == 1; ) {
    i--, o--;
    let f = r.firstChild;
    t.push(f.type.name, f.attrs != f.type.defaultAttrs ? f.attrs : null), r = f.content;
  }
  let s = n.someProp("clipboardSerializer") || sr.fromSchema(n.state.schema), l = m_(), a = l.createElement("div");
  a.appendChild(s.serializeFragment(r, { document: l }));
  let c = a.firstChild, d, u = 0;
  for (; c && c.nodeType == 1 && (d = p_[c.nodeName.toLowerCase()]); ) {
    for (let f = d.length - 1; f >= 0; f--) {
      let p = l.createElement(d[f]);
      for (; a.firstChild; )
        p.appendChild(a.firstChild);
      a.appendChild(p), u++;
    }
    c = a.firstChild;
  }
  c && c.nodeType == 1 && c.setAttribute("data-pm-slice", `${i} ${o}${u ? ` -${u}` : ""} ${JSON.stringify(t)}`);
  let h = n.someProp("clipboardTextSerializer", (f) => f(e, n)) || e.content.textBetween(0, e.content.size, `

`);
  return { dom: a, text: h, slice: e };
}
function d_(n, e, t, r, i) {
  let o = i.parent.type.spec.code, s, l;
  if (!t && !e)
    return null;
  let a = e && (r || o || !t);
  if (a) {
    if (n.someProp("transformPastedText", (h) => {
      e = h(e, o || r, n);
    }), o)
      return e ? new O(A.from(n.state.schema.text(e.replace(/\r\n?/g, `
`))), 0, 0) : O.empty;
    let u = n.someProp("clipboardTextParser", (h) => h(e, i, r, n));
    if (u)
      l = u;
    else {
      let h = i.marks(), { schema: f } = n.state, p = sr.fromSchema(f);
      s = document.createElement("div"), e.split(/(?:\r\n?|\n)+/).forEach((m) => {
        let g = s.appendChild(document.createElement("p"));
        m && g.appendChild(p.serializeNode(f.text(m, h)));
      });
    }
  } else
    n.someProp("transformPastedHTML", (u) => {
      t = u(t, n);
    }), s = WD(t), zs && GD(s);
  let c = s && s.querySelector("[data-pm-slice]"), d = c && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice") || "");
  if (d && d[3])
    for (let u = +d[3]; u > 0; u--) {
      let h = s.firstChild;
      for (; h && h.nodeType != 1; )
        h = h.nextSibling;
      if (!h)
        break;
      s = h;
    }
  if (l || (l = (n.someProp("clipboardParser") || n.someProp("domParser") || On.fromSchema(n.state.schema)).parseSlice(s, {
    preserveWhitespace: !!(a || d),
    context: i,
    ruleFromNode(h) {
      return h.nodeName == "BR" && !h.nextSibling && h.parentNode && !UD.test(h.parentNode.nodeName) ? { ignore: !0 } : null;
    }
  })), d)
    l = KD(yg(l, +d[1], +d[2]), d[4]);
  else if (l = O.maxOpen(qD(l.content, i), !0), l.openStart || l.openEnd) {
    let u = 0, h = 0;
    for (let f = l.content.firstChild; u < l.openStart && !f.type.spec.isolating; u++, f = f.firstChild)
      ;
    for (let f = l.content.lastChild; h < l.openEnd && !f.type.spec.isolating; h++, f = f.lastChild)
      ;
    l = yg(l, u, h);
  }
  return n.someProp("transformPasted", (u) => {
    l = u(l, n);
  }), l;
}
const UD = /^(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 qD(n, e) {
  if (n.childCount < 2)
    return n;
  for (let t = e.depth; t >= 0; t--) {
    let i = e.node(t).contentMatchAt(e.index(t)), o, s = [];
    if (n.forEach((l) => {
      if (!s)
        return;
      let a = i.findWrapping(l.type), c;
      if (!a)
        return s = null;
      if (c = s.length && o.length && h_(a, o, l, s[s.length - 1], 0))
        s[s.length - 1] = c;
      else {
        s.length && (s[s.length - 1] = f_(s[s.length - 1], o.length));
        let d = u_(l, a);
        s.push(d), i = i.matchType(d.type), o = a;
      }
    }), s)
      return A.from(s);
  }
  return n;
}
function u_(n, e, t = 0) {
  for (let r = e.length - 1; r >= t; r--)
    n = e[r].create(null, A.from(n));
  return n;
}
function h_(n, e, t, r, i) {
  if (i < n.length && i < e.length && n[i] == e[i]) {
    let o = h_(n, e, t, r.lastChild, i + 1);
    if (o)
      return r.copy(r.content.replaceChild(r.childCount - 1, o));
    if (r.contentMatchAt(r.childCount).matchType(i == n.length - 1 ? t.type : n[i + 1]))
      return r.copy(r.content.append(A.from(u_(t, n, i + 1))));
  }
}
function f_(n, e) {
  if (e == 0)
    return n;
  let t = n.content.replaceChild(n.childCount - 1, f_(n.lastChild, e - 1)), r = n.contentMatchAt(n.childCount).fillBefore(A.empty, !0);
  return n.copy(t.append(r));
}
function Mu(n, e, t, r, i, o) {
  let s = e < 0 ? n.firstChild : n.lastChild, l = s.content;
  return n.childCount > 1 && (o = 0), i < r - 1 && (l = Mu(l, e, t, r, i + 1, o)), i >= t && (l = e < 0 ? s.contentMatchAt(0).fillBefore(l, o <= i).append(l) : l.append(s.contentMatchAt(s.childCount).fillBefore(A.empty, !0))), n.replaceChild(e < 0 ? 0 : n.childCount - 1, s.copy(l));
}
function yg(n, e, t) {
  return e < n.openStart && (n = new O(Mu(n.content, -1, e, n.openStart, 0, n.openEnd), e, n.openEnd)), t < n.openEnd && (n = new O(Mu(n.content, 1, t, n.openEnd, 0, 0), n.openStart, t)), n;
}
const p_ = {
  thead: ["table"],
  tbody: ["table"],
  tfoot: ["table"],
  caption: ["table"],
  colgroup: ["table"],
  col: ["table", "colgroup"],
  tr: ["table", "tbody"],
  td: ["table", "tbody", "tr"],
  th: ["table", "tbody", "tr"]
};
let _g = null;
function m_() {
  return _g || (_g = document.implementation.createHTMLDocument("title"));
}
let Sd = null;
function jD(n) {
  let e = window.trustedTypes;
  return e ? (Sd || (Sd = e.defaultPolicy || e.createPolicy("ProseMirrorClipboard", { createHTML: (t) => t })), Sd.createHTML(n)) : n;
}
function WD(n) {
  let e = /^(\s*<meta [^>]*>)*/.exec(n);
  e && (n = n.slice(e[0].length));
  let t = m_().createElement("div"), r = /<([a-z][^>\s]+)/i.exec(n), i;
  if ((i = r && p_[r[1].toLowerCase()]) && (n = i.map((o) => "<" + o + ">").join("") + n + i.map((o) => "</" + o + ">").reverse().join("")), t.innerHTML = jD(n), i)
    for (let o = 0; o < i.length; o++)
      t = t.querySelector(i[o]) || t;
  return t;
}
function GD(n) {
  let e = n.querySelectorAll(nt ? "span:not([class]):not([style])" : "span.Apple-converted-space");
  for (let t = 0; t < e.length; t++) {
    let r = e[t];
    r.childNodes.length == 1 && r.textContent == " " && r.parentNode && r.parentNode.replaceChild(n.ownerDocument.createTextNode(" "), r);
  }
}
function KD(n, e) {
  if (!n.size)
    return n;
  let t = n.content.firstChild.type.schema, r;
  try {
    r = JSON.parse(e);
  } catch {
    return n;
  }
  let { content: i, openStart: o, openEnd: s } = n;
  for (let l = r.length - 2; l >= 0; l -= 2) {
    let a = t.nodes[r[l]];
    if (!a || a.hasRequiredAttrs())
      break;
    i = A.from(a.create(r[l + 1], i)), o++, s++;
  }
  return new O(i, o, s);
}
const ft = {}, pt = {}, JD = { touchstart: !0, touchmove: !0 };
class YD {
  constructor() {
    this.shiftKey = !1, 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 = !1, 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 XD(n) {
  for (let e in ft) {
    let t = ft[e];
    n.dom.addEventListener(e, n.input.eventHandlers[e] = (r) => {
      QD(n, r) && !Rh(n, r) && (n.editable || !(r.type in pt)) && t(n, r);
    }, JD[e] ? { passive: !0 } : void 0);
  }
  ht && n.dom.addEventListener("input", () => null), Ou(n);
}
function xr(n, e) {
  n.input.lastSelectionOrigin = e, n.input.lastSelectionTime = Date.now();
}
function ZD(n) {
  n.domObserver.stop();
  for (let e in n.input.eventHandlers)
    n.dom.removeEventListener(e, n.input.eventHandlers[e]);
  clearTimeout(n.input.composingTimeout), clearTimeout(n.input.lastIOSEnterFallbackTimeout);
}
function Ou(n) {
  n.someProp("handleDOMEvents", (e) => {
    for (let t in e)
      n.input.eventHandlers[t] || n.dom.addEventListener(t, n.input.eventHandlers[t] = (r) => Rh(n, r));
  });
}
function Rh(n, e) {
  return n.someProp("handleDOMEvents", (t) => {
    let r = t[e.type];
    return r ? r(n, e) || e.defaultPrevented : !1;
  });
}
function QD(n, e) {
  if (!e.bubbles)
    return !0;
  if (e.defaultPrevented)
    return !1;
  for (let t = e.target; t != n.dom; t = t.parentNode)
    if (!t || t.nodeType == 11 || t.pmViewDesc && t.pmViewDesc.stopEvent(e))
      return !1;
  return !0;
}
function eA(n, e) {
  !Rh(n, e) && ft[e.type] && (n.editable || !(e.type in pt)) && ft[e.type](n, e);
}
pt.keydown = (n, e) => {
  let t = e;
  if (n.input.shiftKey = t.keyCode == 16 || t.shiftKey, !b_(n, t) && (n.input.lastKeyCode = t.keyCode, n.input.lastKeyCodeTime = Date.now(), !(Xn && nt && t.keyCode == 13)))
    if (t.keyCode != 229 && n.domObserver.forceFlush(), so && t.keyCode == 13 && !t.ctrlKey && !t.altKey && !t.metaKey) {
      let r = Date.now();
      n.input.lastIOSEnter = r, n.input.lastIOSEnterFallbackTimeout = setTimeout(() => {
        n.input.lastIOSEnter == r && (n.someProp("handleKeyDown", (i) => i(n, Gr(13, "Enter"))), n.input.lastIOSEnter = 0);
      }, 200);
    } else n.someProp("handleKeyDown", (r) => r(n, t)) || VD(n, t) ? t.preventDefault() : xr(n, "key");
};
pt.keyup = (n, e) => {
  e.keyCode == 16 && (n.input.shiftKey = !1);
};
pt.keypress = (n, e) => {
  let t = e;
  if (b_(n, t) || !t.charCode || t.ctrlKey && !t.altKey || zt && t.metaKey)
    return;
  if (n.someProp("handleKeyPress", (i) => i(n, t))) {
    t.preventDefault();
    return;
  }
  let r = n.state.selection;
  if (!(r instanceof L) || !r.$from.sameParent(r.$to)) {
    let i = String.fromCharCode(t.charCode), o = () => n.state.tr.insertText(i).scrollIntoView();
    !/[\r\n]/.test(i) && !n.someProp("handleTextInput", (s) => s(n, r.$from.pos, r.$to.pos, i, o)) && n.dispatch(o()), t.preventDefault();
  }
};
function bc(n) {
  return { left: n.clientX, top: n.clientY };
}
function tA(n, e) {
  let t = e.x - n.clientX, r = e.y - n.clientY;
  return t * t + r * r < 100;
}
function Bh(n, e, t, r, i) {
  if (r == -1)
    return !1;
  let o = n.state.doc.resolve(r);
  for (let s = o.depth + 1; s > 0; s--)
    if (n.someProp(e, (l) => s > o.depth ? l(n, t, o.nodeAfter, o.before(s), i, !0) : l(n, t, o.node(s), o.before(s), i, !1)))
      return !0;
  return !1;
}
function Yi(n, e, t) {
  if (n.focused || n.focus(), n.state.selection.eq(e))
    return;
  let r = n.state.tr.setSelection(e);
  r.setMeta("pointer", !0), n.dispatch(r);
}
function nA(n, e) {
  if (e == -1)
    return !1;
  let t = n.state.doc.resolve(e), r = t.nodeAfter;
  return r && r.isAtom && P.isSelectable(r) ? (Yi(n, new P(t)), !0) : !1;
}
function rA(n, e) {
  if (e == -1)
    return !1;
  let t = n.state.selection, r, i;
  t instanceof P && (r = t.node);
  let o = n.state.doc.resolve(e);
  for (let s = o.depth + 1; s > 0; s--) {
    let l = s > o.depth ? o.nodeAfter : o.node(s);
    if (P.isSelectable(l)) {
      r && t.$from.depth > 0 && s >= t.$from.depth && o.before(t.$from.depth + 1) == t.$from.pos ? i = o.before(t.$from.depth) : i = o.before(s);
      break;
    }
  }
  return i != null ? (Yi(n, P.create(n.state.doc, i)), !0) : !1;
}
function iA(n, e, t, r, i) {
  return Bh(n, "handleClickOn", e, t, r) || n.someProp("handleClick", (o) => o(n, e, r)) || (i ? rA(n, t) : nA(n, t));
}
function oA(n, e, t, r) {
  return Bh(n, "handleDoubleClickOn", e, t, r) || n.someProp("handleDoubleClick", (i) => i(n, e, r));
}
function sA(n, e, t, r) {
  return Bh(n, "handleTripleClickOn", e, t, r) || n.someProp("handleTripleClick", (i) => i(n, e, r)) || lA(n, t, r);
}
function lA(n, e, t) {
  if (t.button != 0)
    return !1;
  let r = n.state.doc;
  if (e == -1)
    return r.inlineContent ? (Yi(n, L.create(r, 0, r.content.size)), !0) : !1;
  let i = r.resolve(e);
  for (let o = i.depth + 1; o > 0; o--) {
    let s = o > i.depth ? i.nodeAfter : i.node(o), l = i.before(o);
    if (s.inlineContent)
      Yi(n, L.create(r, l + 1, l + 1 + s.content.size));
    else if (P.isSelectable(s))
      Yi(n, P.create(r, l));
    else
      continue;
    return !0;
  }
}
function Ph(n) {
  return ya(n);
}
const g_ = zt ? "metaKey" : "ctrlKey";
ft.mousedown = (n, e) => {
  let t = e;
  n.input.shiftKey = t.shiftKey;
  let r = Ph(n), i = Date.now(), o = "singleClick";
  i - n.input.lastClick.time < 500 && tA(t, n.input.lastClick) && !t[g_] && n.input.lastClick.button == t.button && (n.input.lastClick.type == "singleClick" ? o = "doubleClick" : n.input.lastClick.type == "doubleClick" && (o = "tripleClick")), n.input.lastClick = { time: i, x: t.clientX, y: t.clientY, type: o, button: t.button };
  let s = n.posAtCoords(bc(t));
  s && (o == "singleClick" ? (n.input.mouseDown && n.input.mouseDown.done(), n.input.mouseDown = new aA(n, s, t, !!r)) : (o == "doubleClick" ? oA : sA)(n, s.pos, s.inside, t) ? t.preventDefault() : xr(n, "pointer"));
};
class aA {
  constructor(e, t, r, i) {
    this.view = e, this.pos = t, this.event = r, this.flushed = i, this.delayedSelectionSync = !1, this.mightDrag = null, this.startDoc = e.state.doc, this.selectNode = !!r[g_], this.allowDefault = r.shiftKey;
    let o, s;
    if (t.inside > -1)
      o = e.state.doc.nodeAt(t.inside), s = t.inside;
    else {
      let d = e.state.doc.resolve(t.pos);
      o = d.parent, s = d.depth ? d.before() : 0;
    }
    const l = i ? null : r.target, a = l ? e.docView.nearestDesc(l, !0) : null;
    this.target = a && a.dom.nodeType == 1 ? a.dom : null;
    let { selection: c } = e.state;
    (r.button == 0 && o.type.spec.draggable && o.type.spec.selectable !== !1 || c instanceof P && c.from <= s && c.to > s) && (this.mightDrag = {
      node: o,
      pos: s,
      addAttr: !!(this.target && !this.target.draggable),
      setUneditable: !!(this.target && hn && !this.target.hasAttribute("contentEditable"))
    }), this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable) && (this.view.domObserver.stop(), this.mightDrag.addAttr && (this.target.draggable = !0), this.mightDrag.setUneditable && setTimeout(() => {
      this.view.input.mouseDown == this && this.target.setAttribute("contentEditable", "false");
    }, 20), this.view.domObserver.start()), e.root.addEventListener("mouseup", this.up = this.up.bind(this)), e.root.addEventListener("mousemove", this.move = this.move.bind(this)), xr(e, "pointer");
  }
  done() {
    this.view.root.removeEventListener("mouseup", this.up), this.view.root.removeEventListener("mousemove", this.move), this.mightDrag && this.target && (this.view.domObserver.stop(), this.mightDrag.addAttr && this.target.removeAttribute("draggable"), this.mightDrag.setUneditable && this.target.removeAttribute("contentEditable"), this.view.domObserver.start()), this.delayedSelectionSync && setTimeout(() => tr(this.view)), this.view.input.mouseDown = null;
  }
  up(e) {
    if (this.done(), !this.view.dom.contains(e.target))
      return;
    let t = this.pos;
    this.view.state.doc != this.startDoc && (t = this.view.posAtCoords(bc(e))), this.updateAllowDefault(e), this.allowDefault || !t ? xr(this.view, "pointer") : iA(this.view, t.pos, t.inside, e, this.selectNode) ? e.preventDefault() : e.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements
    ht && 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.
    nt && !this.view.state.selection.visible && Math.min(Math.abs(t.pos - this.view.state.selection.from), Math.abs(t.pos - this.view.state.selection.to)) <= 2) ? (Yi(this.view, V.near(this.view.state.doc.resolve(t.pos))), e.preventDefault()) : xr(this.view, "pointer");
  }
  move(e) {
    this.updateAllowDefault(e), xr(this.view, "pointer"), e.buttons == 0 && this.done();
  }
  updateAllowDefault(e) {
    !this.allowDefault && (Math.abs(this.event.x - e.clientX) > 4 || Math.abs(this.event.y - e.clientY) > 4) && (this.allowDefault = !0);
  }
}
ft.touchstart = (n) => {
  n.input.lastTouch = Date.now(), Ph(n), xr(n, "pointer");
};
ft.touchmove = (n) => {
  n.input.lastTouch = Date.now(), xr(n, "pointer");
};
ft.contextmenu = (n) => Ph(n);
function b_(n, e) {
  return n.composing ? !0 : ht && Math.abs(e.timeStamp - n.input.compositionEndedAt) < 500 ? (n.input.compositionEndedAt = -2e8, !0) : !1;
}
const cA = Xn ? 5e3 : -1;
pt.compositionstart = pt.compositionupdate = (n) => {
  if (!n.composing) {
    n.domObserver.flush();
    let { state: e } = n, t = e.selection.$to;
    if (e.selection instanceof L && (e.storedMarks || !t.textOffset && t.parentOffset && t.nodeBefore.marks.some((r) => r.type.spec.inclusive === !1)))
      n.markCursor = n.state.storedMarks || t.marks(), ya(n, !0), n.markCursor = null;
    else if (ya(n, !e.selection.empty), hn && e.selection.empty && t.parentOffset && !t.textOffset && t.nodeBefore.marks.length) {
      let r = n.domSelectionRange();
      for (let i = r.focusNode, o = r.focusOffset; i && i.nodeType == 1 && o != 0; ) {
        let s = o < 0 ? i.lastChild : i.childNodes[o - 1];
        if (!s)
          break;
        if (s.nodeType == 3) {
          let l = n.domSelection();
          l && l.collapse(s, s.nodeValue.length);
          break;
        } else
          i = s, o = -1;
      }
    }
    n.input.composing = !0;
  }
  y_(n, cA);
};
pt.compositionend = (n, e) => {
  n.composing && (n.input.composing = !1, n.input.compositionEndedAt = e.timeStamp, n.input.compositionPendingChanges = n.domObserver.pendingRecords().length ? n.input.compositionID : 0, n.input.compositionNode = null, n.input.compositionPendingChanges && Promise.resolve().then(() => n.domObserver.flush()), n.input.compositionID++, y_(n, 20));
};
function y_(n, e) {
  clearTimeout(n.input.composingTimeout), e > -1 && (n.input.composingTimeout = setTimeout(() => ya(n), e));
}
function __(n) {
  for (n.composing && (n.input.composing = !1, n.input.compositionEndedAt = uA()); n.input.compositionNodes.length > 0; )
    n.input.compositionNodes.pop().markParentsDirty();
}
function dA(n) {
  let e = n.domSelectionRange();
  if (!e.focusNode)
    return null;
  let t = nD(e.focusNode, e.focusOffset), r = rD(e.focusNode, e.focusOffset);
  if (t && r && t != r) {
    let i = r.pmViewDesc, o = n.domObserver.lastChangedTextNode;
    if (t == o || r == o)
      return o;
    if (!i || !i.isText(r.nodeValue))
      return r;
    if (n.input.compositionNode == r) {
      let s = t.pmViewDesc;
      if (!(!s || !s.isText(t.nodeValue)))
        return r;
    }
  }
  return t || r;
}
function uA() {
  let n = document.createEvent("Event");
  return n.initEvent("event", !0, !0), n.timeStamp;
}
function ya(n, e = !1) {
  if (!(Xn && n.domObserver.flushingSoon >= 0)) {
    if (n.domObserver.forceFlush(), __(n), e || n.docView && n.docView.dirty) {
      let t = $h(n), r = n.state.selection;
      return t && !t.eq(r) ? n.dispatch(n.state.tr.setSelection(t)) : (n.markCursor || e) && !r.$from.node(r.$from.sharedDepth(r.to)).inlineContent ? n.dispatch(n.state.tr.deleteSelection()) : n.updateState(n.state), !0;
    }
    return !1;
  }
}
function hA(n, e) {
  if (!n.dom.parentNode)
    return;
  let t = n.dom.parentNode.appendChild(document.createElement("div"));
  t.appendChild(e), t.style.cssText = "position: fixed; left: -10000px; top: 10px";
  let r = getSelection(), i = document.createRange();
  i.selectNodeContents(e), n.dom.blur(), r.removeAllRanges(), r.addRange(i), setTimeout(() => {
    t.parentNode && t.parentNode.removeChild(t), n.focus();
  }, 50);
}
const ps = kt && Ar < 15 || so && aD < 604;
ft.copy = pt.cut = (n, e) => {
  let t = e, r = n.state.selection, i = t.type == "cut";
  if (r.empty)
    return;
  let o = ps ? null : t.clipboardData, s = r.content(), { dom: l, text: a } = Lh(n, s);
  o ? (t.preventDefault(), o.clearData(), o.setData("text/html", l.innerHTML), o.setData("text/plain", a)) : hA(n, l), i && n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
};
function fA(n) {
  return n.openStart == 0 && n.openEnd == 0 && n.content.childCount == 1 ? n.content.firstChild : null;
}
function pA(n, e) {
  if (!n.dom.parentNode)
    return;
  let t = n.input.shiftKey || n.state.selection.$from.parent.type.spec.code, r = n.dom.parentNode.appendChild(document.createElement(t ? "textarea" : "div"));
  t || (r.contentEditable = "true"), r.style.cssText = "position: fixed; left: -10000px; top: 10px", r.focus();
  let i = n.input.shiftKey && n.input.lastKeyCode != 45;
  setTimeout(() => {
    n.focus(), r.parentNode && r.parentNode.removeChild(r), t ? ms(n, r.value, null, i, e) : ms(n, r.textContent, r.innerHTML, i, e);
  }, 50);
}
function ms(n, e, t, r, i) {
  let o = d_(n, e, t, r, n.state.selection.$from);
  if (n.someProp("handlePaste", (a) => a(n, i, o || O.empty)))
    return !0;
  if (!o)
    return !1;
  let s = fA(o), l = s ? n.state.tr.replaceSelectionWith(s, r) : n.state.tr.replaceSelection(o);
  return n.dispatch(l.scrollIntoView().setMeta("paste", !0).setMeta("uiEvent", "paste")), !0;
}
function w_(n) {
  let e = n.getData("text/plain") || n.getData("Text");
  if (e)
    return e;
  let t = n.getData("text/uri-list");
  return t ? t.replace(/\r?\n/g, " ") : "";
}
pt.paste = (n, e) => {
  let t = e;
  if (n.composing && !Xn)
    return;
  let r = ps ? null : t.clipboardData, i = n.input.shiftKey && n.input.lastKeyCode != 45;
  r && ms(n, w_(r), r.getData("text/html"), i, t) ? t.preventDefault() : pA(n, t);
};
class k_ {
  constructor(e, t, r) {
    this.slice = e, this.move = t, this.node = r;
  }
}
const mA = zt ? "altKey" : "ctrlKey";
function v_(n, e) {
  let t = n.someProp("dragCopies", (r) => !r(e));
  return t ?? !e[mA];
}
ft.dragstart = (n, e) => {
  let t = e, r = n.input.mouseDown;
  if (r && r.done(), !t.dataTransfer)
    return;
  let i = n.state.selection, o = i.empty ? null : n.posAtCoords(bc(t)), s;
  if (!(o && o.pos >= i.from && o.pos <= (i instanceof P ? i.to - 1 : i.to))) {
    if (r && r.mightDrag)
      s = P.create(n.state.doc, r.mightDrag.pos);
    else if (t.target && t.target.nodeType == 1) {
      let u = n.docView.nearestDesc(t.target, !0);
      u && u.node.type.spec.draggable && u != n.docView && (s = P.create(n.state.doc, u.posBefore));
    }
  }
  let l = (s || n.state.selection).content(), { dom: a, text: c, slice: d } = Lh(n, l);
  (!t.dataTransfer.files.length || !nt || Ky > 120) && t.dataTransfer.clearData(), t.dataTransfer.setData(ps ? "Text" : "text/html", a.innerHTML), t.dataTransfer.effectAllowed = "copyMove", ps || t.dataTransfer.setData("text/plain", c), n.dragging = new k_(d, v_(n, t), s);
};
ft.dragend = (n) => {
  let e = n.dragging;
  window.setTimeout(() => {
    n.dragging == e && (n.dragging = null);
  }, 50);
};
pt.dragover = pt.dragenter = (n, e) => e.preventDefault();
pt.drop = (n, e) => {
  let t = e, r = n.dragging;
  if (n.dragging = null, !t.dataTransfer)
    return;
  let i = n.posAtCoords(bc(t));
  if (!i)
    return;
  let o = n.state.doc.resolve(i.pos), s = r && r.slice;
  s ? n.someProp("transformPasted", (p) => {
    s = p(s, n);
  }) : s = d_(n, w_(t.dataTransfer), ps ? null : t.dataTransfer.getData("text/html"), !1, o);
  let l = !!(r && v_(n, t));
  if (n.someProp("handleDrop", (p) => p(n, t, s || O.empty, l))) {
    t.preventDefault();
    return;
  }
  if (!s)
    return;
  t.preventDefault();
  let a = s ? Py(n.state.doc, o.pos, s) : o.pos;
  a == null && (a = o.pos);
  let c = n.state.tr;
  if (l) {
    let { node: p } = r;
    p ? p.replace(c) : c.deleteSelection();
  }
  let d = c.mapping.map(a), u = s.openStart == 0 && s.openEnd == 0 && s.content.childCount == 1, h = c.doc;
  if (u ? c.replaceRangeWith(d, d, s.content.firstChild) : c.replaceRange(d, d, s), c.doc.eq(h))
    return;
  let f = c.doc.resolve(d);
  if (u && P.isSelectable(s.content.firstChild) && f.nodeAfter && f.nodeAfter.sameMarkup(s.content.firstChild))
    c.setSelection(new P(f));
  else {
    let p = c.mapping.map(a);
    c.mapping.maps[c.mapping.maps.length - 1].forEach((m, g, y, _) => p = _), c.setSelection(Ih(n, f, c.doc.resolve(p)));
  }
  n.focus(), n.dispatch(c.setMeta("uiEvent", "drop"));
};
ft.focus = (n) => {
  n.input.lastFocus = Date.now(), n.focused || (n.domObserver.stop(), n.dom.classList.add("ProseMirror-focused"), n.domObserver.start(), n.focused = !0, setTimeout(() => {
    n.docView && n.hasFocus() && !n.domObserver.currentSelection.eq(n.domSelectionRange()) && tr(n);
  }, 20));
};
ft.blur = (n, e) => {
  let t = e;
  n.focused && (n.domObserver.stop(), n.dom.classList.remove("ProseMirror-focused"), n.domObserver.start(), t.relatedTarget && n.dom.contains(t.relatedTarget) && n.domObserver.currentSelection.clear(), n.focused = !1);
};
ft.beforeinput = (n, e) => {
  if (nt && Xn && e.inputType == "deleteContentBackward") {
    n.domObserver.flushSoon();
    let { domChangeCount: r } = n.input;
    setTimeout(() => {
      if (n.input.domChangeCount != r || (n.dom.blur(), n.focus(), n.someProp("handleKeyDown", (o) => o(n, Gr(8, "Backspace")))))
        return;
      let { $cursor: i } = n.state.selection;
      i && i.pos > 0 && n.dispatch(n.state.tr.delete(i.pos - 1, i.pos).scrollIntoView());
    }, 50);
  }
};
for (let n in pt)
  ft[n] = pt[n];
function gs(n, e) {
  if (n == e)
    return !0;
  for (let t in n)
    if (n[t] !== e[t])
      return !1;
  for (let t in e)
    if (!(t in n))
      return !1;
  return !0;
}
class _a {
  constructor(e, t) {
    this.toDOM = e, this.spec = t || oi, this.side = this.spec.side || 0;
  }
  map(e, t, r, i) {
    let { pos: o, deleted: s } = e.mapResult(t.from + i, this.side < 0 ? -1 : 1);
    return s ? null : new se(o - r, o - r, this);
  }
  valid() {
    return !0;
  }
  eq(e) {
    return this == e || e instanceof _a && (this.spec.key && this.spec.key == e.spec.key || this.toDOM == e.toDOM && gs(this.spec, e.spec));
  }
  destroy(e) {
    this.spec.destroy && this.spec.destroy(e);
  }
}
class Mr {
  constructor(e, t) {
    this.attrs = e, this.spec = t || oi;
  }
  map(e, t, r, i) {
    let o = e.map(t.from + i, this.spec.inclusiveStart ? -1 : 1) - r, s = e.map(t.to + i, this.spec.inclusiveEnd ? 1 : -1) - r;
    return o >= s ? null : new se(o, s, this);
  }
  valid(e, t) {
    return t.from < t.to;
  }
  eq(e) {
    return this == e || e instanceof Mr && gs(this.attrs, e.attrs) && gs(this.spec, e.spec);
  }
  static is(e) {
    return e.type instanceof Mr;
  }
  destroy() {
  }
}
class zh {
  constructor(e, t) {
    this.attrs = e, this.spec = t || oi;
  }
  map(e, t, r, i) {
    let o = e.mapResult(t.from + i, 1);
    if (o.deleted)
      return null;
    let s = e.mapResult(t.to + i, -1);
    return s.deleted || s.pos <= o.pos ? null : new se(o.pos - r, s.pos - r, this);
  }
  valid(e, t) {
    let { index: r, offset: i } = e.content.findIndex(t.from), o;
    return i == t.from && !(o = e.child(r)).isText && i + o.nodeSize == t.to;
  }
  eq(e) {
    return this == e || e instanceof zh && gs(this.attrs, e.attrs) && gs(this.spec, e.spec);
  }
  destroy() {
  }
}
class se {
  /**
  @internal
  */
  constructor(e, t, r) {
    this.from = e, this.to = t, this.type = r;
  }
  /**
  @internal
  */
  copy(e, t) {
    return new se(e, t, this.type);
  }
  /**
  @internal
  */
  eq(e, t = 0) {
    return this.type.eq(e.type) && this.from + t == e.from && this.to + t == e.to;
  }
  /**
  @internal
  */
  map(e, t, r) {
    return this.type.map(e, this, t, r);
  }
  /**
  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(e, t, r) {
    return new se(e, e, new _a(t, r));
  }
  /**
  Creates an inline decoration, which adds the given attributes to
  each inline node between `from` and `to`.
  */
  static inline(e, t, r, i) {
    return new se(e, t, new Mr(r, i));
  }
  /**
  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(e, t, r, i) {
    return new se(e, t, new zh(r, i));
  }
  /**
  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 Mr;
  }
  /**
  @internal
  */
  get widget() {
    return this.type instanceof _a;
  }
}
const Vi = [], oi = {};
class Q {
  /**
  @internal
  */
  constructor(e, t) {
    this.local = e.length ? e : Vi, this.children = t.length ? t : Vi;
  }
  /**
  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(e, t) {
    return t.length ? wa(t, e, 0, oi) : tt;
  }
  /**
  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(e, t, r) {
    let i = [];
    return this.findInner(e ?? 0, t ?? 1e9, i, 0, r), i;
  }
  findInner(e, t, r, i, o) {
    for (let s = 0; s < this.local.length; s++) {
      let l = this.local[s];
      l.from <= t && l.to >= e && (!o || o(l.spec)) && r.push(l.copy(l.from + i, l.to + i));
    }
    for (let s = 0; s < this.children.length; s += 3)
      if (this.children[s] < t && this.children[s + 1] > e) {
        let l = this.children[s] + 1;
        this.children[s + 2].findInner(e - l, t - l, r, i + l, o);
      }
  }
  /**
  Map the set of decorations in response to a change in the
  document.
  */
  map(e, t, r) {
    return this == tt || e.maps.length == 0 ? this : this.mapInner(e, t, 0, 0, r || oi);
  }
  /**
  @internal
  */
  mapInner(e, t, r, i, o) {
    let s;
    for (let l = 0; l < this.local.length; l++) {
      let a = this.local[l].map(e, r, i);
      a && a.type.valid(t, a) ? (s || (s = [])).push(a) : o.onRemove && o.onRemove(this.local[l].spec);
    }
    return this.children.length ? gA(this.children, s || [], e, t, r, i, o) : s ? new Q(s.sort(si), Vi) : tt;
  }
  /**
  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(e, t) {
    return t.length ? this == tt ? Q.create(e, t) : this.addInner(e, t, 0) : this;
  }
  addInner(e, t, r) {
    let i, o = 0;
    e.forEach((l, a) => {
      let c = a + r, d;
      if (d = S_(t, l, c)) {
        for (i || (i = this.children.slice()); o < i.length && i[o] < a; )
          o += 3;
        i[o] == a ? i[o + 2] = i[o + 2].addInner(l, d, c + 1) : i.splice(o, 0, a, a + l.nodeSize, wa(d, l, c + 1, oi)), o += 3;
      }
    });
    let s = C_(o ? E_(t) : t, -r);
    for (let l = 0; l < s.length; l++)
      s[l].type.valid(e, s[l]) || s.splice(l--, 1);
    return new Q(s.length ? this.local.concat(s).sort(si) : this.local, i || this.children);
  }
  /**
  Create a new set that contains the decorations in this set, minus
  the ones in the given array.
  */
  remove(e) {
    return e.length == 0 || this == tt ? this : this.removeInner(e, 0);
  }
  removeInner(e, t) {
    let r = this.children, i = this.local;
    for (let o = 0; o < r.length; o += 3) {
      let s, l = r[o] + t, a = r[o + 1] + t;
      for (let d = 0, u; d < e.length; d++)
        (u = e[d]) && u.from > l && u.to < a && (e[d] = null, (s || (s = [])).push(u));
      if (!s)
        continue;
      r == this.children && (r = this.children.slice());
      let c = r[o + 2].removeInner(s, l + 1);
      c != tt ? r[o + 2] = c : (r.splice(o, 3), o -= 3);
    }
    if (i.length) {
      for (let o = 0, s; o < e.length; o++)
        if (s = e[o])
          for (let l = 0; l < i.length; l++)
            i[l].eq(s, t) && (i == this.local && (i = this.local.slice()), i.splice(l--, 1));
    }
    return r == this.children && i == this.local ? this : i.length || r.length ? new Q(i, r) : tt;
  }
  forChild(e, t) {
    if (this == tt)
      return this;
    if (t.isLeaf)
      return Q.empty;
    let r, i;
    for (let l = 0; l < this.children.length; l += 3)
      if (this.children[l] >= e) {
        this.children[l] == e && (r = this.children[l + 2]);
        break;
      }
    let o = e + 1, s = o + t.content.size;
    for (let l = 0; l < this.local.length; l++) {
      let a = this.local[l];
      if (a.from < s && a.to > o && a.type instanceof Mr) {
        let c = Math.max(o, a.from) - o, d = Math.min(s, a.to) - o;
        c < d && (i || (i = [])).push(a.copy(c, d));
      }
    }
    if (i) {
      let l = new Q(i.sort(si), Vi);
      return r ? new _r([l, r]) : l;
    }
    return r || tt;
  }
  /**
  @internal
  */
  eq(e) {
    if (this == e)
      return !0;
    if (!(e instanceof Q) || this.local.length != e.local.length || this.children.length != e.children.length)
      return !1;
    for (let t = 0; t < this.local.length; t++)
      if (!this.local[t].eq(e.local[t]))
        return !1;
    for (let t = 0; t < this.children.length; t += 3)
      if (this.children[t] != e.children[t] || this.children[t + 1] != e.children[t + 1] || !this.children[t + 2].eq(e.children[t + 2]))
        return !1;
    return !0;
  }
  /**
  @internal
  */
  locals(e) {
    return Hh(this.localsInner(e));
  }
  /**
  @internal
  */
  localsInner(e) {
    if (this == tt)
      return Vi;
    if (e.inlineContent || !this.local.some(Mr.is))
      return this.local;
    let t = [];
    for (let r = 0; r < this.local.length; r++)
      this.local[r].type instanceof Mr || t.push(this.local[r]);
    return t;
  }
  forEachSet(e) {
    e(this);
  }
}
Q.empty = new Q([], []);
Q.removeOverlap = Hh;
const tt = Q.empty;
class _r {
  constructor(e) {
    this.members = e;
  }
  map(e, t) {
    const r = this.members.map((i) => i.map(e, t, oi));
    return _r.from(r);
  }
  forChild(e, t) {
    if (t.isLeaf)
      return Q.empty;
    let r = [];
    for (let i = 0; i < this.members.length; i++) {
      let o = this.members[i].forChild(e, t);
      o != tt && (o instanceof _r ? r = r.concat(o.members) : r.push(o));
    }
    return _r.from(r);
  }
  eq(e) {
    if (!(e instanceof _r) || e.members.length != this.members.length)
      return !1;
    for (let t = 0; t < this.members.length; t++)
      if (!this.members[t].eq(e.members[t]))
        return !1;
    return !0;
  }
  locals(e) {
    let t, r = !0;
    for (let i = 0; i < this.members.length; i++) {
      let o = this.members[i].localsInner(e);
      if (o.length)
        if (!t)
          t = o;
        else {
          r && (t = t.slice(), r = !1);
          for (let s = 0; s < o.length; s++)
            t.push(o[s]);
        }
    }
    return t ? Hh(r ? t : t.sort(si)) : Vi;
  }
  // Create a group for the given array of decoration sets, or return
  // a single set when possible.
  static from(e) {
    switch (e.length) {
      case 0:
        return tt;
      case 1:
        return e[0];
      default:
        return new _r(e.every((t) => t instanceof Q) ? e : e.reduce((t, r) => t.concat(r instanceof Q ? r : r.members), []));
    }
  }
  forEachSet(e) {
    for (let t = 0; t < this.members.length; t++)
      this.members[t].forEachSet(e);
  }
}
function gA(n, e, t, r, i, o, s) {
  let l = n.slice();
  for (let c = 0, d = o; c < t.maps.length; c++) {
    let u = 0;
    t.maps[c].forEach((h, f, p, m) => {
      let g = m - p - (f - h);
      for (let y = 0; y < l.length; y += 3) {
        let _ = l[y + 1];
        if (_ < 0 || h > _ + d - u)
          continue;
        let b = l[y] + d - u;
        f >= b ? l[y + 1] = h <= b ? -2 : -1 : h >= d && g && (l[y] += g, l[y + 1] += g);
      }
      u += g;
    }), d = t.maps[c].map(d, -1);
  }
  let a = !1;
  for (let c = 0; c < l.length; c += 3)
    if (l[c + 1] < 0) {
      if (l[c + 1] == -2) {
        a = !0, l[c + 1] = -1;
        continue;
      }
      let d = t.map(n[c] + o), u = d - i;
      if (u < 0 || u >= r.content.size) {
        a = !0;
        continue;
      }
      let h = t.map(n[c + 1] + o, -1), f = h - i, { index: p, offset: m } = r.content.findIndex(u), g = r.maybeChild(p);
      if (g && m == u && m + g.nodeSize == f) {
        let y = l[c + 2].mapInner(t, g, d + 1, n[c] + o + 1, s);
        y != tt ? (l[c] = u, l[c + 1] = f, l[c + 2] = y) : (l[c + 1] = -2, a = !0);
      } else
        a = !0;
    }
  if (a) {
    let c = bA(l, n, e, t, i, o, s), d = wa(c, r, 0, s);
    e = d.local;
    for (let u = 0; u < l.length; u += 3)
      l[u + 1] < 0 && (l.splice(u, 3), u -= 3);
    for (let u = 0, h = 0; u < d.children.length; u += 3) {
      let f = d.children[u];
      for (; h < l.length && l[h] < f; )
        h += 3;
      l.splice(h, 0, d.children[u], d.children[u + 1], d.children[u + 2]);
    }
  }
  return new Q(e.sort(si), l);
}
function C_(n, e) {
  if (!e || !n.length)
    return n;
  let t = [];
  for (let r = 0; r < n.length; r++) {
    let i = n[r];
    t.push(new se(i.from + e, i.to + e, i.type));
  }
  return t;
}
function bA(n, e, t, r, i, o, s) {
  function l(a, c) {
    for (let d = 0; d < a.local.length; d++) {
      let u = a.local[d].map(r, i, c);
      u ? t.push(u) : s.onRemove && s.onRemove(a.local[d].spec);
    }
    for (let d = 0; d < a.children.length; d += 3)
      l(a.children[d + 2], a.children[d] + c + 1);
  }
  for (let a = 0; a < n.length; a += 3)
    n[a + 1] == -1 && l(n[a + 2], e[a] + o + 1);
  return t;
}
function S_(n, e, t) {
  if (e.isLeaf)
    return null;
  let r = t + e.nodeSize, i = null;
  for (let o = 0, s; o < n.length; o++)
    (s = n[o]) && s.from > t && s.to < r && ((i || (i = [])).push(s), n[o] = null);
  return i;
}
function E_(n) {
  let e = [];
  for (let t = 0; t < n.length; t++)
    n[t] != null && e.push(n[t]);
  return e;
}
function wa(n, e, t, r) {
  let i = [], o = !1;
  e.forEach((l, a) => {
    let c = S_(n, l, a + t);
    if (c) {
      o = !0;
      let d = wa(c, l, t + a + 1, r);
      d != tt && i.push(a, a + l.nodeSize, d);
    }
  });
  let s = C_(o ? E_(n) : n, -t).sort(si);
  for (let l = 0; l < s.length; l++)
    s[l].type.valid(e, s[l]) || (r.onRemove && r.onRemove(s[l].spec), s.splice(l--, 1));
  return s.length || i.length ? new Q(s, i) : tt;
}
function si(n, e) {
  return n.from - e.from || n.to - e.to;
}
function Hh(n) {
  let e = n;
  for (let t = 0; t < e.length - 1; t++) {
    let r = e[t];
    if (r.from != r.to)
      for (let i = t + 1; i < e.length; i++) {
        let o = e[i];
        if (o.from == r.from) {
          o.to != r.to && (e == n && (e = n.slice()), e[i] = o.copy(o.from, r.to), wg(e, i + 1, o.copy(r.to, o.to)));
          continue;
        } else {
          o.from < r.to && (e == n && (e = n.slice()), e[t] = r.copy(r.from, o.from), wg(e, i, r.copy(o.from, r.to)));
          break;
        }
      }
  }
  return e;
}
function wg(n, e, t) {
  for (; e < n.length && si(t, n[e]) > 0; )
    e++;
  n.splice(e, 0, t);
}
function Ed(n) {
  let e = [];
  return n.someProp("decorations", (t) => {
    let r = t(n.state);
    r && r != tt && e.push(r);
  }), n.cursorWrapper && e.push(Q.create(n.state.doc, [n.cursorWrapper.deco])), _r.from(e);
}
const yA = {
  childList: !0,
  characterData: !0,
  characterDataOldValue: !0,
  attributes: !0,
  attributeOldValue: !0,
  subtree: !0
}, _A = kt && Ar <= 11;
class wA {
  constructor() {
    this.anchorNode = null, this.anchorOffset = 0, this.focusNode = null, this.focusOffset = 0;
  }
  set(e) {
    this.anchorNode = e.anchorNode, this.anchorOffset = e.anchorOffset, this.focusNode = e.focusNode, this.focusOffset = e.focusOffset;
  }
  clear() {
    this.anchorNode = this.focusNode = null;
  }
  eq(e) {
    return e.anchorNode == this.anchorNode && e.anchorOffset == this.anchorOffset && e.focusNode == this.focusNode && e.focusOffset == this.focusOffset;
  }
}
class kA {
  constructor(e, t) {
    this.view = e, this.handleDOMChange = t, this.queue = [], this.flushingSoon = -1, this.observer = null, this.currentSelection = new wA(), this.onCharData = null, this.suppressingSelectionUpdates = !1, this.lastChangedTextNode = null, this.observer = window.MutationObserver && new window.MutationObserver((r) => {
      for (let i = 0; i < r.length; i++)
        this.queue.push(r[i]);
      kt && Ar <= 11 && r.some((i) => i.type == "childList" && i.removedNodes.length || i.type == "characterData" && i.oldValue.length > i.target.nodeValue.length) ? this.flushSoon() : this.flush();
    }), _A && (this.onCharData = (r) => {
      this.queue.push({ target: r.target, type: "characterData", oldValue: r.prevValue }), this.flushSoon();
    }), this.onSelectionChange = this.onSelectionChange.bind(this);
  }
  flushSoon() {
    this.flushingSoon < 0 && (this.flushingSoon = window.setTimeout(() => {
      this.flushingSoon = -1, this.flush();
    }, 20));
  }
  forceFlush() {
    this.flushingSoon > -1 && (window.clearTimeout(this.flushingSoon), this.flushingSoon = -1, this.flush());
  }
  start() {
    this.observer && (this.observer.takeRecords(), this.observer.observe(this.view.dom, yA)), this.onCharData && this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData), this.connectSelection();
  }
  stop() {
    if (this.observer) {
      let e = this.observer.takeRecords();
      if (e.length) {
        for (let t = 0; t < e.length; t++)
          this.queue.push(e[t]);
        window.setTimeout(() => this.flush(), 20);
      }
      this.observer.disconnect();
    }
    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 = !0, setTimeout(() => this.suppressingSelectionUpdates = !1, 50);
  }
  onSelectionChange() {
    if (hg(this.view)) {
      if (this.suppressingSelectionUpdates)
        return tr(this.view);
      if (kt && Ar <= 11 && !this.view.state.selection.empty) {
        let e = this.view.domSelectionRange();
        if (e.focusNode && pi(e.focusNode, e.focusOffset, e.anchorNode, e.anchorOffset))
          return this.flushSoon();
      }
      this.flush();
    }
  }
  setCurSelection() {
    this.currentSelection.set(this.view.domSelectionRange());
  }
  ignoreSelectionChange(e) {
    if (!e.focusNode)
      return !0;
    let t = /* @__PURE__ */ new Set(), r;
    for (let o = e.focusNode; o; o = oo(o))
      t.add(o);
    for (let o = e.anchorNode; o; o = oo(o))
      if (t.has(o)) {
        r = o;
        break;
      }
    let i = r && this.view.docView.nearestDesc(r);
    if (i && i.ignoreMutation({
      type: "selection",
      target: r.nodeType == 3 ? r.parentNode : r
    }))
      return this.setCurSelection(), !0;
  }
  pendingRecords() {
    if (this.observer)
      for (let e of this.observer.takeRecords())
        this.queue.push(e);
    return this.queue;
  }
  flush() {
    let { view: e } = this;
    if (!e.docView || this.flushingSoon > -1)
      return;
    let t = this.pendingRecords();
    t.length && (this.queue = []);
    let r = e.domSelectionRange(), i = !this.suppressingSelectionUpdates && !this.currentSelection.eq(r) && hg(e) && !this.ignoreSelectionChange(r), o = -1, s = -1, l = !1, a = [];
    if (e.editable)
      for (let d = 0; d < t.length; d++) {
        let u = this.registerMutation(t[d], a);
        u && (o = o < 0 ? u.from : Math.min(u.from, o), s = s < 0 ? u.to : Math.max(u.to, s), u.typeOver && (l = !0));
      }
    if (hn && a.length) {
      let d = a.filter((u) => u.nodeName == "BR");
      if (d.length == 2) {
        let [u, h] = d;
        u.parentNode && u.parentNode.parentNode == h.parentNode ? h.remove() : u.remove();
      } else {
        let { focusNode: u } = this.currentSelection;
        for (let h of d) {
          let f = h.parentNode;
          f && f.nodeName == "LI" && (!u || SA(e, u) != f) && h.remove();
        }
      }
    }
    let c = null;
    o < 0 && i && e.input.lastFocus > Date.now() - 200 && Math.max(e.input.lastTouch, e.input.lastClick.time) < Date.now() - 300 && mc(r) && (c = $h(e)) && c.eq(V.near(e.state.doc.resolve(0), 1)) ? (e.input.lastFocus = 0, tr(e), this.currentSelection.set(r), e.scrollToSelection()) : (o > -1 || i) && (o > -1 && (e.docView.markDirty(o, s), vA(e)), this.handleDOMChange(o, s, l, a), e.docView && e.docView.dirty ? e.updateState(e.state) : this.currentSelection.eq(r) || tr(e), this.currentSelection.set(r));
  }
  registerMutation(e, t) {
    if (t.indexOf(e.target) > -1)
      return null;
    let r = this.view.docView.nearestDesc(e.target);
    if (e.type == "attributes" && (r == this.view.docView || e.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
    e.attributeName == "style" && !e.oldValue && !e.target.getAttribute("style")) || !r || r.ignoreMutation(e))
      return null;
    if (e.type == "childList") {
      for (let d = 0; d < e.addedNodes.length; d++) {
        let u = e.addedNodes[d];
        t.push(u), u.nodeType == 3 && (this.lastChangedTextNode = u);
      }
      if (r.contentDOM && r.contentDOM != r.dom && !r.contentDOM.contains(e.target))
        return { from: r.posBefore, to: r.posAfter };
      let i = e.previousSibling, o = e.nextSibling;
      if (kt && Ar <= 11 && e.addedNodes.length)
        for (let d = 0; d < e.addedNodes.length; d++) {
          let { previousSibling: u, nextSibling: h } = e.addedNodes[d];
          (!u || Array.prototype.indexOf.call(e.addedNodes, u) < 0) && (i = u), (!h || Array.prototype.indexOf.call(e.addedNodes, h) < 0) && (o = h);
        }
      let s = i && i.parentNode == e.target ? Ge(i) + 1 : 0, l = r.localPosFromDOM(e.target, s, -1), a = o && o.parentNode == e.target ? Ge(o) : e.target.childNodes.length, c = r.localPosFromDOM(e.target, a, 1);
      return { from: l, to: c };
    } else return e.type == "attributes" ? { from: r.posAtStart - r.border, to: r.posAtEnd + r.border } : (this.lastChangedTextNode = e.target, {
      from: r.posAtStart,
      to: r.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: e.target.nodeValue == e.oldValue
    });
  }
}
let kg = /* @__PURE__ */ new WeakMap(), vg = !1;
function vA(n) {
  if (!kg.has(n) && (kg.set(n, null), ["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(n.dom).whiteSpace) !== -1)) {
    if (n.requiresGeckoHackNode = hn, vg)
      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."), vg = !0;
  }
}
function Cg(n, e) {
  let t = e.startContainer, r = e.startOffset, i = e.endContainer, o = e.endOffset, s = n.domAtPos(n.state.selection.anchor);
  return pi(s.node, s.offset, i, o) && ([t, r, i, o] = [i, o, t, r]), { anchorNode: t, anchorOffset: r, focusNode: i, focusOffset: o };
}
function CA(n, e) {
  if (e.getComposedRanges) {
    let i = e.getComposedRanges(n.root)[0];
    if (i)
      return Cg(n, i);
  }
  let t;
  function r(i) {
    i.preventDefault(), i.stopImmediatePropagation(), t = i.getTargetRanges()[0];
  }
  return n.dom.addEventListener("beforeinput", r, !0), document.execCommand("indent"), n.dom.removeEventListener("beforeinput", r, !0), t ? Cg(n, t) : null;
}
function SA(n, e) {
  for (let t = e.parentNode; t && t != n.dom; t = t.parentNode) {
    let r = n.docView.nearestDesc(t, !0);
    if (r && r.node.isBlock)
      return t;
  }
  return null;
}
function EA(n, e, t) {
  let { node: r, fromOffset: i, toOffset: o, from: s, to: l } = n.docView.parseRange(e, t), a = n.domSelectionRange(), c, d = a.anchorNode;
  if (d && n.dom.contains(d.nodeType == 1 ? d : d.parentNode) && (c = [{ node: d, offset: a.anchorOffset }], mc(a) || c.push({ node: a.focusNode, offset: a.focusOffset })), nt && n.input.lastKeyCode === 8)
    for (let g = o; g > i; g--) {
      let y = r.childNodes[g - 1], _ = y.pmViewDesc;
      if (y.nodeName == "BR" && !_) {
        o = g;
        break;
      }
      if (!_ || _.size)
        break;
    }
  let u = n.state.doc, h = n.someProp("domParser") || On.fromSchema(n.state.schema), f = u.resolve(s), p = null, m = h.parse(r, {
    topNode: f.parent,
    topMatch: f.parent.contentMatchAt(f.index()),
    topOpen: !0,
    from: i,
    to: o,
    preserveWhitespace: f.parent.type.whitespace == "pre" ? "full" : !0,
    findPositions: c,
    ruleFromNode: xA,
    context: f
  });
  if (c && c[0].pos != null) {
    let g = c[0].pos, y = c[1] && c[1].pos;
    y == null && (y = g), p = { anchor: g + s, head: y + s };
  }
  return { doc: m, sel: p, from: s, to: l };
}
function xA(n) {
  let e = n.pmViewDesc;
  if (e)
    return e.parseRule();
  if (n.nodeName == "BR" && n.parentNode) {
    if (ht && /^(ul|ol)$/i.test(n.parentNode.nodeName)) {
      let t = document.createElement("div");
      return t.appendChild(document.createElement("li")), { skip: t };
    } else if (n.parentNode.lastChild == n || ht && /^(tr|table)$/i.test(n.parentNode.nodeName))
      return { ignore: !0 };
  } else if (n.nodeName == "IMG" && n.getAttribute("mark-placeholder"))
    return { ignore: !0 };
  return null;
}
const DA = /^(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 AA(n, e, t, r, i) {
  let o = n.input.compositionPendingChanges || (n.composing ? n.input.compositionID : 0);
  if (n.input.compositionPendingChanges = 0, e < 0) {
    let S = n.input.lastSelectionTime > Date.now() - 50 ? n.input.lastSelectionOrigin : null, D = $h(n, S);
    if (D && !n.state.selection.eq(D)) {
      if (nt && Xn && n.input.lastKeyCode === 13 && Date.now() - 100 < n.input.lastKeyCodeTime && n.someProp("handleKeyDown", (I) => I(n, Gr(13, "Enter"))))
        return;
      let T = n.state.tr.setSelection(D);
      S == "pointer" ? T.setMeta("pointer", !0) : S == "key" && T.scrollIntoView(), o && T.setMeta("composition", o), n.dispatch(T);
    }
    return;
  }
  let s = n.state.doc.resolve(e), l = s.sharedDepth(t);
  e = s.before(l + 1), t = n.state.doc.resolve(t).after(l + 1);
  let a = n.state.selection, c = EA(n, e, t), d = n.state.doc, u = d.slice(c.from, c.to), h, f;
  n.input.lastKeyCode === 8 && Date.now() - 100 < n.input.lastKeyCodeTime ? (h = n.state.selection.to, f = "end") : (h = n.state.selection.from, f = "start"), n.input.lastKeyCode = null;
  let p = OA(u.content, c.doc.content, c.from, h, f);
  if (p && n.input.domChangeCount++, (so && n.input.lastIOSEnter > Date.now() - 225 || Xn) && i.some((S) => S.nodeType == 1 && !DA.test(S.nodeName)) && (!p || p.endA >= p.endB) && n.someProp("handleKeyDown", (S) => S(n, Gr(13, "Enter")))) {
    n.input.lastIOSEnter = 0;
    return;
  }
  if (!p)
    if (r && a instanceof L && !a.empty && a.$head.sameParent(a.$anchor) && !n.composing && !(c.sel && c.sel.anchor != c.sel.head))
      p = { start: a.from, endA: a.to, endB: a.to };
    else {
      if (c.sel) {
        let S = Sg(n, n.state.doc, c.sel);
        if (S && !S.eq(n.state.selection)) {
          let D = n.state.tr.setSelection(S);
          o && D.setMeta("composition", o), n.dispatch(D);
        }
      }
      return;
    }
  n.state.selection.from < n.state.selection.to && p.start == p.endB && n.state.selection instanceof L && (p.start > n.state.selection.from && p.start <= n.state.selection.from + 2 && n.state.selection.from >= c.from ? p.start = n.state.selection.from : p.endA < n.state.selection.to && p.endA >= n.state.selection.to - 2 && n.state.selection.to <= c.to && (p.endB += n.state.selection.to - p.endA, p.endA = n.state.selection.to)), kt && Ar <= 11 && p.endB == p.start + 1 && p.endA == p.start && p.start > c.from && c.doc.textBetween(p.start - c.from - 1, p.start - c.from + 1) == "  " && (p.start--, p.endA--, p.endB--);
  let m = c.doc.resolveNoCache(p.start - c.from), g = c.doc.resolveNoCache(p.endB - c.from), y = d.resolve(p.start), _ = m.sameParent(g) && m.parent.inlineContent && y.end() >= p.endA, b;
  if ((so && n.input.lastIOSEnter > Date.now() - 225 && (!_ || i.some((S) => S.nodeName == "DIV" || S.nodeName == "P")) || !_ && m.pos < c.doc.content.size && (!m.sameParent(g) || !m.parent.inlineContent) && !/\S/.test(c.doc.textBetween(m.pos, g.pos, "", "")) && (b = V.findFrom(c.doc.resolve(m.pos + 1), 1, !0)) && b.head > m.pos) && n.someProp("handleKeyDown", (S) => S(n, Gr(13, "Enter")))) {
    n.input.lastIOSEnter = 0;
    return;
  }
  if (n.state.selection.anchor > p.start && MA(d, p.start, p.endA, m, g) && n.someProp("handleKeyDown", (S) => S(n, Gr(8, "Backspace")))) {
    Xn && nt && n.domObserver.suppressSelectionUpdates();
    return;
  }
  nt && p.endB == p.start && (n.input.lastChromeDelete = Date.now()), Xn && !_ && m.start() != g.start() && g.parentOffset == 0 && m.depth == g.depth && c.sel && c.sel.anchor == c.sel.head && c.sel.head == p.endA && (p.endB -= 2, g = c.doc.resolveNoCache(p.endB - c.from), setTimeout(() => {
    n.someProp("handleKeyDown", function(S) {
      return S(n, Gr(13, "Enter"));
    });
  }, 20));
  let k = p.start, C = p.endA, w = (S) => {
    let D = S || n.state.tr.replace(k, C, c.doc.slice(p.start - c.from, p.endB - c.from));
    if (c.sel) {
      let T = Sg(n, D.doc, c.sel);
      T && !(nt && n.composing && T.empty && (p.start != p.endB || n.input.lastChromeDelete < Date.now() - 100) && (T.head == k || T.head == D.mapping.map(C) - 1) || kt && T.empty && T.head == k) && D.setSelection(T);
    }
    return o && D.setMeta("composition", o), D.scrollIntoView();
  }, x;
  if (_) {
    if (m.pos == g.pos) {
      kt && Ar <= 11 && m.parentOffset == 0 && (n.domObserver.suppressSelectionUpdates(), setTimeout(() => tr(n), 20));
      let S = w(n.state.tr.delete(k, C)), D = d.resolve(p.start).marksAcross(d.resolve(p.endA));
      D && S.ensureMarks(D), n.dispatch(S);
    } else if (
      // Adding or removing a mark
      p.endA == p.endB && (x = TA(m.parent.content.cut(m.parentOffset, g.parentOffset), y.parent.content.cut(y.parentOffset, p.endA - y.start())))
    ) {
      let S = w(n.state.tr);
      x.type == "add" ? S.addMark(k, C, x.mark) : S.removeMark(k, C, x.mark), n.dispatch(S);
    } else if (m.parent.child(m.index()).isText && m.index() == g.index() - (g.textOffset ? 0 : 1)) {
      let S = m.parent.textBetween(m.parentOffset, g.parentOffset), D = () => w(n.state.tr.insertText(S, k, C));
      n.someProp("handleTextInput", (T) => T(n, k, C, S, D)) || n.dispatch(D());
    }
  } else
    n.dispatch(w());
}
function Sg(n, e, t) {
  return Math.max(t.anchor, t.head) > e.content.size ? null : Ih(n, e.resolve(t.anchor), e.resolve(t.head));
}
function TA(n, e) {
  let t = n.firstChild.marks, r = e.firstChild.marks, i = t, o = r, s, l, a;
  for (let d = 0; d < r.length; d++)
    i = r[d].removeFromSet(i);
  for (let d = 0; d < t.length; d++)
    o = t[d].removeFromSet(o);
  if (i.length == 1 && o.length == 0)
    l = i[0], s = "add", a = (d) => d.mark(l.addToSet(d.marks));
  else if (i.length == 0 && o.length == 1)
    l = o[0], s = "remove", a = (d) => d.mark(l.removeFromSet(d.marks));
  else
    return null;
  let c = [];
  for (let d = 0; d < e.childCount; d++)
    c.push(a(e.child(d)));
  if (A.from(c).eq(n))
    return { mark: l, type: s };
}
function MA(n, e, t, r, i) {
  if (
    // The content must have shrunk
    t - e <= i.pos - r.pos || // newEnd must point directly at or after the end of the block that newStart points into
    xd(r, !0, !1) < i.pos
  )
    return !1;
  let o = n.resolve(e);
  if (!r.parent.isTextblock) {
    let l = o.nodeAfter;
    return l != null && t == e + l.nodeSize;
  }
  if (o.parentOffset < o.parent.content.size || !o.parent.isTextblock)
    return !1;
  let s = n.resolve(xd(o, !0, !0));
  return !s.parent.isTextblock || s.pos > t || xd(s, !0, !1) < t ? !1 : r.parent.content.cut(r.parentOffset).eq(s.parent.content);
}
function xd(n, e, t) {
  let r = n.depth, i = e ? n.end() : n.pos;
  for (; r > 0 && (e || n.indexAfter(r) == n.node(r).childCount); )
    r--, i++, e = !1;
  if (t) {
    let o = n.node(r).maybeChild(n.indexAfter(r));
    for (; o && !o.isLeaf; )
      o = o.firstChild, i++;
  }
  return i;
}
function OA(n, e, t, r, i) {
  let o = n.findDiffStart(e, t);
  if (o == null)
    return null;
  let { a: s, b: l } = n.findDiffEnd(e, t + n.size, t + e.size);
  if (i == "end") {
    let a = Math.max(0, o - Math.min(s, l));
    r -= s + a - o;
  }
  if (s < o && n.size < e.size) {
    let a = r <= o && r >= s ? o - r : 0;
    o -= a, o && o < e.size && Eg(e.textBetween(o - 1, o + 1)) && (o += a ? 1 : -1), l = o + (l - s), s = o;
  } else if (l < o) {
    let a = r <= o && r >= l ? o - r : 0;
    o -= a, o && o < n.size && Eg(n.textBetween(o - 1, o + 1)) && (o += a ? 1 : -1), s = o + (s - l), l = o;
  }
  return { start: o, endA: s, endB: l };
}
function Eg(n) {
  if (n.length != 2)
    return !1;
  let e = n.charCodeAt(0), t = n.charCodeAt(1);
  return e >= 56320 && e <= 57343 && t >= 55296 && t <= 56319;
}
class Vh {
  /**
  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(e, t) {
    this._root = null, this.focused = !1, this.trackWrites = null, this.mounted = !1, this.markCursor = null, this.cursorWrapper = null, this.lastSelectedViewDesc = void 0, this.input = new YD(), this.prevDirectPlugins = [], this.pluginViews = [], this.requiresGeckoHackNode = !1, this.dragging = null, this._props = t, this.state = t.state, this.directPlugins = t.plugins || [], this.directPlugins.forEach(Mg), this.dispatch = this.dispatch.bind(this), this.dom = e && e.mount || document.createElement("div"), e && (e.appendChild ? e.appendChild(this.dom) : typeof e == "function" ? e(this.dom) : e.mount && (this.mounted = !0)), this.editable = Ag(this), Dg(this), this.nodeViews = Tg(this), this.docView = sg(this.state.doc, xg(this), Ed(this), this.dom, this), this.domObserver = new kA(this, (r, i, o, s) => AA(this, r, i, o, s)), this.domObserver.start(), XD(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 e = this._props;
      this._props = {};
      for (let t in e)
        this._props[t] = e[t];
      this._props.state = this.state;
    }
    return this._props;
  }
  /**
  Update the view's props. Will immediately cause an update to
  the DOM.
  */
  update(e) {
    e.handleDOMEvents != this._props.handleDOMEvents && Ou(this);
    let t = this._props;
    this._props = e, e.plugins && (e.plugins.forEach(Mg), this.directPlugins = e.plugins), this.updateStateInner(e.state, t);
  }
  /**
  Update the view by updating existing props object with the object
  given as argument. Equivalent to `view.update(Object.assign({},
  view.props, props))`.
  */
  setProps(e) {
    let t = {};
    for (let r in this._props)
      t[r] = this._props[r];
    t.state = this.state;
    for (let r in e)
      t[r] = e[r];
    this.update(t);
  }
  /**
  Update the editor's `state` prop, without touching any of the
  other props.
  */
  updateState(e) {
    this.updateStateInner(e, this._props);
  }
  updateStateInner(e, t) {
    var r;
    let i = this.state, o = !1, s = !1;
    e.storedMarks && this.composing && (__(this), s = !0), this.state = e;
    let l = i.plugins != e.plugins || this._props.plugins != t.plugins;
    if (l || this._props.plugins != t.plugins || this._props.nodeViews != t.nodeViews) {
      let f = Tg(this);
      NA(f, this.nodeViews) && (this.nodeViews = f, o = !0);
    }
    (l || t.handleDOMEvents != this._props.handleDOMEvents) && Ou(this), this.editable = Ag(this), Dg(this);
    let a = Ed(this), c = xg(this), d = i.plugins != e.plugins && !i.doc.eq(e.doc) ? "reset" : e.scrollToSelection > i.scrollToSelection ? "to selection" : "preserve", u = o || !this.docView.matchesNode(e.doc, c, a);
    (u || !e.selection.eq(i.selection)) && (s = !0);
    let h = d == "preserve" && s && this.dom.style.overflowAnchor == null && uD(this);
    if (s) {
      this.domObserver.stop();
      let f = u && (kt || nt) && !this.composing && !i.selection.empty && !e.selection.empty && FA(i.selection, e.selection);
      if (u) {
        let p = nt ? this.trackWrites = this.domSelectionRange().focusNode : null;
        this.composing && (this.input.compositionNode = dA(this)), (o || !this.docView.update(e.doc, c, a, this)) && (this.docView.updateOuterDeco(c), this.docView.destroy(), this.docView = sg(e.doc, c, a, this.dom, this)), p && !this.trackWrites && (f = !0);
      }
      f || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && ID(this)) ? tr(this, f) : (l_(this, e.selection), this.domObserver.setCurSelection()), this.domObserver.start();
    }
    this.updatePluginViews(i), !((r = this.dragging) === null || r === void 0) && r.node && !i.doc.eq(e.doc) && this.updateDraggedNode(this.dragging, i), d == "reset" ? this.dom.scrollTop = 0 : d == "to selection" ? this.scrollToSelection() : h && hD(h);
  }
  /**
  @internal
  */
  scrollToSelection() {
    let e = this.domSelectionRange().focusNode;
    if (!(!e || !this.dom.contains(e.nodeType == 1 ? e : e.parentNode))) {
      if (!this.someProp("handleScrollToSelection", (t) => t(this))) if (this.state.selection instanceof P) {
        let t = this.docView.domAfterPos(this.state.selection.from);
        t.nodeType == 1 && eg(this, t.getBoundingClientRect(), e);
      } else
        eg(this, this.coordsAtPos(this.state.selection.head, 1), e);
    }
  }
  destroyPluginViews() {
    let e;
    for (; e = this.pluginViews.pop(); )
      e.destroy && e.destroy();
  }
  updatePluginViews(e) {
    if (!e || e.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
      this.prevDirectPlugins = this.directPlugins, this.destroyPluginViews();
      for (let t = 0; t < this.directPlugins.length; t++) {
        let r = this.directPlugins[t];
        r.spec.view && this.pluginViews.push(r.spec.view(this));
      }
      for (let t = 0; t < this.state.plugins.length; t++) {
        let r = this.state.plugins[t];
        r.spec.view && this.pluginViews.push(r.spec.view(this));
      }
    } else
      for (let t = 0; t < this.pluginViews.length; t++) {
        let r = this.pluginViews[t];
        r.update && r.update(this, e);
      }
  }
  updateDraggedNode(e, t) {
    let r = e.node, i = -1;
    if (this.state.doc.nodeAt(r.from) == r.node)
      i = r.from;
    else {
      let o = r.from + (this.state.doc.content.size - t.doc.content.size);
      (o > 0 && this.state.doc.nodeAt(o)) == r.node && (i = o);
    }
    this.dragging = new k_(e.slice, e.move, i < 0 ? void 0 : P.create(this.state.doc, i));
  }
  someProp(e, t) {
    let r = this._props && this._props[e], i;
    if (r != null && (i = t ? t(r) : r))
      return i;
    for (let s = 0; s < this.directPlugins.length; s++) {
      let l = this.directPlugins[s].props[e];
      if (l != null && (i = t ? t(l) : l))
        return i;
    }
    let o = this.state.plugins;
    if (o)
      for (let s = 0; s < o.length; s++) {
        let l = o[s].props[e];
        if (l != null && (i = t ? t(l) : l))
          return i;
      }
  }
  /**
  Query whether the view has focus.
  */
  hasFocus() {
    if (kt) {
      let e = this.root.activeElement;
      if (e == this.dom)
        return !0;
      if (!e || !this.dom.contains(e))
        return !1;
      for (; e && this.dom != e && this.dom.contains(e); ) {
        if (e.contentEditable == "false")
          return !1;
        e = e.parentElement;
      }
      return !0;
    }
    return this.root.activeElement == this.dom;
  }
  /**
  Focus the editor.
  */
  focus() {
    this.domObserver.stop(), this.editable && fD(this.dom), tr(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 e = this._root;
    if (e == null) {
      for (let t = this.dom.parentNode; t; t = t.parentNode)
        if (t.nodeType == 9 || t.nodeType == 11 && t.host)
          return t.getSelection || (Object.getPrototypeOf(t).getSelection = () => t.ownerDocument.getSelection()), this._root = t;
    }
    return e || 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(e) {
    return yD(this, e);
  }
  /**
  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(e, t = 1) {
    return Qy(this, e, t);
  }
  /**
  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(e, t = 0) {
    return this.docView.domFromPos(e, t);
  }
  /**
  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(e) {
    let t = this.docView.descAt(e);
    return t ? t.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(e, t, r = -1) {
    let i = this.docView.posFromDOM(e, t, r);
    if (i == null)
      throw new RangeError("DOM position not inside the editor");
    return i;
  }
  /**
  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(e, t) {
    return CD(this, t || this.state, e);
  }
  /**
  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(e, t) {
    return ms(this, "", e, !1, t || new ClipboardEvent("paste"));
  }
  /**
  Run the editor's paste logic with the given plain-text input.
  */
  pasteText(e, t) {
    return ms(this, e, null, !0, t || 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(e) {
    return Lh(this, e);
  }
  /**
  Removes the editor from the DOM and destroys all [node
  views](https://prosemirror.net/docs/ref/#view.NodeView).
  */
  destroy() {
    this.docView && (ZD(this), this.destroyPluginViews(), this.mounted ? (this.docView.update(this.state.doc, [], Ed(this), this), this.dom.textContent = "") : this.dom.parentNode && this.dom.parentNode.removeChild(this.dom), this.docView.destroy(), this.docView = null, eD());
  }
  /**
  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(e) {
    return eA(this, e);
  }
  /**
  @internal
  */
  domSelectionRange() {
    let e = this.domSelection();
    return e ? ht && this.root.nodeType === 11 && oD(this.dom.ownerDocument) == this.dom && CA(this, e) || e : { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };
  }
  /**
  @internal
  */
  domSelection() {
    return this.root.getSelection();
  }
}
Vh.prototype.dispatch = function(n) {
  let e = this._props.dispatchTransaction;
  e ? e.call(this, n) : this.updateState(this.state.apply(n));
};
function xg(n) {
  let e = /* @__PURE__ */ Object.create(null);
  return e.class = "ProseMirror", e.contenteditable = String(n.editable), n.someProp("attributes", (t) => {
    if (typeof t == "function" && (t = t(n.state)), t)
      for (let r in t)
        r == "class" ? e.class += " " + t[r] : r == "style" ? e.style = (e.style ? e.style + ";" : "") + t[r] : !e[r] && r != "contenteditable" && r != "nodeName" && (e[r] = String(t[r]));
  }), e.translate || (e.translate = "no"), [se.node(0, n.state.doc.content.size, e)];
}
function Dg(n) {
  if (n.markCursor) {
    let e = document.createElement("img");
    e.className = "ProseMirror-separator", e.setAttribute("mark-placeholder", "true"), e.setAttribute("alt", ""), n.cursorWrapper = { dom: e, deco: se.widget(n.state.selection.from, e, { raw: !0, marks: n.markCursor }) };
  } else
    n.cursorWrapper = null;
}
function Ag(n) {
  return !n.someProp("editable", (e) => e(n.state) === !1);
}
function FA(n, e) {
  let t = Math.min(n.$anchor.sharedDepth(n.head), e.$anchor.sharedDepth(e.head));
  return n.$anchor.start(t) != e.$anchor.start(t);
}
function Tg(n) {
  let e = /* @__PURE__ */ Object.create(null);
  function t(r) {
    for (let i in r)
      Object.prototype.hasOwnProperty.call(e, i) || (e[i] = r[i]);
  }
  return n.someProp("nodeViews", t), n.someProp("markViews", t), e;
}
function NA(n, e) {
  let t = 0, r = 0;
  for (let i in n) {
    if (n[i] != e[i])
      return !0;
    t++;
  }
  for (let i in e)
    r++;
  return t != r;
}
function Mg(n) {
  if (n.spec.state || n.spec.filterTransaction || n.spec.appendTransaction)
    throw new RangeError("Plugins passed directly to the view must not have a state component");
}
var Or = {
  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: "'"
}, ka = {
  48: ")",
  49: "!",
  50: "@",
  51: "#",
  52: "$",
  53: "%",
  54: "^",
  55: "&",
  56: "*",
  57: "(",
  59: ":",
  61: "+",
  173: "_",
  186: ":",
  187: "+",
  188: "<",
  189: "_",
  190: ">",
  191: "?",
  192: "~",
  219: "{",
  220: "|",
  221: "}",
  222: '"'
}, $A = typeof navigator < "u" && /Mac/.test(navigator.platform), IA = typeof navigator < "u" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
for (var Ke = 0; Ke < 10; Ke++) Or[48 + Ke] = Or[96 + Ke] = String(Ke);
for (var Ke = 1; Ke <= 24; Ke++) Or[Ke + 111] = "F" + Ke;
for (var Ke = 65; Ke <= 90; Ke++)
  Or[Ke] = String.fromCharCode(Ke + 32), ka[Ke] = String.fromCharCode(Ke);
for (var Dd in Or) ka.hasOwnProperty(Dd) || (ka[Dd] = Or[Dd]);
function LA(n) {
  var e = $A && n.metaKey && n.shiftKey && !n.ctrlKey && !n.altKey || IA && n.shiftKey && n.key && n.key.length == 1 || n.key == "Unidentified", t = !e && n.key || (n.shiftKey ? ka : Or)[n.keyCode] || n.key || "Unidentified";
  return t == "Esc" && (t = "Escape"), t == "Del" && (t = "Delete"), t == "Left" && (t = "ArrowLeft"), t == "Up" && (t = "ArrowUp"), t == "Right" && (t = "ArrowRight"), t == "Down" && (t = "ArrowDown"), t;
}
const RA = typeof navigator < "u" && /Mac|iP(hone|[oa]d)/.test(navigator.platform), BA = typeof navigator < "u" && /Win/.test(navigator.platform);
function PA(n) {
  let e = n.split(/-(?!$)/), t = e[e.length - 1];
  t == "Space" && (t = " ");
  let r, i, o, s;
  for (let l = 0; l < e.length - 1; l++) {
    let a = e[l];
    if (/^(cmd|meta|m)$/i.test(a))
      s = !0;
    else if (/^a(lt)?$/i.test(a))
      r = !0;
    else if (/^(c|ctrl|control)$/i.test(a))
      i = !0;
    else if (/^s(hift)?$/i.test(a))
      o = !0;
    else if (/^mod$/i.test(a))
      RA ? s = !0 : i = !0;
    else
      throw new Error("Unrecognized modifier name: " + a);
  }
  return r && (t = "Alt-" + t), i && (t = "Ctrl-" + t), s && (t = "Meta-" + t), o && (t = "Shift-" + t), t;
}
function zA(n) {
  let e = /* @__PURE__ */ Object.create(null);
  for (let t in n)
    e[PA(t)] = n[t];
  return e;
}
function Ad(n, e, t = !0) {
  return e.altKey && (n = "Alt-" + n), e.ctrlKey && (n = "Ctrl-" + n), e.metaKey && (n = "Meta-" + n), t && e.shiftKey && (n = "Shift-" + n), n;
}
function HA(n) {
  return new G({ props: { handleKeyDown: Uh(n) } });
}
function Uh(n) {
  let e = zA(n);
  return function(t, r) {
    let i = LA(r), o, s = e[Ad(i, r)];
    if (s && s(t.state, t.dispatch, t))
      return !0;
    if (i.length == 1 && i != " ") {
      if (r.shiftKey) {
        let l = e[Ad(i, r, !1)];
        if (l && l(t.state, t.dispatch, t))
          return !0;
      }
      if ((r.altKey || r.metaKey || r.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
      !(BA && r.ctrlKey && r.altKey) && (o = Or[r.keyCode]) && o != i) {
        let l = e[Ad(o, r)];
        if (l && l(t.state, t.dispatch, t))
          return !0;
      }
    }
    return !1;
  };
}
const qh = (n, e) => n.selection.empty ? !1 : (e && e(n.tr.deleteSelection().scrollIntoView()), !0);
function x_(n, e) {
  let { $cursor: t } = n.selection;
  return !t || (e ? !e.endOfTextblock("backward", n) : t.parentOffset > 0) ? null : t;
}
const D_ = (n, e, t) => {
  let r = x_(n, t);
  if (!r)
    return !1;
  let i = jh(r);
  if (!i) {
    let s = r.blockRange(), l = s && go(s);
    return l == null ? !1 : (e && e(n.tr.lift(s, l).scrollIntoView()), !0);
  }
  let o = i.nodeBefore;
  if (L_(n, i, e, -1))
    return !0;
  if (r.parent.content.size == 0 && (lo(o, "end") || P.isSelectable(o)))
    for (let s = r.depth; ; s--) {
      let l = fc(n.doc, r.before(s), r.after(s), O.empty);
      if (l && l.slice.size < l.to - l.from) {
        if (e) {
          let a = n.tr.step(l);
          a.setSelection(lo(o, "end") ? V.findFrom(a.doc.resolve(a.mapping.map(i.pos, -1)), -1) : P.create(a.doc, i.pos - o.nodeSize)), e(a.scrollIntoView());
        }
        return !0;
      }
      if (s == 1 || r.node(s - 1).childCount > 1)
        break;
    }
  return o.isAtom && i.depth == r.depth - 1 ? (e && e(n.tr.delete(i.pos - o.nodeSize, i.pos).scrollIntoView()), !0) : !1;
}, VA = (n, e, t) => {
  let r = x_(n, t);
  if (!r)
    return !1;
  let i = jh(r);
  return i ? A_(n, i, e) : !1;
}, UA = (n, e, t) => {
  let r = M_(n, t);
  if (!r)
    return !1;
  let i = Wh(r);
  return i ? A_(n, i, e) : !1;
};
function A_(n, e, t) {
  let r = e.nodeBefore, i = r, o = e.pos - 1;
  for (; !i.isTextblock; o--) {
    if (i.type.spec.isolating)
      return !1;
    let d = i.lastChild;
    if (!d)
      return !1;
    i = d;
  }
  let s = e.nodeAfter, l = s, a = e.pos + 1;
  for (; !l.isTextblock; a++) {
    if (l.type.spec.isolating)
      return !1;
    let d = l.firstChild;
    if (!d)
      return !1;
    l = d;
  }
  let c = fc(n.doc, o, a, O.empty);
  if (!c || c.from != o || c instanceof Me && c.slice.size >= a - o)
    return !1;
  if (t) {
    let d = n.tr.step(c);
    d.setSelection(L.create(d.doc, o)), t(d.scrollIntoView());
  }
  return !0;
}
function lo(n, e, t = !1) {
  for (let r = n; r; r = e == "start" ? r.firstChild : r.lastChild) {
    if (r.isTextblock)
      return !0;
    if (t && r.childCount != 1)
      return !1;
  }
  return !1;
}
const T_ = (n, e, t) => {
  let { $head: r, empty: i } = n.selection, o = r;
  if (!i)
    return !1;
  if (r.parent.isTextblock) {
    if (t ? !t.endOfTextblock("backward", n) : r.parentOffset > 0)
      return !1;
    o = jh(r);
  }
  let s = o && o.nodeBefore;
  return !s || !P.isSelectable(s) ? !1 : (e && e(n.tr.setSelection(P.create(n.doc, o.pos - s.nodeSize)).scrollIntoView()), !0);
};
function jh(n) {
  if (!n.parent.type.spec.isolating)
    for (let e = n.depth - 1; e >= 0; e--) {
      if (n.index(e) > 0)
        return n.doc.resolve(n.before(e + 1));
      if (n.node(e).type.spec.isolating)
        break;
    }
  return null;
}
function M_(n, e) {
  let { $cursor: t } = n.selection;
  return !t || (e ? !e.endOfTextblock("forward", n) : t.parentOffset < t.parent.content.size) ? null : t;
}
const O_ = (n, e, t) => {
  let r = M_(n, t);
  if (!r)
    return !1;
  let i = Wh(r);
  if (!i)
    return !1;
  let o = i.nodeAfter;
  if (L_(n, i, e, 1))
    return !0;
  if (r.parent.content.size == 0 && (lo(o, "start") || P.isSelectable(o))) {
    let s = fc(n.doc, r.before(), r.after(), O.empty);
    if (s && s.slice.size < s.to - s.from) {
      if (e) {
        let l = n.tr.step(s);
        l.setSelection(lo(o, "start") ? V.findFrom(l.doc.resolve(l.mapping.map(i.pos)), 1) : P.create(l.doc, l.mapping.map(i.pos))), e(l.scrollIntoView());
      }
      return !0;
    }
  }
  return o.isAtom && i.depth == r.depth - 1 ? (e && e(n.tr.delete(i.pos, i.pos + o.nodeSize).scrollIntoView()), !0) : !1;
}, F_ = (n, e, t) => {
  let { $head: r, empty: i } = n.selection, o = r;
  if (!i)
    return !1;
  if (r.parent.isTextblock) {
    if (t ? !t.endOfTextblock("forward", n) : r.parentOffset < r.parent.content.size)
      return !1;
    o = Wh(r);
  }
  let s = o && o.nodeAfter;
  return !s || !P.isSelectable(s) ? !1 : (e && e(n.tr.setSelection(P.create(n.doc, o.pos)).scrollIntoView()), !0);
};
function Wh(n) {
  if (!n.parent.type.spec.isolating)
    for (let e = n.depth - 1; e >= 0; e--) {
      let t = n.node(e);
      if (n.index(e) + 1 < t.childCount)
        return n.doc.resolve(n.after(e + 1));
      if (t.type.spec.isolating)
        break;
    }
  return null;
}
const qA = (n, e) => {
  let t = n.selection, r = t instanceof P, i;
  if (r) {
    if (t.node.isTextblock || !Ei(n.doc, t.from))
      return !1;
    i = t.from;
  } else if (i = hc(n.doc, t.from, -1), i == null)
    return !1;
  if (e) {
    let o = n.tr.join(i);
    r && o.setSelection(P.create(o.doc, i - n.doc.resolve(i).nodeBefore.nodeSize)), e(o.scrollIntoView());
  }
  return !0;
}, jA = (n, e) => {
  let t = n.selection, r;
  if (t instanceof P) {
    if (t.node.isTextblock || !Ei(n.doc, t.to))
      return !1;
    r = t.to;
  } else if (r = hc(n.doc, t.to, 1), r == null)
    return !1;
  return e && e(n.tr.join(r).scrollIntoView()), !0;
}, WA = (n, e) => {
  let { $from: t, $to: r } = n.selection, i = t.blockRange(r), o = i && go(i);
  return o == null ? !1 : (e && e(n.tr.lift(i, o).scrollIntoView()), !0);
}, N_ = (n, e) => {
  let { $head: t, $anchor: r } = n.selection;
  return !t.parent.type.spec.code || !t.sameParent(r) ? !1 : (e && e(n.tr.insertText(`
`).scrollIntoView()), !0);
};
function Gh(n) {
  for (let e = 0; e < n.edgeCount; e++) {
    let { type: t } = n.edge(e);
    if (t.isTextblock && !t.hasRequiredAttrs())
      return t;
  }
  return null;
}
const GA = (n, e) => {
  let { $head: t, $anchor: r } = n.selection;
  if (!t.parent.type.spec.code || !t.sameParent(r))
    return !1;
  let i = t.node(-1), o = t.indexAfter(-1), s = Gh(i.contentMatchAt(o));
  if (!s || !i.canReplaceWith(o, o, s))
    return !1;
  if (e) {
    let l = t.after(), a = n.tr.replaceWith(l, l, s.createAndFill());
    a.setSelection(V.near(a.doc.resolve(l), 1)), e(a.scrollIntoView());
  }
  return !0;
}, $_ = (n, e) => {
  let t = n.selection, { $from: r, $to: i } = t;
  if (t instanceof wt || r.parent.inlineContent || i.parent.inlineContent)
    return !1;
  let o = Gh(i.parent.contentMatchAt(i.indexAfter()));
  if (!o || !o.isTextblock)
    return !1;
  if (e) {
    let s = (!r.parentOffset && i.index() < i.parent.childCount ? r : i).pos, l = n.tr.insert(s, o.createAndFill());
    l.setSelection(L.create(l.doc, s + 1)), e(l.scrollIntoView());
  }
  return !0;
}, I_ = (n, e) => {
  let { $cursor: t } = n.selection;
  if (!t || t.parent.content.size)
    return !1;
  if (t.depth > 1 && t.after() != t.end(-1)) {
    let o = t.before();
    if (er(n.doc, o))
      return e && e(n.tr.split(o).scrollIntoView()), !0;
  }
  let r = t.blockRange(), i = r && go(r);
  return i == null ? !1 : (e && e(n.tr.lift(r, i).scrollIntoView()), !0);
};
function KA(n) {
  return (e, t) => {
    let { $from: r, $to: i } = e.selection;
    if (e.selection instanceof P && e.selection.node.isBlock)
      return !r.parentOffset || !er(e.doc, r.pos) ? !1 : (t && t(e.tr.split(r.pos).scrollIntoView()), !0);
    if (!r.depth)
      return !1;
    let o = [], s, l, a = !1, c = !1;
    for (let f = r.depth; ; f--)
      if (r.node(f).isBlock) {
        a = r.end(f) == r.pos + (r.depth - f), c = r.start(f) == r.pos - (r.depth - f), l = Gh(r.node(f - 1).contentMatchAt(r.indexAfter(f - 1))), o.unshift(a && l ? { type: l } : null), s = f;
        break;
      } else {
        if (f == 1)
          return !1;
        o.unshift(null);
      }
    let d = e.tr;
    (e.selection instanceof L || e.selection instanceof wt) && d.deleteSelection();
    let u = d.mapping.map(r.pos), h = er(d.doc, u, o.length, o);
    if (h || (o[0] = l ? { type: l } : null, h = er(d.doc, u, o.length, o)), !h)
      return !1;
    if (d.split(u, o.length, o), !a && c && r.node(s).type != l) {
      let f = d.mapping.map(r.before(s)), p = d.doc.resolve(f);
      l && r.node(s - 1).canReplaceWith(p.index(), p.index() + 1, l) && d.setNodeMarkup(d.mapping.map(r.before(s)), l);
    }
    return t && t(d.scrollIntoView()), !0;
  };
}
const JA = KA(), YA = (n, e) => {
  let { $from: t, to: r } = n.selection, i, o = t.sharedDepth(r);
  return o == 0 ? !1 : (i = t.before(o), e && e(n.tr.setSelection(P.create(n.doc, i))), !0);
};
function XA(n, e, t) {
  let r = e.nodeBefore, i = e.nodeAfter, o = e.index();
  return !r || !i || !r.type.compatibleContent(i.type) ? !1 : !r.content.size && e.parent.canReplace(o - 1, o) ? (t && t(n.tr.delete(e.pos - r.nodeSize, e.pos).scrollIntoView()), !0) : !e.parent.canReplace(o, o + 1) || !(i.isTextblock || Ei(n.doc, e.pos)) ? !1 : (t && t(n.tr.join(e.pos).scrollIntoView()), !0);
}
function L_(n, e, t, r) {
  let i = e.nodeBefore, o = e.nodeAfter, s, l, a = i.type.spec.isolating || o.type.spec.isolating;
  if (!a && XA(n, e, t))
    return !0;
  let c = !a && e.parent.canReplace(e.index(), e.index() + 1);
  if (c && (s = (l = i.contentMatchAt(i.childCount)).findWrapping(o.type)) && l.matchType(s[0] || o.type).validEnd) {
    if (t) {
      let f = e.pos + o.nodeSize, p = A.empty;
      for (let y = s.length - 1; y >= 0; y--)
        p = A.from(s[y].create(null, p));
      p = A.from(i.copy(p));
      let m = n.tr.step(new Ae(e.pos - 1, f, e.pos, f, new O(p, 1, 0), s.length, !0)), g = m.doc.resolve(f + 2 * s.length);
      g.nodeAfter && g.nodeAfter.type == i.type && Ei(m.doc, g.pos) && m.join(g.pos), t(m.scrollIntoView());
    }
    return !0;
  }
  let d = o.type.spec.isolating || r > 0 && a ? null : V.findFrom(e, 1), u = d && d.$from.blockRange(d.$to), h = u && go(u);
  if (h != null && h >= e.depth)
    return t && t(n.tr.lift(u, h).scrollIntoView()), !0;
  if (c && lo(o, "start", !0) && lo(i, "end")) {
    let f = i, p = [];
    for (; p.push(f), !f.isTextblock; )
      f = f.lastChild;
    let m = o, g = 1;
    for (; !m.isTextblock; m = m.firstChild)
      g++;
    if (f.canReplace(f.childCount, f.childCount, m.content)) {
      if (t) {
        let y = A.empty;
        for (let b = p.length - 1; b >= 0; b--)
          y = A.from(p[b].copy(y));
        let _ = n.tr.step(new Ae(e.pos - p.length, e.pos + o.nodeSize, e.pos + g, e.pos + o.nodeSize - g, new O(y, p.length, 0), 0, !0));
        t(_.scrollIntoView());
      }
      return !0;
    }
  }
  return !1;
}
function R_(n) {
  return function(e, t) {
    let r = e.selection, i = n < 0 ? r.$from : r.$to, o = i.depth;
    for (; i.node(o).isInline; ) {
      if (!o)
        return !1;
      o--;
    }
    return i.node(o).isTextblock ? (t && t(e.tr.setSelection(L.create(e.doc, n < 0 ? i.start(o) : i.end(o)))), !0) : !1;
  };
}
const ZA = R_(-1), QA = R_(1);
function eT(n, e = null) {
  return function(t, r) {
    let { $from: i, $to: o } = t.selection, s = i.blockRange(o), l = s && Iy(s, n, e);
    return l ? (r && r(t.tr.wrap(s, l).scrollIntoView()), !0) : !1;
  };
}
function Og(n, e = null) {
  return function(t, r) {
    let i = !1;
    for (let o = 0; o < t.selection.ranges.length && !i; o++) {
      let { $from: { pos: s }, $to: { pos: l } } = t.selection.ranges[o];
      t.doc.nodesBetween(s, l, (a, c) => {
        if (i)
          return !1;
        if (!(!a.isTextblock || a.hasMarkup(n, e)))
          if (a.type == n)
            i = !0;
          else {
            let d = t.doc.resolve(c), u = d.index();
            i = d.parent.canReplaceWith(u, u + 1, n);
          }
      });
    }
    if (!i)
      return !1;
    if (r) {
      let o = t.tr;
      for (let s = 0; s < t.selection.ranges.length; s++) {
        let { $from: { pos: l }, $to: { pos: a } } = t.selection.ranges[s];
        o.setBlockType(l, a, n, e);
      }
      r(o.scrollIntoView());
    }
    return !0;
  };
}
function Kh(...n) {
  return function(e, t, r) {
    for (let i = 0; i < n.length; i++)
      if (n[i](e, t, r))
        return !0;
    return !1;
  };
}
Kh(qh, D_, T_);
Kh(qh, O_, F_);
Kh(N_, $_, I_, JA);
typeof navigator < "u" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os < "u" && os.platform && os.platform() == "darwin";
function tT(n, e = null) {
  return function(t, r) {
    let { $from: i, $to: o } = t.selection, s = i.blockRange(o);
    if (!s)
      return !1;
    let l = r ? t.tr : null;
    return nT(l, s, n, e) ? (r && r(l.scrollIntoView()), !0) : !1;
  };
}
function nT(n, e, t, r = null) {
  let i = !1, o = e, s = e.$from.doc;
  if (e.depth >= 2 && e.$from.node(e.depth - 1).type.compatibleContent(t) && e.startIndex == 0) {
    if (e.$from.index(e.depth - 1) == 0)
      return !1;
    let a = s.resolve(e.start - 2);
    o = new pa(a, a, e.depth), e.endIndex < e.parent.childCount && (e = new pa(e.$from, s.resolve(e.$to.end(e.depth)), e.depth)), i = !0;
  }
  let l = Iy(o, t, r, e);
  return l ? (n && rT(n, e, l, i, t), !0) : !1;
}
function rT(n, e, t, r, i) {
  let o = A.empty;
  for (let d = t.length - 1; d >= 0; d--)
    o = A.from(t[d].type.create(t[d].attrs, o));
  n.step(new Ae(e.start - (r ? 2 : 0), e.end, e.start, e.end, new O(o, 0, 0), t.length, !0));
  let s = 0;
  for (let d = 0; d < t.length; d++)
    t[d].type == i && (s = d + 1);
  let l = t.length - s, a = e.start + t.length - (r ? 2 : 0), c = e.parent;
  for (let d = e.startIndex, u = e.endIndex, h = !0; d < u; d++, h = !1)
    !h && er(n.doc, a, l) && (n.split(a, l), a += 2 * l), a += c.child(d).nodeSize;
  return n;
}
function iT(n) {
  return function(e, t) {
    let { $from: r, $to: i } = e.selection, o = r.blockRange(i, (s) => s.childCount > 0 && s.firstChild.type == n);
    return o ? t ? r.node(o.depth - 1).type == n ? oT(e, t, n, o) : sT(e, t, o) : !0 : !1;
  };
}
function oT(n, e, t, r) {
  let i = n.tr, o = r.end, s = r.$to.end(r.depth);
  o < s && (i.step(new Ae(o - 1, s, o, s, new O(A.from(t.create(null, r.parent.copy())), 1, 0), 1, !0)), r = new pa(i.doc.resolve(r.$from.pos), i.doc.resolve(s), r.depth));
  const l = go(r);
  if (l == null)
    return !1;
  i.lift(r, l);
  let a = i.doc.resolve(i.mapping.map(o, -1) - 1);
  return Ei(i.doc, a.pos) && a.nodeBefore.type == a.nodeAfter.type && i.join(a.pos), e(i.scrollIntoView()), !0;
}
function sT(n, e, t) {
  let r = n.tr, i = t.parent;
  for (let f = t.end, p = t.endIndex - 1, m = t.startIndex; p > m; p--)
    f -= i.child(p).nodeSize, r.delete(f - 1, f + 1);
  let o = r.doc.resolve(t.start), s = o.nodeAfter;
  if (r.mapping.map(t.end) != t.start + o.nodeAfter.nodeSize)
    return !1;
  let l = t.startIndex == 0, a = t.endIndex == i.childCount, c = o.node(-1), d = o.index(-1);
  if (!c.canReplace(d + (l ? 0 : 1), d + 1, s.content.append(a ? A.empty : A.from(i))))
    return !1;
  let u = o.pos, h = u + s.nodeSize;
  return r.step(new Ae(u - (l ? 1 : 0), h + (a ? 1 : 0), u + 1, h - 1, new O((l ? A.empty : A.from(i.copy(A.empty))).append(a ? A.empty : A.from(i.copy(A.empty))), l ? 0 : 1, a ? 0 : 1), l ? 0 : 1)), e(r.scrollIntoView()), !0;
}
function lT(n) {
  return function(e, t) {
    let { $from: r, $to: i } = e.selection, o = r.blockRange(i, (c) => c.childCount > 0 && c.firstChild.type == n);
    if (!o)
      return !1;
    let s = o.startIndex;
    if (s == 0)
      return !1;
    let l = o.parent, a = l.child(s - 1);
    if (a.type != n)
      return !1;
    if (t) {
      let c = a.lastChild && a.lastChild.type == l.type, d = A.from(c ? n.create() : null), u = new O(A.from(n.create(null, A.from(l.type.create(null, d)))), c ? 3 : 1, 0), h = o.start, f = o.end;
      t(e.tr.step(new Ae(h - (c ? 3 : 1), f, h, f, u, 1, !0)).scrollIntoView());
    }
    return !0;
  };
}
function yc(n) {
  const { state: e, transaction: t } = n;
  let { selection: r } = t, { doc: i } = t, { storedMarks: o } = t;
  return {
    ...e,
    apply: e.apply.bind(e),
    applyTransaction: e.applyTransaction.bind(e),
    plugins: e.plugins,
    schema: e.schema,
    reconfigure: e.reconfigure.bind(e),
    toJSON: e.toJSON.bind(e),
    get storedMarks() {
      return o;
    },
    get selection() {
      return r;
    },
    get doc() {
      return i;
    },
    get tr() {
      return r = t.selection, i = t.doc, o = t.storedMarks, t;
    }
  };
}
class _c {
  constructor(e) {
    this.editor = e.editor, this.rawCommands = this.editor.extensionManager.commands, this.customState = e.state;
  }
  get hasCustomState() {
    return !!this.customState;
  }
  get state() {
    return this.customState || this.editor.state;
  }
  get commands() {
    const { rawCommands: e, editor: t, state: r } = this, { view: i } = t, { tr: o } = r, s = this.buildProps(o);
    return Object.fromEntries(Object.entries(e).map(([l, a]) => [l, (...d) => {
      const u = a(...d)(s);
      return !o.getMeta("preventDispatch") && !this.hasCustomState && i.dispatch(o), u;
    }]));
  }
  get chain() {
    return () => this.createChain();
  }
  get can() {
    return () => this.createCan();
  }
  createChain(e, t = !0) {
    const { rawCommands: r, editor: i, state: o } = this, { view: s } = i, l = [], a = !!e, c = e || o.tr, d = () => (!a && t && !c.getMeta("preventDispatch") && !this.hasCustomState && s.dispatch(c), l.every((h) => h === !0)), u = {
      ...Object.fromEntries(Object.entries(r).map(([h, f]) => [h, (...m) => {
        const g = this.buildProps(c, t), y = f(...m)(g);
        return l.push(y), u;
      }])),
      run: d
    };
    return u;
  }
  createCan(e) {
    const { rawCommands: t, state: r } = this, i = !1, o = e || r.tr, s = this.buildProps(o, i);
    return {
      ...Object.fromEntries(Object.entries(t).map(([a, c]) => [a, (...d) => c(...d)({ ...s, dispatch: void 0 })])),
      chain: () => this.createChain(o, i)
    };
  }
  buildProps(e, t = !0) {
    const { rawCommands: r, editor: i, state: o } = this, { view: s } = i, l = {
      tr: e,
      editor: i,
      view: s,
      state: yc({
        state: o,
        transaction: e
      }),
      dispatch: t ? () => {
      } : void 0,
      chain: () => this.createChain(e, t),
      can: () => this.createCan(e),
      get commands() {
        return Object.fromEntries(Object.entries(r).map(([a, c]) => [a, (...d) => c(...d)(l)]));
      }
    };
    return l;
  }
}
class aT {
  constructor() {
    this.callbacks = {};
  }
  on(e, t) {
    return this.callbacks[e] || (this.callbacks[e] = []), this.callbacks[e].push(t), this;
  }
  emit(e, ...t) {
    const r = this.callbacks[e];
    return r && r.forEach((i) => i.apply(this, t)), this;
  }
  off(e, t) {
    const r = this.callbacks[e];
    return r && (t ? this.callbacks[e] = r.filter((i) => i !== t) : delete this.callbacks[e]), this;
  }
  once(e, t) {
    const r = (...i) => {
      this.off(e, r), t.apply(this, i);
    };
    return this.on(e, r);
  }
  removeAllListeners() {
    this.callbacks = {};
  }
}
function R(n, e, t) {
  return n.config[e] === void 0 && n.parent ? R(n.parent, e, t) : typeof n.config[e] == "function" ? n.config[e].bind({
    ...t,
    parent: n.parent ? R(n.parent, e, t) : null
  }) : n.config[e];
}
function wc(n) {
  const e = n.filter((i) => i.type === "extension"), t = n.filter((i) => i.type === "node"), r = n.filter((i) => i.type === "mark");
  return {
    baseExtensions: e,
    nodeExtensions: t,
    markExtensions: r
  };
}
function B_(n) {
  const e = [], { nodeExtensions: t, markExtensions: r } = wc(n), i = [...t, ...r], o = {
    default: null,
    rendered: !0,
    renderHTML: null,
    parseHTML: null,
    keepOnSplit: !0,
    isRequired: !1
  };
  return n.forEach((s) => {
    const l = {
      name: s.name,
      options: s.options,
      storage: s.storage,
      extensions: i
    }, a = R(s, "addGlobalAttributes", l);
    if (!a)
      return;
    a().forEach((d) => {
      d.types.forEach((u) => {
        Object.entries(d.attributes).forEach(([h, f]) => {
          e.push({
            type: u,
            name: h,
            attribute: {
              ...o,
              ...f
            }
          });
        });
      });
    });
  }), i.forEach((s) => {
    const l = {
      name: s.name,
      options: s.options,
      storage: s.storage
    }, a = R(s, "addAttributes", l);
    if (!a)
      return;
    const c = a();
    Object.entries(c).forEach(([d, u]) => {
      const h = {
        ...o,
        ...u
      };
      typeof (h == null ? void 0 : h.default) == "function" && (h.default = h.default()), h != null && h.isRequired && (h == null ? void 0 : h.default) === void 0 && delete h.default, e.push({
        type: s.name,
        name: d,
        attribute: h
      });
    });
  }), e;
}
function He(n, e) {
  if (typeof n == "string") {
    if (!e.nodes[n])
      throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);
    return e.nodes[n];
  }
  return n;
}
function Tt(...n) {
  return n.filter((e) => !!e).reduce((e, t) => {
    const r = { ...e };
    return Object.entries(t).forEach(([i, o]) => {
      if (!r[i]) {
        r[i] = o;
        return;
      }
      if (i === "class") {
        const l = o ? String(o).split(" ") : [], a = r[i] ? r[i].split(" ") : [], c = l.filter((d) => !a.includes(d));
        r[i] = [...a, ...c].join(" ");
      } else if (i === "style") {
        const l = o ? o.split(";").map((d) => d.trim()).filter(Boolean) : [], a = r[i] ? r[i].split(";").map((d) => d.trim()).filter(Boolean) : [], c = /* @__PURE__ */ new Map();
        a.forEach((d) => {
          const [u, h] = d.split(":").map((f) => f.trim());
          c.set(u, h);
        }), l.forEach((d) => {
          const [u, h] = d.split(":").map((f) => f.trim());
          c.set(u, h);
        }), r[i] = Array.from(c.entries()).map(([d, u]) => `${d}: ${u}`).join("; ");
      } else
        r[i] = o;
    }), r;
  }, {});
}
function Fu(n, e) {
  return e.filter((t) => t.type === n.type.name).filter((t) => t.attribute.rendered).map((t) => t.attribute.renderHTML ? t.attribute.renderHTML(n.attrs) || {} : {
    [t.name]: n.attrs[t.name]
  }).reduce((t, r) => Tt(t, r), {});
}
function P_(n) {
  return typeof n == "function";
}
function X(n, e = void 0, ...t) {
  return P_(n) ? e ? n.bind(e)(...t) : n(...t) : n;
}
function cT(n = {}) {
  return Object.keys(n).length === 0 && n.constructor === Object;
}
function dT(n) {
  return typeof n != "string" ? n : n.match(/^[+-]?(?:\d*\.)?\d+$/) ? Number(n) : n === "true" ? !0 : n === "false" ? !1 : n;
}
function Fg(n, e) {
  return "style" in n ? n : {
    ...n,
    getAttrs: (t) => {
      const r = n.getAttrs ? n.getAttrs(t) : n.attrs;
      if (r === !1)
        return !1;
      const i = e.reduce((o, s) => {
        const l = s.attribute.parseHTML ? s.attribute.parseHTML(t) : dT(t.getAttribute(s.name));
        return l == null ? o : {
          ...o,
          [s.name]: l
        };
      }, {});
      return { ...r, ...i };
    }
  };
}
function Ng(n) {
  return Object.fromEntries(
    // @ts-ignore
    Object.entries(n).filter(([e, t]) => e === "attrs" && cT(t) ? !1 : t != null)
  );
}
function z_(n, e) {
  var t;
  const r = B_(n), { nodeExtensions: i, markExtensions: o } = wc(n), s = (t = i.find((c) => R(c, "topNode"))) === null || t === void 0 ? void 0 : t.name, l = Object.fromEntries(i.map((c) => {
    const d = r.filter((y) => y.type === c.name), u = {
      name: c.name,
      options: c.options,
      storage: c.storage,
      editor: e
    }, h = n.reduce((y, _) => {
      const b = R(_, "extendNodeSchema", u);
      return {
        ...y,
        ...b ? b(c) : {}
      };
    }, {}), f = Ng({
      ...h,
      content: X(R(c, "content", u)),
      marks: X(R(c, "marks", u)),
      group: X(R(c, "group", u)),
      inline: X(R(c, "inline", u)),
      atom: X(R(c, "atom", u)),
      selectable: X(R(c, "selectable", u)),
      draggable: X(R(c, "draggable", u)),
      code: X(R(c, "code", u)),
      whitespace: X(R(c, "whitespace", u)),
      linebreakReplacement: X(R(c, "linebreakReplacement", u)),
      defining: X(R(c, "defining", u)),
      isolating: X(R(c, "isolating", u)),
      attrs: Object.fromEntries(d.map((y) => {
        var _;
        return [y.name, { default: (_ = y == null ? void 0 : y.attribute) === null || _ === void 0 ? void 0 : _.default }];
      }))
    }), p = X(R(c, "parseHTML", u));
    p && (f.parseDOM = p.map((y) => Fg(y, d)));
    const m = R(c, "renderHTML", u);
    m && (f.toDOM = (y) => m({
      node: y,
      HTMLAttributes: Fu(y, d)
    }));
    const g = R(c, "renderText", u);
    return g && (f.toText = g), [c.name, f];
  })), a = Object.fromEntries(o.map((c) => {
    const d = r.filter((g) => g.type === c.name), u = {
      name: c.name,
      options: c.options,
      storage: c.storage,
      editor: e
    }, h = n.reduce((g, y) => {
      const _ = R(y, "extendMarkSchema", u);
      return {
        ...g,
        ..._ ? _(c) : {}
      };
    }, {}), f = Ng({
      ...h,
      inclusive: X(R(c, "inclusive", u)),
      excludes: X(R(c, "excludes", u)),
      group: X(R(c, "group", u)),
      spanning: X(R(c, "spanning", u)),
      code: X(R(c, "code", u)),
      attrs: Object.fromEntries(d.map((g) => {
        var y;
        return [g.name, { default: (y = g == null ? void 0 : g.attribute) === null || y === void 0 ? void 0 : y.default }];
      }))
    }), p = X(R(c, "parseHTML", u));
    p && (f.parseDOM = p.map((g) => Fg(g, d)));
    const m = R(c, "renderHTML", u);
    return m && (f.toDOM = (g) => m({
      mark: g,
      HTMLAttributes: Fu(g, d)
    })), [c.name, f];
  }));
  return new Dy({
    topNode: s,
    nodes: l,
    marks: a
  });
}
function Td(n, e) {
  return e.nodes[n] || e.marks[n] || null;
}
function $g(n, e) {
  return Array.isArray(e) ? e.some((t) => (typeof t == "string" ? t : t.name) === n.name) : e;
}
function Jh(n, e) {
  const t = sr.fromSchema(e).serializeFragment(n), i = document.implementation.createHTMLDocument().createElement("div");
  return i.appendChild(t), i.innerHTML;
}
const uT = (n, e = 500) => {
  let t = "";
  const r = n.parentOffset;
  return n.parent.nodesBetween(Math.max(0, r - e), r, (i, o, s, l) => {
    var a, c;
    const d = ((c = (a = i.type.spec).toText) === null || c === void 0 ? void 0 : c.call(a, {
      node: i,
      pos: o,
      parent: s,
      index: l
    })) || i.textContent || "%leaf%";
    t += i.isAtom && !i.isText ? d : d.slice(0, Math.max(0, r - o));
  }), t;
};
function Yh(n) {
  return Object.prototype.toString.call(n) === "[object RegExp]";
}
class Fr {
  constructor(e) {
    this.find = e.find, this.handler = e.handler;
  }
}
const hT = (n, e) => {
  if (Yh(e))
    return e.exec(n);
  const t = e(n);
  if (!t)
    return null;
  const r = [t.text];
  return r.index = t.index, r.input = n, r.data = t.data, t.replaceWith && (t.text.includes(t.replaceWith) || console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'), r.push(t.replaceWith)), r;
};
function kl(n) {
  var e;
  const { editor: t, from: r, to: i, text: o, rules: s, plugin: l } = n, { view: a } = t;
  if (a.composing)
    return !1;
  const c = a.state.doc.resolve(r);
  if (
    // check for code node
    c.parent.type.spec.code || !((e = c.nodeBefore || c.nodeAfter) === null || e === void 0) && e.marks.find((h) => h.type.spec.code)
  )
    return !1;
  let d = !1;
  const u = uT(c) + o;
  return s.forEach((h) => {
    if (d)
      return;
    const f = hT(u, h.find);
    if (!f)
      return;
    const p = a.state.tr, m = yc({
      state: a.state,
      transaction: p
    }), g = {
      from: r - (f[0].length - o.length),
      to: i
    }, { commands: y, chain: _, can: b } = new _c({
      editor: t,
      state: m
    });
    h.handler({
      state: m,
      range: g,
      match: f,
      commands: y,
      chain: _,
      can: b
    }) === null || !p.steps.length || (p.setMeta(l, {
      transform: p,
      from: r,
      to: i,
      text: o
    }), a.dispatch(p), d = !0);
  }), d;
}
function fT(n) {
  const { editor: e, rules: t } = n, r = new G({
    state: {
      init() {
        return null;
      },
      apply(i, o, s) {
        const l = i.getMeta(r);
        if (l)
          return l;
        const a = i.getMeta("applyInputRules");
        return !!a && setTimeout(() => {
          let { text: d } = a;
          typeof d == "string" ? d = d : d = Jh(A.from(d), s.schema);
          const { from: u } = a, h = u + d.length;
          kl({
            editor: e,
            from: u,
            to: h,
            text: d,
            rules: t,
            plugin: r
          });
        }), i.selectionSet || i.docChanged ? null : o;
      }
    },
    props: {
      handleTextInput(i, o, s, l) {
        return kl({
          editor: e,
          from: o,
          to: s,
          text: l,
          rules: t,
          plugin: r
        });
      },
      handleDOMEvents: {
        compositionend: (i) => (setTimeout(() => {
          const { $cursor: o } = i.state.selection;
          o && kl({
            editor: e,
            from: o.pos,
            to: o.pos,
            text: "",
            rules: t,
            plugin: r
          });
        }), !1)
      },
      // add support for input rules to trigger on enter
      // this is useful for example for code blocks
      handleKeyDown(i, o) {
        if (o.key !== "Enter")
          return !1;
        const { $cursor: s } = i.state.selection;
        return s ? kl({
          editor: e,
          from: s.pos,
          to: s.pos,
          text: `
`,
          rules: t,
          plugin: r
        }) : !1;
      }
    },
    // @ts-ignore
    isInputRules: !0
  });
  return r;
}
function pT(n) {
  return Object.prototype.toString.call(n).slice(8, -1);
}
function vl(n) {
  return pT(n) !== "Object" ? !1 : n.constructor === Object && Object.getPrototypeOf(n) === Object.prototype;
}
function kc(n, e) {
  const t = { ...n };
  return vl(n) && vl(e) && Object.keys(e).forEach((r) => {
    vl(e[r]) && vl(n[r]) ? t[r] = kc(n[r], e[r]) : t[r] = e[r];
  }), t;
}
class Je {
  constructor(e = {}) {
    this.type = "mark", this.name = "mark", this.parent = null, this.child = null, this.config = {
      name: this.name,
      defaultOptions: {}
    }, this.config = {
      ...this.config,
      ...e
    }, this.name = this.config.name, e.defaultOptions && Object.keys(e.defaultOptions).length > 0 && console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`), this.options = this.config.defaultOptions, this.config.addOptions && (this.options = X(R(this, "addOptions", {
      name: this.name
    }))), this.storage = X(R(this, "addStorage", {
      name: this.name,
      options: this.options
    })) || {};
  }
  static create(e = {}) {
    return new Je(e);
  }
  configure(e = {}) {
    const t = this.extend({
      ...this.config,
      addOptions: () => kc(this.options, e)
    });
    return t.name = this.name, t.parent = this.parent, t;
  }
  extend(e = {}) {
    const t = new Je(e);
    return t.parent = this, this.child = t, t.name = e.name ? e.name : t.parent.name, e.defaultOptions && Object.keys(e.defaultOptions).length > 0 && console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${t.name}".`), t.options = X(R(t, "addOptions", {
      name: t.name
    })), t.storage = X(R(t, "addStorage", {
      name: t.name,
      options: t.options
    })), t;
  }
  static handleExit({ editor: e, mark: t }) {
    const { tr: r } = e.state, i = e.state.selection.$from;
    if (i.pos === i.end()) {
      const s = i.marks();
      if (!!!s.find((c) => (c == null ? void 0 : c.type.name) === t.name))
        return !1;
      const a = s.find((c) => (c == null ? void 0 : c.type.name) === t.name);
      return a && r.removeStoredMark(a), r.insertText(" ", i.pos), e.view.dispatch(r), !0;
    }
    return !1;
  }
}
function mT(n) {
  return typeof n == "number";
}
class gT {
  constructor(e) {
    this.find = e.find, this.handler = e.handler;
  }
}
const bT = (n, e, t) => {
  if (Yh(e))
    return [...n.matchAll(e)];
  const r = e(n, t);
  return r ? r.map((i) => {
    const o = [i.text];
    return o.index = i.index, o.input = n, o.data = i.data, i.replaceWith && (i.text.includes(i.replaceWith) || console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'), o.push(i.replaceWith)), o;
  }) : [];
};
function yT(n) {
  const { editor: e, state: t, from: r, to: i, rule: o, pasteEvent: s, dropEvent: l } = n, { commands: a, chain: c, can: d } = new _c({
    editor: e,
    state: t
  }), u = [];
  return t.doc.nodesBetween(r, i, (f, p) => {
    if (!f.isTextblock || f.type.spec.code)
      return;
    const m = Math.max(r, p), g = Math.min(i, p + f.content.size), y = f.textBetween(m - p, g - p, void 0, "￼");
    bT(y, o.find, s).forEach((b) => {
      if (b.index === void 0)
        return;
      const k = m + b.index + 1, C = k + b[0].length, w = {
        from: t.tr.mapping.map(k),
        to: t.tr.mapping.map(C)
      }, x = o.handler({
        state: t,
        range: w,
        match: b,
        commands: a,
        chain: c,
        can: d,
        pasteEvent: s,
        dropEvent: l
      });
      u.push(x);
    });
  }), u.every((f) => f !== null);
}
let Cl = null;
const _T = (n) => {
  var e;
  const t = new ClipboardEvent("paste", {
    clipboardData: new DataTransfer()
  });
  return (e = t.clipboardData) === null || e === void 0 || e.setData("text/html", n), t;
};
function wT(n) {
  const { editor: e, rules: t } = n;
  let r = null, i = !1, o = !1, s = typeof ClipboardEvent < "u" ? new ClipboardEvent("paste") : null, l;
  try {
    l = typeof DragEvent < "u" ? new DragEvent("drop") : null;
  } catch {
    l = null;
  }
  const a = ({ state: d, from: u, to: h, rule: f, pasteEvt: p }) => {
    const m = d.tr, g = yc({
      state: d,
      transaction: m
    });
    if (!(!yT({
      editor: e,
      state: g,
      from: Math.max(u - 1, 0),
      to: h.b - 1,
      rule: f,
      pasteEvent: p,
      dropEvent: l
    }) || !m.steps.length)) {
      try {
        l = typeof DragEvent < "u" ? new DragEvent("drop") : null;
      } catch {
        l = null;
      }
      return s = typeof ClipboardEvent < "u" ? new ClipboardEvent("paste") : null, m;
    }
  };
  return t.map((d) => new G({
    // we register a global drag handler to track the current drag source element
    view(u) {
      const h = (p) => {
        var m;
        r = !((m = u.dom.parentElement) === null || m === void 0) && m.contains(p.target) ? u.dom.parentElement : null, r && (Cl = e);
      }, f = () => {
        Cl && (Cl = null);
      };
      return window.addEventListener("dragstart", h), window.addEventListener("dragend", f), {
        destroy() {
          window.removeEventListener("dragstart", h), window.removeEventListener("dragend", f);
        }
      };
    },
    props: {
      handleDOMEvents: {
        drop: (u, h) => {
          if (o = r === u.dom.parentElement, l = h, !o) {
            const f = Cl;
            f != null && f.isEditable && setTimeout(() => {
              const p = f.state.selection;
              p && f.commands.deleteRange({ from: p.from, to: p.to });
            }, 10);
          }
          return !1;
        },
        paste: (u, h) => {
          var f;
          const p = (f = h.clipboardData) === null || f === void 0 ? void 0 : f.getData("text/html");
          return s = h, i = !!(p != null && p.includes("data-pm-slice")), !1;
        }
      }
    },
    appendTransaction: (u, h, f) => {
      const p = u[0], m = p.getMeta("uiEvent") === "paste" && !i, g = p.getMeta("uiEvent") === "drop" && !o, y = p.getMeta("applyPasteRules"), _ = !!y;
      if (!m && !g && !_)
        return;
      if (_) {
        let { text: C } = y;
        typeof C == "string" ? C = C : C = Jh(A.from(C), f.schema);
        const { from: w } = y, x = w + C.length, S = _T(C);
        return a({
          rule: d,
          state: f,
          from: w,
          to: { b: x },
          pasteEvt: S
        });
      }
      const b = h.doc.content.findDiffStart(f.doc.content), k = h.doc.content.findDiffEnd(f.doc.content);
      if (!(!mT(b) || !k || b === k.b))
        return a({
          rule: d,
          state: f,
          from: b,
          to: k,
          pasteEvt: s
        });
    }
  }));
}
function kT(n) {
  const e = n.filter((t, r) => n.indexOf(t) !== r);
  return Array.from(new Set(e));
}
class ti {
  constructor(e, t) {
    this.splittableMarks = [], this.editor = t, this.extensions = ti.resolve(e), this.schema = z_(this.extensions, t), this.setupExtensions();
  }
  /**
   * Returns a flattened and sorted extension list while
   * also checking for duplicated extensions and warns the user.
   * @param extensions An array of Tiptap extensions
   * @returns An flattened and sorted array of Tiptap extensions
   */
  static resolve(e) {
    const t = ti.sort(ti.flatten(e)), r = kT(t.map((i) => i.name));
    return r.length && console.warn(`[tiptap warn]: Duplicate extension names found: [${r.map((i) => `'${i}'`).join(", ")}]. This can lead to issues.`), t;
  }
  /**
   * Create a flattened array of extensions by traversing the `addExtensions` field.
   * @param extensions An array of Tiptap extensions
   * @returns A flattened array of Tiptap extensions
   */
  static flatten(e) {
    return e.map((t) => {
      const r = {
        name: t.name,
        options: t.options,
        storage: t.storage
      }, i = R(t, "addExtensions", r);
      return i ? [t, ...this.flatten(i())] : t;
    }).flat(10);
  }
  /**
   * Sort extensions by priority.
   * @param extensions An array of Tiptap extensions
   * @returns A sorted array of Tiptap extensions by priority
   */
  static sort(e) {
    return e.sort((r, i) => {
      const o = R(r, "priority") || 100, s = R(i, "priority") || 100;
      return o > s ? -1 : o < s ? 1 : 0;
    });
  }
  /**
   * 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((e, t) => {
      const r = {
        name: t.name,
        options: t.options,
        storage: t.storage,
        editor: this.editor,
        type: Td(t.name, this.schema)
      }, i = R(t, "addCommands", r);
      return i ? {
        ...e,
        ...i()
      } : e;
    }, {});
  }
  /**
   * Get all registered Prosemirror plugins from the extensions.
   * @returns An array of Prosemirror plugins
   */
  get plugins() {
    const { editor: e } = this, t = ti.sort([...this.extensions].reverse()), r = [], i = [], o = t.map((s) => {
      const l = {
        name: s.name,
        options: s.options,
        storage: s.storage,
        editor: e,
        type: Td(s.name, this.schema)
      }, a = [], c = R(s, "addKeyboardShortcuts", l);
      let d = {};
      if (s.type === "mark" && R(s, "exitable", l) && (d.ArrowRight = () => Je.handleExit({ editor: e, mark: s })), c) {
        const m = Object.fromEntries(Object.entries(c()).map(([g, y]) => [g, () => y({ editor: e })]));
        d = { ...d, ...m };
      }
      const u = HA(d);
      a.push(u);
      const h = R(s, "addInputRules", l);
      $g(s, e.options.enableInputRules) && h && r.push(...h());
      const f = R(s, "addPasteRules", l);
      $g(s, e.options.enablePasteRules) && f && i.push(...f());
      const p = R(s, "addProseMirrorPlugins", l);
      if (p) {
        const m = p();
        a.push(...m);
      }
      return a;
    }).flat();
    return [
      fT({
        editor: e,
        rules: r
      }),
      ...wT({
        editor: e,
        rules: i
      }),
      ...o
    ];
  }
  /**
   * Get all attributes from the extensions.
   * @returns An array of attributes
   */
  get attributes() {
    return B_(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: e } = this, { nodeExtensions: t } = wc(this.extensions);
    return Object.fromEntries(t.filter((r) => !!R(r, "addNodeView")).map((r) => {
      const i = this.attributes.filter((a) => a.type === r.name), o = {
        name: r.name,
        options: r.options,
        storage: r.storage,
        editor: e,
        type: He(r.name, this.schema)
      }, s = R(r, "addNodeView", o);
      if (!s)
        return [];
      const l = (a, c, d, u, h) => {
        const f = Fu(a, i);
        return s()({
          // pass-through
          node: a,
          view: c,
          getPos: d,
          decorations: u,
          innerDecorations: h,
          // tiptap-specific
          editor: e,
          extension: r,
          HTMLAttributes: f
        });
      };
      return [r.name, l];
    }));
  }
  /**
   * Go through all extensions, create extension storages & setup marks
   * & bind editor event listener.
   */
  setupExtensions() {
    this.extensions.forEach((e) => {
      var t;
      this.editor.extensionStorage[e.name] = e.storage;
      const r = {
        name: e.name,
        options: e.options,
        storage: e.storage,
        editor: this.editor,
        type: Td(e.name, this.schema)
      };
      e.type === "mark" && (!((t = X(R(e, "keepOnSplit", r))) !== null && t !== void 0) || t) && this.splittableMarks.push(e.name);
      const i = R(e, "onBeforeCreate", r), o = R(e, "onCreate", r), s = R(e, "onUpdate", r), l = R(e, "onSelectionUpdate", r), a = R(e, "onTransaction", r), c = R(e, "onFocus", r), d = R(e, "onBlur", r), u = R(e, "onDestroy", r);
      i && this.editor.on("beforeCreate", i), o && this.editor.on("create", o), s && this.editor.on("update", s), l && this.editor.on("selectionUpdate", l), a && this.editor.on("transaction", a), c && this.editor.on("focus", c), d && this.editor.on("blur", d), u && this.editor.on("destroy", u);
    });
  }
}
class he {
  constructor(e = {}) {
    this.type = "extension", this.name = "extension", this.parent = null, this.child = null, this.config = {
      name: this.name,
      defaultOptions: {}
    }, this.config = {
      ...this.config,
      ...e
    }, this.name = this.config.name, e.defaultOptions && Object.keys(e.defaultOptions).length > 0 && console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`), this.options = this.config.defaultOptions, this.config.addOptions && (this.options = X(R(this, "addOptions", {
      name: this.name
    }))), this.storage = X(R(this, "addStorage", {
      name: this.name,
      options: this.options
    })) || {};
  }
  static create(e = {}) {
    return new he(e);
  }
  configure(e = {}) {
    const t = this.extend({
      ...this.config,
      addOptions: () => kc(this.options, e)
    });
    return t.name = this.name, t.parent = this.parent, t;
  }
  extend(e = {}) {
    const t = new he({ ...this.config, ...e });
    return t.parent = this, this.child = t, t.name = e.name ? e.name : t.parent.name, e.defaultOptions && Object.keys(e.defaultOptions).length > 0 && console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${t.name}".`), t.options = X(R(t, "addOptions", {
      name: t.name
    })), t.storage = X(R(t, "addStorage", {
      name: t.name,
      options: t.options
    })), t;
  }
}
function H_(n, e, t) {
  const { from: r, to: i } = e, { blockSeparator: o = `

`, textSerializers: s = {} } = t || {};
  let l = "";
  return n.nodesBetween(r, i, (a, c, d, u) => {
    var h;
    a.isBlock && c > r && (l += o);
    const f = s == null ? void 0 : s[a.type.name];
    if (f)
      return d && (l += f({
        node: a,
        pos: c,
        parent: d,
        index: u,
        range: e
      })), !1;
    a.isText && (l += (h = a == null ? void 0 : a.text) === null || h === void 0 ? void 0 : h.slice(Math.max(r, c) - c, i - c));
  }), l;
}
function V_(n) {
  return Object.fromEntries(Object.entries(n.nodes).filter(([, e]) => e.spec.toText).map(([e, t]) => [e, t.spec.toText]));
}
const U_ = he.create({
  name: "clipboardTextSerializer",
  addOptions() {
    return {
      blockSeparator: void 0
    };
  },
  addProseMirrorPlugins() {
    return [
      new G({
        key: new te("clipboardTextSerializer"),
        props: {
          clipboardTextSerializer: () => {
            const { editor: n } = this, { state: e, schema: t } = n, { doc: r, selection: i } = e, { ranges: o } = i, s = Math.min(...o.map((d) => d.$from.pos)), l = Math.max(...o.map((d) => d.$to.pos)), a = V_(t);
            return H_(r, { from: s, to: l }, {
              ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {},
              textSerializers: a
            });
          }
        }
      })
    ];
  }
}), vT = () => ({ editor: n, view: e }) => (requestAnimationFrame(() => {
  var t;
  n.isDestroyed || (e.dom.blur(), (t = window == null ? void 0 : window.getSelection()) === null || t === void 0 || t.removeAllRanges());
}), !0), CT = (n = !1) => ({ commands: e }) => e.setContent("", n), ST = () => ({ state: n, tr: e, dispatch: t }) => {
  const { selection: r } = e, { ranges: i } = r;
  return t && i.forEach(({ $from: o, $to: s }) => {
    n.doc.nodesBetween(o.pos, s.pos, (l, a) => {
      if (l.type.isText)
        return;
      const { doc: c, mapping: d } = e, u = c.resolve(d.map(a)), h = c.resolve(d.map(a + l.nodeSize)), f = u.blockRange(h);
      if (!f)
        return;
      const p = go(f);
      if (l.type.isTextblock) {
        const { defaultType: m } = u.parent.contentMatchAt(u.index());
        e.setNodeMarkup(f.start, m);
      }
      (p || p === 0) && e.lift(f, p);
    });
  }), !0;
}, ET = (n) => (e) => n(e), xT = () => ({ state: n, dispatch: e }) => $_(n, e), DT = (n, e) => ({ editor: t, tr: r }) => {
  const { state: i } = t, o = i.doc.slice(n.from, n.to);
  r.deleteRange(n.from, n.to);
  const s = r.mapping.map(e);
  return r.insert(s, o.content), r.setSelection(new L(r.doc.resolve(Math.max(s - 1, 0)))), !0;
}, AT = () => ({ tr: n, dispatch: e }) => {
  const { selection: t } = n, r = t.$anchor.node();
  if (r.content.size > 0)
    return !1;
  const i = n.selection.$anchor;
  for (let o = i.depth; o > 0; o -= 1)
    if (i.node(o).type === r.type) {
      if (e) {
        const l = i.before(o), a = i.after(o);
        n.delete(l, a).scrollIntoView();
      }
      return !0;
    }
  return !1;
}, TT = (n) => ({ tr: e, state: t, dispatch: r }) => {
  const i = He(n, t.schema), o = e.selection.$anchor;
  for (let s = o.depth; s > 0; s -= 1)
    if (o.node(s).type === i) {
      if (r) {
        const a = o.before(s), c = o.after(s);
        e.delete(a, c).scrollIntoView();
      }
      return !0;
    }
  return !1;
}, MT = (n) => ({ tr: e, dispatch: t }) => {
  const { from: r, to: i } = n;
  return t && e.delete(r, i), !0;
}, OT = () => ({ state: n, dispatch: e }) => qh(n, e), FT = () => ({ commands: n }) => n.keyboardShortcut("Enter"), NT = () => ({ state: n, dispatch: e }) => GA(n, e);
function va(n, e, t = { strict: !0 }) {
  const r = Object.keys(e);
  return r.length ? r.every((i) => t.strict ? e[i] === n[i] : Yh(e[i]) ? e[i].test(n[i]) : e[i] === n[i]) : !0;
}
function q_(n, e, t = {}) {
  return n.find((r) => r.type === e && va(
    // Only check equality for the attributes that are provided
    Object.fromEntries(Object.keys(t).map((i) => [i, r.attrs[i]])),
    t
  ));
}
function Ig(n, e, t = {}) {
  return !!q_(n, e, t);
}
function bs(n, e, t) {
  var r;
  if (!n || !e)
    return;
  let i = n.parent.childAfter(n.parentOffset);
  if ((!i.node || !i.node.marks.some((d) => d.type === e)) && (i = n.parent.childBefore(n.parentOffset)), !i.node || !i.node.marks.some((d) => d.type === e) || (t = t || ((r = i.node.marks[0]) === null || r === void 0 ? void 0 : r.attrs), !q_([...i.node.marks], e, t)))
    return;
  let s = i.index, l = n.start() + i.offset, a = s + 1, c = l + i.node.nodeSize;
  for (; s > 0 && Ig([...n.parent.child(s - 1).marks], e, t); )
    s -= 1, l -= n.parent.child(s).nodeSize;
  for (; a < n.parent.childCount && Ig([...n.parent.child(a).marks], e, t); )
    c += n.parent.child(a).nodeSize, a += 1;
  return {
    from: l,
    to: c
  };
}
function zr(n, e) {
  if (typeof n == "string") {
    if (!e.marks[n])
      throw Error(`There is no mark type named '${n}'. Maybe you forgot to add the extension?`);
    return e.marks[n];
  }
  return n;
}
const $T = (n, e = {}) => ({ tr: t, state: r, dispatch: i }) => {
  const o = zr(n, r.schema), { doc: s, selection: l } = t, { $from: a, from: c, to: d } = l;
  if (i) {
    const u = bs(a, o, e);
    if (u && u.from <= c && u.to >= d) {
      const h = L.create(s, u.from, u.to);
      t.setSelection(h);
    }
  }
  return !0;
}, IT = (n) => (e) => {
  const t = typeof n == "function" ? n(e) : n;
  for (let r = 0; r < t.length; r += 1)
    if (t[r](e))
      return !0;
  return !1;
};
function vc(n) {
  return n instanceof L;
}
function Zn(n = 0, e = 0, t = 0) {
  return Math.min(Math.max(n, e), t);
}
function j_(n, e = null) {
  if (!e)
    return null;
  const t = V.atStart(n), r = V.atEnd(n);
  if (e === "start" || e === !0)
    return t;
  if (e === "end")
    return r;
  const i = t.from, o = r.to;
  return e === "all" ? L.create(n, Zn(0, i, o), Zn(n.content.size, i, o)) : L.create(n, Zn(e, i, o), Zn(e, i, o));
}
function LT() {
  return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
}
function Xh() {
  return [
    "iPad Simulator",
    "iPhone Simulator",
    "iPod Simulator",
    "iPad",
    "iPhone",
    "iPod"
  ].includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend" in document;
}
const RT = (n = null, e = {}) => ({ editor: t, view: r, tr: i, dispatch: o }) => {
  e = {
    scrollIntoView: !0,
    ...e
  };
  const s = () => {
    (Xh() || LT()) && r.dom.focus(), requestAnimationFrame(() => {
      t.isDestroyed || (r.focus(), e != null && e.scrollIntoView && t.commands.scrollIntoView());
    });
  };
  if (r.hasFocus() && n === null || n === !1)
    return !0;
  if (o && n === null && !vc(t.state.selection))
    return s(), !0;
  const l = j_(i.doc, n) || t.state.selection, a = t.state.selection.eq(l);
  return o && (a || i.setSelection(l), a && i.storedMarks && i.setStoredMarks(i.storedMarks), s()), !0;
}, BT = (n, e) => (t) => n.every((r, i) => e(r, { ...t, index: i })), PT = (n, e) => ({ tr: t, commands: r }) => r.insertContentAt({ from: t.selection.from, to: t.selection.to }, n, e), W_ = (n) => {
  const e = n.childNodes;
  for (let t = e.length - 1; t >= 0; t -= 1) {
    const r = e[t];
    r.nodeType === 3 && r.nodeValue && /^(\n\s\s|\n)$/.test(r.nodeValue) ? n.removeChild(r) : r.nodeType === 1 && W_(r);
  }
  return n;
};
function Sl(n) {
  const e = `<body>${n}</body>`, t = new window.DOMParser().parseFromString(e, "text/html").body;
  return W_(t);
}
function ys(n, e, t) {
  if (n instanceof Qn || n instanceof A)
    return n;
  t = {
    slice: !0,
    parseOptions: {},
    ...t
  };
  const r = typeof n == "object" && n !== null, i = typeof n == "string";
  if (r)
    try {
      if (Array.isArray(n) && n.length > 0)
        return A.fromArray(n.map((l) => e.nodeFromJSON(l)));
      const s = e.nodeFromJSON(n);
      return t.errorOnInvalidContent && s.check(), s;
    } catch (o) {
      if (t.errorOnInvalidContent)
        throw new Error("[tiptap error]: Invalid JSON content", { cause: o });
      return console.warn("[tiptap warn]: Invalid content.", "Passed value:", n, "Error:", o), ys("", e, t);
    }
  if (i) {
    if (t.errorOnInvalidContent) {
      let s = !1, l = "";
      const a = new Dy({
        topNode: e.spec.topNode,
        marks: e.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: e.spec.nodes.append({
          __tiptap__private__unknown__catch__all__node: {
            content: "inline*",
            group: "block",
            parseDOM: [
              {
                tag: "*",
                getAttrs: (c) => (s = !0, l = typeof c == "string" ? c : c.outerHTML, null)
              }
            ]
          }
        })
      });
      if (t.slice ? On.fromSchema(a).parseSlice(Sl(n), t.parseOptions) : On.fromSchema(a).parse(Sl(n), t.parseOptions), t.errorOnInvalidContent && s)
        throw new Error("[tiptap error]: Invalid HTML content", { cause: new Error(`Invalid element found: ${l}`) });
    }
    const o = On.fromSchema(e);
    return t.slice ? o.parseSlice(Sl(n), t.parseOptions).content : o.parse(Sl(n), t.parseOptions);
  }
  return ys("", e, t);
}
function G_(n, e, t) {
  const r = n.steps.length - 1;
  if (r < e)
    return;
  const i = n.steps[r];
  if (!(i instanceof Me || i instanceof Ae))
    return;
  const o = n.mapping.maps[r];
  let s = 0;
  o.forEach((l, a, c, d) => {
    s === 0 && (s = d);
  }), n.setSelection(V.near(n.doc.resolve(s), t));
}
const zT = (n) => !("type" in n), HT = (n, e, t) => ({ tr: r, dispatch: i, editor: o }) => {
  var s;
  if (i) {
    t = {
      parseOptions: o.options.parseOptions,
      updateSelection: !0,
      applyInputRules: !1,
      applyPasteRules: !1,
      ...t
    };
    let l;
    const a = (g) => {
      o.emit("contentError", {
        editor: o,
        error: g,
        disableCollaboration: () => {
          o.storage.collaboration && (o.storage.collaboration.isDisabled = !0);
        }
      });
    }, c = {
      preserveWhitespace: "full",
      ...t.parseOptions
    };
    if (!t.errorOnInvalidContent && !o.options.enableContentCheck && o.options.emitContentError)
      try {
        ys(e, o.schema, {
          parseOptions: c,
          errorOnInvalidContent: !0
        });
      } catch (g) {
        a(g);
      }
    try {
      l = ys(e, o.schema, {
        parseOptions: c,
        errorOnInvalidContent: (s = t.errorOnInvalidContent) !== null && s !== void 0 ? s : o.options.enableContentCheck
      });
    } catch (g) {
      return a(g), !1;
    }
    let { from: d, to: u } = typeof n == "number" ? { from: n, to: n } : { from: n.from, to: n.to }, h = !0, f = !0;
    if ((zT(l) ? l : [l]).forEach((g) => {
      g.check(), h = h ? g.isText && g.marks.length === 0 : !1, f = f ? g.isBlock : !1;
    }), d === u && f) {
      const { parent: g } = r.doc.resolve(d);
      g.isTextblock && !g.type.spec.code && !g.childCount && (d -= 1, u += 1);
    }
    let m;
    if (h) {
      if (Array.isArray(e))
        m = e.map((g) => g.text || "").join("");
      else if (e instanceof A) {
        let g = "";
        e.forEach((y) => {
          y.text && (g += y.text);
        }), m = g;
      } else typeof e == "object" && e && e.text ? m = e.text : m = e;
      r.insertText(m, d, u);
    } else
      m = l, r.replaceWith(d, u, m);
    t.updateSelection && G_(r, r.steps.length - 1, -1), t.applyInputRules && r.setMeta("applyInputRules", { from: d, text: m }), t.applyPasteRules && r.setMeta("applyPasteRules", { from: d, text: m });
  }
  return !0;
}, VT = () => ({ state: n, dispatch: e }) => qA(n, e), UT = () => ({ state: n, dispatch: e }) => jA(n, e), qT = () => ({ state: n, dispatch: e }) => D_(n, e), jT = () => ({ state: n, dispatch: e }) => O_(n, e), WT = () => ({ state: n, dispatch: e, tr: t }) => {
  try {
    const r = hc(n.doc, n.selection.$from.pos, -1);
    return r == null ? !1 : (t.join(r, 2), e && e(t), !0);
  } catch {
    return !1;
  }
}, GT = () => ({ state: n, dispatch: e, tr: t }) => {
  try {
    const r = hc(n.doc, n.selection.$from.pos, 1);
    return r == null ? !1 : (t.join(r, 2), e && e(t), !0);
  } catch {
    return !1;
  }
}, KT = () => ({ state: n, dispatch: e }) => VA(n, e), JT = () => ({ state: n, dispatch: e }) => UA(n, e);
function K_() {
  return typeof navigator < "u" ? /Mac/.test(navigator.platform) : !1;
}
function YT(n) {
  const e = n.split(/-(?!$)/);
  let t = e[e.length - 1];
  t === "Space" && (t = " ");
  let r, i, o, s;
  for (let l = 0; l < e.length - 1; l += 1) {
    const a = e[l];
    if (/^(cmd|meta|m)$/i.test(a))
      s = !0;
    else if (/^a(lt)?$/i.test(a))
      r = !0;
    else if (/^(c|ctrl|control)$/i.test(a))
      i = !0;
    else if (/^s(hift)?$/i.test(a))
      o = !0;
    else if (/^mod$/i.test(a))
      Xh() || K_() ? s = !0 : i = !0;
    else
      throw new Error(`Unrecognized modifier name: ${a}`);
  }
  return r && (t = `Alt-${t}`), i && (t = `Ctrl-${t}`), s && (t = `Meta-${t}`), o && (t = `Shift-${t}`), t;
}
const XT = (n) => ({ editor: e, view: t, tr: r, dispatch: i }) => {
  const o = YT(n).split(/-(?!$)/), s = o.find((c) => !["Alt", "Ctrl", "Meta", "Shift"].includes(c)), l = new KeyboardEvent("keydown", {
    key: s === "Space" ? " " : s,
    altKey: o.includes("Alt"),
    ctrlKey: o.includes("Ctrl"),
    metaKey: o.includes("Meta"),
    shiftKey: o.includes("Shift"),
    bubbles: !0,
    cancelable: !0
  }), a = e.captureTransaction(() => {
    t.someProp("handleKeyDown", (c) => c(t, l));
  });
  return a == null || a.steps.forEach((c) => {
    const d = c.map(r.mapping);
    d && i && r.maybeStep(d);
  }), !0;
};
function _s(n, e, t = {}) {
  const { from: r, to: i, empty: o } = n.selection, s = e ? He(e, n.schema) : null, l = [];
  n.doc.nodesBetween(r, i, (u, h) => {
    if (u.isText)
      return;
    const f = Math.max(r, h), p = Math.min(i, h + u.nodeSize);
    l.push({
      node: u,
      from: f,
      to: p
    });
  });
  const a = i - r, c = l.filter((u) => s ? s.name === u.node.type.name : !0).filter((u) => va(u.node.attrs, t, { strict: !1 }));
  return o ? !!c.length : c.reduce((u, h) => u + h.to - h.from, 0) >= a;
}
const ZT = (n, e = {}) => ({ state: t, dispatch: r }) => {
  const i = He(n, t.schema);
  return _s(t, i, e) ? WA(t, r) : !1;
}, QT = () => ({ state: n, dispatch: e }) => I_(n, e), eM = (n) => ({ state: e, dispatch: t }) => {
  const r = He(n, e.schema);
  return iT(r)(e, t);
}, tM = () => ({ state: n, dispatch: e }) => N_(n, e);
function Cc(n, e) {
  return e.nodes[n] ? "node" : e.marks[n] ? "mark" : null;
}
function Lg(n, e) {
  const t = typeof e == "string" ? [e] : e;
  return Object.keys(n).reduce((r, i) => (t.includes(i) || (r[i] = n[i]), r), {});
}
const nM = (n, e) => ({ tr: t, state: r, dispatch: i }) => {
  let o = null, s = null;
  const l = Cc(typeof n == "string" ? n : n.name, r.schema);
  return l ? (l === "node" && (o = He(n, r.schema)), l === "mark" && (s = zr(n, r.schema)), i && t.selection.ranges.forEach((a) => {
    r.doc.nodesBetween(a.$from.pos, a.$to.pos, (c, d) => {
      o && o === c.type && t.setNodeMarkup(d, void 0, Lg(c.attrs, e)), s && c.marks.length && c.marks.forEach((u) => {
        s === u.type && t.addMark(d, d + c.nodeSize, s.create(Lg(u.attrs, e)));
      });
    });
  }), !0) : !1;
}, rM = () => ({ tr: n, dispatch: e }) => (e && n.scrollIntoView(), !0), iM = () => ({ tr: n, dispatch: e }) => {
  if (e) {
    const t = new wt(n.doc);
    n.setSelection(t);
  }
  return !0;
}, oM = () => ({ state: n, dispatch: e }) => T_(n, e), sM = () => ({ state: n, dispatch: e }) => F_(n, e), lM = () => ({ state: n, dispatch: e }) => YA(n, e), aM = () => ({ state: n, dispatch: e }) => QA(n, e), cM = () => ({ state: n, dispatch: e }) => ZA(n, e);
function Ca(n, e, t = {}, r = {}) {
  return ys(n, e, {
    slice: !1,
    parseOptions: t,
    errorOnInvalidContent: r.errorOnInvalidContent
  });
}
const dM = (n, e = !1, t = {}, r = {}) => ({ editor: i, tr: o, dispatch: s, commands: l }) => {
  var a, c;
  const { doc: d } = o;
  if (t.preserveWhitespace !== "full") {
    const u = Ca(n, i.schema, t, {
      errorOnInvalidContent: (a = r.errorOnInvalidContent) !== null && a !== void 0 ? a : i.options.enableContentCheck
    });
    return s && o.replaceWith(0, d.content.size, u).setMeta("preventUpdate", !e), !0;
  }
  return s && o.setMeta("preventUpdate", !e), l.insertContentAt({ from: 0, to: d.content.size }, n, {
    parseOptions: t,
    errorOnInvalidContent: (c = r.errorOnInvalidContent) !== null && c !== void 0 ? c : i.options.enableContentCheck
  });
};
function J_(n, e) {
  const t = zr(e, n.schema), { from: r, to: i, empty: o } = n.selection, s = [];
  o ? (n.storedMarks && s.push(...n.storedMarks), s.push(...n.selection.$head.marks())) : n.doc.nodesBetween(r, i, (a) => {
    s.push(...a.marks);
  });
  const l = s.find((a) => a.type.name === t.name);
  return l ? { ...l.attrs } : {};
}
function Zh(n, e) {
  const t = new Oh(n);
  return e.forEach((r) => {
    r.steps.forEach((i) => {
      t.step(i);
    });
  }), t;
}
function uM(n) {
  for (let e = 0; e < n.edgeCount; e += 1) {
    const { type: t } = n.edge(e);
    if (t.isTextblock && !t.hasRequiredAttrs())
      return t;
  }
  return null;
}
function Rg(n, e) {
  const t = [];
  return n.descendants((r, i) => {
    e(r) && t.push({
      node: r,
      pos: i
    });
  }), t;
}
function Y_(n, e, t) {
  const r = [];
  return n.nodesBetween(e.from, e.to, (i, o) => {
    t(i) && r.push({
      node: i,
      pos: o
    });
  }), r;
}
function hM(n, e) {
  for (let t = n.depth; t > 0; t -= 1) {
    const r = n.node(t);
    if (e(r))
      return {
        pos: t > 0 ? n.before(t) : 0,
        start: n.start(t),
        depth: t,
        node: r
      };
  }
}
function Sc(n) {
  return (e) => hM(e.$from, n);
}
function fM(n, e) {
  const t = ti.resolve(n);
  return z_(t, e);
}
function pM(n, e) {
  const t = {
    from: 0,
    to: n.content.size
  };
  return H_(n, t, e);
}
function mM(n, e) {
  const t = He(e, n.schema), { from: r, to: i } = n.selection, o = [];
  n.doc.nodesBetween(r, i, (l) => {
    o.push(l);
  });
  const s = o.reverse().find((l) => l.type.name === t.name);
  return s ? { ...s.attrs } : {};
}
function X_(n, e) {
  const t = Cc(typeof e == "string" ? e : e.name, n.schema);
  return t === "node" ? mM(n, e) : t === "mark" ? J_(n, e) : {};
}
function gM(n, e = JSON.stringify) {
  const t = {};
  return n.filter((r) => {
    const i = e(r);
    return Object.prototype.hasOwnProperty.call(t, i) ? !1 : t[i] = !0;
  });
}
function bM(n) {
  const e = gM(n);
  return e.length === 1 ? e : e.filter((t, r) => !e.filter((o, s) => s !== r).some((o) => t.oldRange.from >= o.oldRange.from && t.oldRange.to <= o.oldRange.to && t.newRange.from >= o.newRange.from && t.newRange.to <= o.newRange.to));
}
function Z_(n) {
  const { mapping: e, steps: t } = n, r = [];
  return e.maps.forEach((i, o) => {
    const s = [];
    if (i.ranges.length)
      i.forEach((l, a) => {
        s.push({ from: l, to: a });
      });
    else {
      const { from: l, to: a } = t[o];
      if (l === void 0 || a === void 0)
        return;
      s.push({ from: l, to: a });
    }
    s.forEach(({ from: l, to: a }) => {
      const c = e.slice(o).map(l, -1), d = e.slice(o).map(a), u = e.invert().map(c, -1), h = e.invert().map(d);
      r.push({
        oldRange: {
          from: u,
          to: h
        },
        newRange: {
          from: c,
          to: d
        }
      });
    });
  }), bM(r);
}
function Qh(n, e, t) {
  const r = [];
  return n === e ? t.resolve(n).marks().forEach((i) => {
    const o = t.resolve(n), s = bs(o, i.type);
    s && r.push({
      mark: i,
      ...s
    });
  }) : t.nodesBetween(n, e, (i, o) => {
    !i || (i == null ? void 0 : i.nodeSize) === void 0 || r.push(...i.marks.map((s) => ({
      from: o,
      to: o + i.nodeSize,
      mark: s
    })));
  }), r;
}
function Jl(n, e, t) {
  return Object.fromEntries(Object.entries(t).filter(([r]) => {
    const i = n.find((o) => o.type === e && o.name === r);
    return i ? i.attribute.keepOnSplit : !1;
  }));
}
function Nu(n, e, t = {}) {
  const { empty: r, ranges: i } = n.selection, o = e ? zr(e, n.schema) : null;
  if (r)
    return !!(n.storedMarks || n.selection.$from.marks()).filter((u) => o ? o.name === u.type.name : !0).find((u) => va(u.attrs, t, { strict: !1 }));
  let s = 0;
  const l = [];
  if (i.forEach(({ $from: u, $to: h }) => {
    const f = u.pos, p = h.pos;
    n.doc.nodesBetween(f, p, (m, g) => {
      if (!m.isText && !m.marks.length)
        return;
      const y = Math.max(f, g), _ = Math.min(p, g + m.nodeSize), b = _ - y;
      s += b, l.push(...m.marks.map((k) => ({
        mark: k,
        from: y,
        to: _
      })));
    });
  }), s === 0)
    return !1;
  const a = l.filter((u) => o ? o.name === u.mark.type.name : !0).filter((u) => va(u.mark.attrs, t, { strict: !1 })).reduce((u, h) => u + h.to - h.from, 0), c = l.filter((u) => o ? u.mark.type !== o && u.mark.type.excludes(o) : !0).reduce((u, h) => u + h.to - h.from, 0);
  return (a > 0 ? a + c : a) >= s;
}
function yM(n, e, t = {}) {
  if (!e)
    return _s(n, null, t) || Nu(n, null, t);
  const r = Cc(e, n.schema);
  return r === "node" ? _s(n, e, t) : r === "mark" ? Nu(n, e, t) : !1;
}
function Bg(n, e) {
  const { nodeExtensions: t } = wc(e), r = t.find((s) => s.name === n);
  if (!r)
    return !1;
  const i = {
    name: r.name,
    options: r.options,
    storage: r.storage
  }, o = X(R(r, "group", i));
  return typeof o != "string" ? !1 : o.split(" ").includes("list");
}
function ef(n, { checkChildren: e = !0, ignoreWhitespace: t = !1 } = {}) {
  var r;
  if (t) {
    if (n.type.name === "hardBreak")
      return !0;
    if (n.isText)
      return /^\s*$/m.test((r = n.text) !== null && r !== void 0 ? r : "");
  }
  if (n.isText)
    return !n.text;
  if (n.isAtom || n.isLeaf)
    return !1;
  if (n.content.childCount === 0)
    return !0;
  if (e) {
    let i = !0;
    return n.content.forEach((o) => {
      i !== !1 && (ef(o, { ignoreWhitespace: t, checkChildren: e }) || (i = !1));
    }), i;
  }
  return !1;
}
function $u(n) {
  return n instanceof P;
}
function Sa(n, e, t) {
  const i = n.state.doc.content.size, o = Zn(e, 0, i), s = Zn(t, 0, i), l = n.coordsAtPos(o), a = n.coordsAtPos(s, -1), c = Math.min(l.top, a.top), d = Math.max(l.bottom, a.bottom), u = Math.min(l.left, a.left), h = Math.max(l.right, a.right), f = h - u, p = d - c, y = {
    top: c,
    bottom: d,
    left: u,
    right: h,
    width: f,
    height: p,
    x: u,
    y: c
  };
  return {
    ...y,
    toJSON: () => y
  };
}
function _M(n, e, t) {
  var r;
  const { selection: i } = e;
  let o = null;
  if (vc(i) && (o = i.$cursor), o) {
    const l = (r = n.storedMarks) !== null && r !== void 0 ? r : o.marks();
    return !!t.isInSet(l) || !l.some((a) => a.type.excludes(t));
  }
  const { ranges: s } = i;
  return s.some(({ $from: l, $to: a }) => {
    let c = l.depth === 0 ? n.doc.inlineContent && n.doc.type.allowsMarkType(t) : !1;
    return n.doc.nodesBetween(l.pos, a.pos, (d, u, h) => {
      if (c)
        return !1;
      if (d.isInline) {
        const f = !h || h.type.allowsMarkType(t), p = !!t.isInSet(d.marks) || !d.marks.some((m) => m.type.excludes(t));
        c = f && p;
      }
      return !c;
    }), c;
  });
}
const wM = (n, e = {}) => ({ tr: t, state: r, dispatch: i }) => {
  const { selection: o } = t, { empty: s, ranges: l } = o, a = zr(n, r.schema);
  if (i)
    if (s) {
      const c = J_(r, a);
      t.addStoredMark(a.create({
        ...c,
        ...e
      }));
    } else
      l.forEach((c) => {
        const d = c.$from.pos, u = c.$to.pos;
        r.doc.nodesBetween(d, u, (h, f) => {
          const p = Math.max(f, d), m = Math.min(f + h.nodeSize, u);
          h.marks.find((y) => y.type === a) ? h.marks.forEach((y) => {
            a === y.type && t.addMark(p, m, a.create({
              ...y.attrs,
              ...e
            }));
          }) : t.addMark(p, m, a.create(e));
        });
      });
  return _M(r, t, a);
}, kM = (n, e) => ({ tr: t }) => (t.setMeta(n, e), !0), vM = (n, e = {}) => ({ state: t, dispatch: r, chain: i }) => {
  const o = He(n, t.schema);
  let s;
  return t.selection.$anchor.sameParent(t.selection.$head) && (s = t.selection.$anchor.parent.attrs), o.isTextblock ? i().command(({ commands: l }) => Og(o, { ...s, ...e })(t) ? !0 : l.clearNodes()).command(({ state: l }) => Og(o, { ...s, ...e })(l, r)).run() : (console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'), !1);
}, CM = (n) => ({ tr: e, dispatch: t }) => {
  if (t) {
    const { doc: r } = e, i = Zn(n, 0, r.content.size), o = P.create(r, i);
    e.setSelection(o);
  }
  return !0;
}, SM = (n) => ({ tr: e, dispatch: t }) => {
  if (t) {
    const { doc: r } = e, { from: i, to: o } = typeof n == "number" ? { from: n, to: n } : n, s = L.atStart(r).from, l = L.atEnd(r).to, a = Zn(i, s, l), c = Zn(o, s, l), d = L.create(r, a, c);
    e.setSelection(d);
  }
  return !0;
}, EM = (n) => ({ state: e, dispatch: t }) => {
  const r = He(n, e.schema);
  return lT(r)(e, t);
};
function Pg(n, e) {
  const t = n.storedMarks || n.selection.$to.parentOffset && n.selection.$from.marks();
  if (t) {
    const r = t.filter((i) => e == null ? void 0 : e.includes(i.type.name));
    n.tr.ensureMarks(r);
  }
}
const xM = ({ keepMarks: n = !0 } = {}) => ({ tr: e, state: t, dispatch: r, editor: i }) => {
  const { selection: o, doc: s } = e, { $from: l, $to: a } = o, c = i.extensionManager.attributes, d = Jl(c, l.node().type.name, l.node().attrs);
  if (o instanceof P && o.node.isBlock)
    return !l.parentOffset || !er(s, l.pos) ? !1 : (r && (n && Pg(t, i.extensionManager.splittableMarks), e.split(l.pos).scrollIntoView()), !0);
  if (!l.parent.isBlock)
    return !1;
  const u = a.parentOffset === a.parent.content.size, h = l.depth === 0 ? void 0 : uM(l.node(-1).contentMatchAt(l.indexAfter(-1)));
  let f = u && h ? [
    {
      type: h,
      attrs: d
    }
  ] : void 0, p = er(e.doc, e.mapping.map(l.pos), 1, f);
  if (!f && !p && er(e.doc, e.mapping.map(l.pos), 1, h ? [{ type: h }] : void 0) && (p = !0, f = h ? [
    {
      type: h,
      attrs: d
    }
  ] : void 0), r) {
    if (p && (o instanceof L && e.deleteSelection(), e.split(e.mapping.map(l.pos), 1, f), h && !u && !l.parentOffset && l.parent.type !== h)) {
      const m = e.mapping.map(l.before()), g = e.doc.resolve(m);
      l.node(-1).canReplaceWith(g.index(), g.index() + 1, h) && e.setNodeMarkup(e.mapping.map(l.before()), h);
    }
    n && Pg(t, i.extensionManager.splittableMarks), e.scrollIntoView();
  }
  return p;
}, DM = (n, e = {}) => ({ tr: t, state: r, dispatch: i, editor: o }) => {
  var s;
  const l = He(n, r.schema), { $from: a, $to: c } = r.selection, d = r.selection.node;
  if (d && d.isBlock || a.depth < 2 || !a.sameParent(c))
    return !1;
  const u = a.node(-1);
  if (u.type !== l)
    return !1;
  const h = o.extensionManager.attributes;
  if (a.parent.content.size === 0 && a.node(-1).childCount === a.indexAfter(-1)) {
    if (a.depth === 2 || a.node(-3).type !== l || a.index(-2) !== a.node(-2).childCount - 1)
      return !1;
    if (i) {
      let y = A.empty;
      const _ = a.index(-1) ? 1 : a.index(-2) ? 2 : 3;
      for (let S = a.depth - _; S >= a.depth - 3; S -= 1)
        y = A.from(a.node(S).copy(y));
      const b = a.indexAfter(-1) < a.node(-2).childCount ? 1 : a.indexAfter(-2) < a.node(-3).childCount ? 2 : 3, k = {
        ...Jl(h, a.node().type.name, a.node().attrs),
        ...e
      }, C = ((s = l.contentMatch.defaultType) === null || s === void 0 ? void 0 : s.createAndFill(k)) || void 0;
      y = y.append(A.from(l.createAndFill(null, C) || void 0));
      const w = a.before(a.depth - (_ - 1));
      t.replace(w, a.after(-b), new O(y, 4 - _, 0));
      let x = -1;
      t.doc.nodesBetween(w, t.doc.content.size, (S, D) => {
        if (x > -1)
          return !1;
        S.isTextblock && S.content.size === 0 && (x = D + 1);
      }), x > -1 && t.setSelection(L.near(t.doc.resolve(x))), t.scrollIntoView();
    }
    return !0;
  }
  const f = c.pos === a.end() ? u.contentMatchAt(0).defaultType : null, p = {
    ...Jl(h, u.type.name, u.attrs),
    ...e
  }, m = {
    ...Jl(h, a.node().type.name, a.node().attrs),
    ...e
  };
  t.delete(a.pos, c.pos);
  const g = f ? [
    { type: l, attrs: p },
    { type: f, attrs: m }
  ] : [{ type: l, attrs: p }];
  if (!er(t.doc, a.pos, 2))
    return !1;
  if (i) {
    const { selection: y, storedMarks: _ } = r, { splittableMarks: b } = o.extensionManager, k = _ || y.$to.parentOffset && y.$from.marks();
    if (t.split(a.pos, 2, g).scrollIntoView(), !k || !i)
      return !0;
    const C = k.filter((w) => b.includes(w.type.name));
    t.ensureMarks(C);
  }
  return !0;
}, Md = (n, e) => {
  const t = Sc((s) => s.type === e)(n.selection);
  if (!t)
    return !0;
  const r = n.doc.resolve(Math.max(0, t.pos - 1)).before(t.depth);
  if (r === void 0)
    return !0;
  const i = n.doc.nodeAt(r);
  return t.node.type === (i == null ? void 0 : i.type) && Ei(n.doc, t.pos) && n.join(t.pos), !0;
}, Od = (n, e) => {
  const t = Sc((s) => s.type === e)(n.selection);
  if (!t)
    return !0;
  const r = n.doc.resolve(t.start).after(t.depth);
  if (r === void 0)
    return !0;
  const i = n.doc.nodeAt(r);
  return t.node.type === (i == null ? void 0 : i.type) && Ei(n.doc, r) && n.join(r), !0;
}, AM = (n, e, t, r = {}) => ({ editor: i, tr: o, state: s, dispatch: l, chain: a, commands: c, can: d }) => {
  const { extensions: u, splittableMarks: h } = i.extensionManager, f = He(n, s.schema), p = He(e, s.schema), { selection: m, storedMarks: g } = s, { $from: y, $to: _ } = m, b = y.blockRange(_), k = g || m.$to.parentOffset && m.$from.marks();
  if (!b)
    return !1;
  const C = Sc((w) => Bg(w.type.name, u))(m);
  if (b.depth >= 1 && C && b.depth - C.depth <= 1) {
    if (C.node.type === f)
      return c.liftListItem(p);
    if (Bg(C.node.type.name, u) && f.validContent(C.node.content) && l)
      return a().command(() => (o.setNodeMarkup(C.pos, f), !0)).command(() => Md(o, f)).command(() => Od(o, f)).run();
  }
  return !t || !k || !l ? a().command(() => d().wrapInList(f, r) ? !0 : c.clearNodes()).wrapInList(f, r).command(() => Md(o, f)).command(() => Od(o, f)).run() : a().command(() => {
    const w = d().wrapInList(f, r), x = k.filter((S) => h.includes(S.type.name));
    return o.ensureMarks(x), w ? !0 : c.clearNodes();
  }).wrapInList(f, r).command(() => Md(o, f)).command(() => Od(o, f)).run();
}, TM = (n, e = {}, t = {}) => ({ state: r, commands: i }) => {
  const { extendEmptyMarkRange: o = !1 } = t, s = zr(n, r.schema);
  return Nu(r, s, e) ? i.unsetMark(s, { extendEmptyMarkRange: o }) : i.setMark(s, e);
}, MM = (n, e, t = {}) => ({ state: r, commands: i }) => {
  const o = He(n, r.schema), s = He(e, r.schema), l = _s(r, o, t);
  let a;
  return r.selection.$anchor.sameParent(r.selection.$head) && (a = r.selection.$anchor.parent.attrs), l ? i.setNode(s, a) : i.setNode(o, { ...a, ...t });
}, OM = (n, e = {}) => ({ state: t, commands: r }) => {
  const i = He(n, t.schema);
  return _s(t, i, e) ? r.lift(i) : r.wrapIn(i, e);
}, FM = () => ({ state: n, dispatch: e }) => {
  const t = n.plugins;
  for (let r = 0; r < t.length; r += 1) {
    const i = t[r];
    let o;
    if (i.spec.isInputRules && (o = i.getState(n))) {
      if (e) {
        const s = n.tr, l = o.transform;
        for (let a = l.steps.length - 1; a >= 0; a -= 1)
          s.step(l.steps[a].invert(l.docs[a]));
        if (o.text) {
          const a = s.doc.resolve(o.from).marks();
          s.replaceWith(o.from, o.to, n.schema.text(o.text, a));
        } else
          s.delete(o.from, o.to);
      }
      return !0;
    }
  }
  return !1;
}, NM = () => ({ tr: n, dispatch: e }) => {
  const { selection: t } = n, { empty: r, ranges: i } = t;
  return r || e && i.forEach((o) => {
    n.removeMark(o.$from.pos, o.$to.pos);
  }), !0;
}, $M = (n, e = {}) => ({ tr: t, state: r, dispatch: i }) => {
  var o;
  const { extendEmptyMarkRange: s = !1 } = e, { selection: l } = t, a = zr(n, r.schema), { $from: c, empty: d, ranges: u } = l;
  if (!i)
    return !0;
  if (d && s) {
    let { from: h, to: f } = l;
    const p = (o = c.marks().find((g) => g.type === a)) === null || o === void 0 ? void 0 : o.attrs, m = bs(c, a, p);
    m && (h = m.from, f = m.to), t.removeMark(h, f, a);
  } else
    u.forEach((h) => {
      t.removeMark(h.$from.pos, h.$to.pos, a);
    });
  return t.removeStoredMark(a), !0;
}, IM = (n, e = {}) => ({ tr: t, state: r, dispatch: i }) => {
  let o = null, s = null;
  const l = Cc(typeof n == "string" ? n : n.name, r.schema);
  return l ? (l === "node" && (o = He(n, r.schema)), l === "mark" && (s = zr(n, r.schema)), i && t.selection.ranges.forEach((a) => {
    const c = a.$from.pos, d = a.$to.pos;
    let u, h, f, p;
    t.selection.empty ? r.doc.nodesBetween(c, d, (m, g) => {
      o && o === m.type && (f = Math.max(g, c), p = Math.min(g + m.nodeSize, d), u = g, h = m);
    }) : r.doc.nodesBetween(c, d, (m, g) => {
      g < c && o && o === m.type && (f = Math.max(g, c), p = Math.min(g + m.nodeSize, d), u = g, h = m), g >= c && g <= d && (o && o === m.type && t.setNodeMarkup(g, void 0, {
        ...m.attrs,
        ...e
      }), s && m.marks.length && m.marks.forEach((y) => {
        if (s === y.type) {
          const _ = Math.max(g, c), b = Math.min(g + m.nodeSize, d);
          t.addMark(_, b, s.create({
            ...y.attrs,
            ...e
          }));
        }
      }));
    }), h && (u !== void 0 && t.setNodeMarkup(u, void 0, {
      ...h.attrs,
      ...e
    }), s && h.marks.length && h.marks.forEach((m) => {
      s === m.type && t.addMark(f, p, s.create({
        ...m.attrs,
        ...e
      }));
    }));
  }), !0) : !1;
}, LM = (n, e = {}) => ({ state: t, dispatch: r }) => {
  const i = He(n, t.schema);
  return eT(i, e)(t, r);
}, RM = (n, e = {}) => ({ state: t, dispatch: r }) => {
  const i = He(n, t.schema);
  return tT(i, e)(t, r);
};
var BM = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  blur: vT,
  clearContent: CT,
  clearNodes: ST,
  command: ET,
  createParagraphNear: xT,
  cut: DT,
  deleteCurrentNode: AT,
  deleteNode: TT,
  deleteRange: MT,
  deleteSelection: OT,
  enter: FT,
  exitCode: NT,
  extendMarkRange: $T,
  first: IT,
  focus: RT,
  forEach: BT,
  insertContent: PT,
  insertContentAt: HT,
  joinBackward: qT,
  joinDown: UT,
  joinForward: jT,
  joinItemBackward: WT,
  joinItemForward: GT,
  joinTextblockBackward: KT,
  joinTextblockForward: JT,
  joinUp: VT,
  keyboardShortcut: XT,
  lift: ZT,
  liftEmptyBlock: QT,
  liftListItem: eM,
  newlineInCode: tM,
  resetAttributes: nM,
  scrollIntoView: rM,
  selectAll: iM,
  selectNodeBackward: oM,
  selectNodeForward: sM,
  selectParentNode: lM,
  selectTextblockEnd: aM,
  selectTextblockStart: cM,
  setContent: dM,
  setMark: wM,
  setMeta: kM,
  setNode: vM,
  setNodeSelection: CM,
  setTextSelection: SM,
  sinkListItem: EM,
  splitBlock: xM,
  splitListItem: DM,
  toggleList: AM,
  toggleMark: TM,
  toggleNode: MM,
  toggleWrap: OM,
  undoInputRule: FM,
  unsetAllMarks: NM,
  unsetMark: $M,
  updateAttributes: IM,
  wrapIn: LM,
  wrapInList: RM
});
const Q_ = he.create({
  name: "commands",
  addCommands() {
    return {
      ...BM
    };
  }
}), ew = he.create({
  name: "drop",
  addProseMirrorPlugins() {
    return [
      new G({
        key: new te("tiptapDrop"),
        props: {
          handleDrop: (n, e, t, r) => {
            this.editor.emit("drop", {
              editor: this.editor,
              event: e,
              slice: t,
              moved: r
            });
          }
        }
      })
    ];
  }
}), tw = he.create({
  name: "editable",
  addProseMirrorPlugins() {
    return [
      new G({
        key: new te("editable"),
        props: {
          editable: () => this.editor.options.editable
        }
      })
    ];
  }
}), nw = new te("focusEvents"), rw = he.create({
  name: "focusEvents",
  addProseMirrorPlugins() {
    const { editor: n } = this;
    return [
      new G({
        key: nw,
        props: {
          handleDOMEvents: {
            focus: (e, t) => {
              n.isFocused = !0;
              const r = n.state.tr.setMeta("focus", { event: t }).setMeta("addToHistory", !1);
              return e.dispatch(r), !1;
            },
            blur: (e, t) => {
              n.isFocused = !1;
              const r = n.state.tr.setMeta("blur", { event: t }).setMeta("addToHistory", !1);
              return e.dispatch(r), !1;
            }
          }
        }
      })
    ];
  }
}), iw = he.create({
  name: "keymap",
  addKeyboardShortcuts() {
    const n = () => this.editor.commands.first(({ commands: s }) => [
      () => s.undoInputRule(),
      // maybe convert first text block node to default node
      () => s.command(({ tr: l }) => {
        const { selection: a, doc: c } = l, { empty: d, $anchor: u } = a, { pos: h, parent: f } = u, p = u.parent.isTextblock && h > 0 ? l.doc.resolve(h - 1) : u, m = p.parent.type.spec.isolating, g = u.pos - u.parentOffset, y = m && p.parent.childCount === 1 ? g === u.pos : V.atStart(c).from === h;
        return !d || !f.type.isTextblock || f.textContent.length || !y || y && u.parent.type.name === "paragraph" ? !1 : s.clearNodes();
      }),
      () => s.deleteSelection(),
      () => s.joinBackward(),
      () => s.selectNodeBackward()
    ]), e = () => this.editor.commands.first(({ commands: s }) => [
      () => s.deleteSelection(),
      () => s.deleteCurrentNode(),
      () => s.joinForward(),
      () => s.selectNodeForward()
    ]), r = {
      Enter: () => this.editor.commands.first(({ commands: s }) => [
        () => s.newlineInCode(),
        () => s.createParagraphNear(),
        () => s.liftEmptyBlock(),
        () => s.splitBlock()
      ]),
      "Mod-Enter": () => this.editor.commands.exitCode(),
      Backspace: n,
      "Mod-Backspace": n,
      "Shift-Backspace": n,
      Delete: e,
      "Mod-Delete": e,
      "Mod-a": () => this.editor.commands.selectAll()
    }, i = {
      ...r
    }, o = {
      ...r,
      "Ctrl-h": n,
      "Alt-Backspace": n,
      "Ctrl-d": e,
      "Ctrl-Alt-Backspace": e,
      "Alt-Delete": e,
      "Alt-d": e,
      "Ctrl-a": () => this.editor.commands.selectTextblockStart(),
      "Ctrl-e": () => this.editor.commands.selectTextblockEnd()
    };
    return Xh() || K_() ? o : i;
  },
  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 G({
        key: new te("clearDocument"),
        appendTransaction: (n, e, t) => {
          if (n.some((m) => m.getMeta("composition")))
            return;
          const r = n.some((m) => m.docChanged) && !e.doc.eq(t.doc), i = n.some((m) => m.getMeta("preventClearDocument"));
          if (!r || i)
            return;
          const { empty: o, from: s, to: l } = e.selection, a = V.atStart(e.doc).from, c = V.atEnd(e.doc).to;
          if (o || !(s === a && l === c) || !ef(t.doc))
            return;
          const h = t.tr, f = yc({
            state: t,
            transaction: h
          }), { commands: p } = new _c({
            editor: this.editor,
            state: f
          });
          if (p.clearNodes(), !!h.steps.length)
            return h;
        }
      })
    ];
  }
}), ow = he.create({
  name: "paste",
  addProseMirrorPlugins() {
    return [
      new G({
        key: new te("tiptapPaste"),
        props: {
          handlePaste: (n, e, t) => {
            this.editor.emit("paste", {
              editor: this.editor,
              event: e,
              slice: t
            });
          }
        }
      })
    ];
  }
}), sw = he.create({
  name: "tabindex",
  addProseMirrorPlugins() {
    return [
      new G({
        key: new te("tabindex"),
        props: {
          attributes: () => this.editor.isEditable ? { tabindex: "0" } : {}
        }
      })
    ];
  }
});
var Io = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ClipboardTextSerializer: U_,
  Commands: Q_,
  Drop: ew,
  Editable: tw,
  FocusEvents: rw,
  Keymap: iw,
  Paste: ow,
  Tabindex: sw,
  focusEventsPluginKey: nw
});
class Kr {
  get name() {
    return this.node.type.name;
  }
  constructor(e, t, r = !1, i = null) {
    this.currentNode = null, this.actualDepth = null, this.isBlock = r, this.resolvedPos = e, this.editor = t, this.currentNode = i;
  }
  get node() {
    return this.currentNode || this.resolvedPos.node();
  }
  get element() {
    return this.editor.view.domAtPos(this.pos).node;
  }
  get depth() {
    var e;
    return (e = this.actualDepth) !== null && e !== void 0 ? e : this.resolvedPos.depth;
  }
  get pos() {
    return this.resolvedPos.pos;
  }
  get content() {
    return this.node.content;
  }
  set content(e) {
    let t = this.from, r = 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;
      }
      t = this.from + 1, r = this.to - 1;
    }
    this.editor.commands.insertContentAt({ from: t, to: r }, e);
  }
  get attributes() {
    return this.node.attrs;
  }
  get textContent() {
    return this.node.textContent;
  }
  get size() {
    return this.node.nodeSize;
  }
  get from() {
    return this.isBlock ? this.pos : this.resolvedPos.start(this.resolvedPos.depth);
  }
  get range() {
    return {
      from: this.from,
      to: this.to
    };
  }
  get to() {
    return this.isBlock ? this.pos + this.size : this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1);
  }
  get parent() {
    if (this.depth === 0)
      return null;
    const e = this.resolvedPos.start(this.resolvedPos.depth - 1), t = this.resolvedPos.doc.resolve(e);
    return new Kr(t, this.editor);
  }
  get before() {
    let e = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2));
    return e.depth !== this.depth && (e = this.resolvedPos.doc.resolve(this.from - 3)), new Kr(e, this.editor);
  }
  get after() {
    let e = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1));
    return e.depth !== this.depth && (e = this.resolvedPos.doc.resolve(this.to + 3)), new Kr(e, this.editor);
  }
  get children() {
    const e = [];
    return this.node.content.forEach((t, r) => {
      const i = t.isBlock && !t.isTextblock, o = t.isAtom && !t.isText, s = this.pos + r + (o ? 0 : 1);
      if (s < 0 || s > this.resolvedPos.doc.nodeSize - 2)
        return;
      const l = this.resolvedPos.doc.resolve(s);
      if (!i && l.depth <= this.depth)
        return;
      const a = new Kr(l, this.editor, i, i ? t : null);
      i && (a.actualDepth = this.depth + 1), e.push(new Kr(l, this.editor, i, i ? t : null));
    }), e;
  }
  get firstChild() {
    return this.children[0] || null;
  }
  get lastChild() {
    const e = this.children;
    return e[e.length - 1] || null;
  }
  closest(e, t = {}) {
    let r = null, i = this.parent;
    for (; i && !r; ) {
      if (i.node.type.name === e)
        if (Object.keys(t).length > 0) {
          const o = i.node.attrs, s = Object.keys(t);
          for (let l = 0; l < s.length; l += 1) {
            const a = s[l];
            if (o[a] !== t[a])
              break;
          }
        } else
          r = i;
      i = i.parent;
    }
    return r;
  }
  querySelector(e, t = {}) {
    return this.querySelectorAll(e, t, !0)[0] || null;
  }
  querySelectorAll(e, t = {}, r = !1) {
    let i = [];
    if (!this.children || this.children.length === 0)
      return i;
    const o = Object.keys(t);
    return this.children.forEach((s) => {
      r && i.length > 0 || (s.node.type.name === e && o.every((a) => t[a] === s.node.attrs[a]) && i.push(s), !(r && i.length > 0) && (i = i.concat(s.querySelectorAll(e, t, r))));
    }), i;
  }
  setAttribute(e) {
    const { tr: t } = this.editor.state;
    t.setNodeMarkup(this.from, void 0, {
      ...this.node.attrs,
      ...e
    }), this.editor.view.dispatch(t);
  }
}
const PM = `.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;
}

.tippy-box[data-animation=fade][data-state=hidden] {
  opacity: 0
}`;
function zM(n, e, t) {
  const r = document.querySelector("style[data-tiptap-style]");
  if (r !== null)
    return r;
  const i = document.createElement("style");
  return e && i.setAttribute("nonce", e), i.setAttribute("data-tiptap-style", ""), i.innerHTML = n, document.getElementsByTagName("head")[0].appendChild(i), i;
}
class HM extends aT {
  constructor(e = {}) {
    super(), this.isFocused = !1, this.isInitialized = !1, this.extensionStorage = {}, this.options = {
      element: document.createElement("div"),
      content: "",
      injectCSS: !0,
      injectNonce: void 0,
      extensions: [],
      autofocus: !1,
      editable: !0,
      editorProps: {},
      parseOptions: {},
      coreExtensionOptions: {},
      enableInputRules: !0,
      enablePasteRules: !0,
      enableCoreExtensions: !0,
      enableContentCheck: !1,
      emitContentError: !1,
      onBeforeCreate: () => null,
      onCreate: () => null,
      onUpdate: () => null,
      onSelectionUpdate: () => null,
      onTransaction: () => null,
      onFocus: () => null,
      onBlur: () => null,
      onDestroy: () => null,
      onContentError: ({ error: t }) => {
        throw t;
      },
      onPaste: () => null,
      onDrop: () => null
    }, this.isCapturingTransaction = !1, this.capturedTransaction = null, this.setOptions(e), this.createExtensionManager(), this.createCommandManager(), this.createSchema(), this.on("beforeCreate", this.options.onBeforeCreate), this.emit("beforeCreate", { editor: this }), this.on("contentError", this.options.onContentError), this.createView(), this.injectCSS(), 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: t, slice: r, moved: i }) => this.options.onDrop(t, r, i)), this.on("paste", ({ event: t, slice: r }) => this.options.onPaste(t, r)), window.setTimeout(() => {
      this.isDestroyed || (this.commands.focus(this.options.autofocus), this.emit("create", { editor: this }), this.isInitialized = !0);
    }, 0);
  }
  /**
   * 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() {
    this.options.injectCSS && document && (this.css = zM(PM, this.options.injectNonce));
  }
  /**
   * Update editor options.
   *
   * @param options A list of options
   */
  setOptions(e = {}) {
    this.options = {
      ...this.options,
      ...e
    }, !(!this.view || !this.state || this.isDestroyed) && (this.options.editorProps && this.view.setProps(this.options.editorProps), this.view.updateState(this.state));
  }
  /**
   * Update editable state of the editor.
   */
  setEditable(e, t = !0) {
    this.setOptions({ editable: e }), t && this.emit("update", { editor: this, transaction: this.state.tr });
  }
  /**
   * Returns whether the editor is editable.
   */
  get isEditable() {
    return this.options.editable && this.view && this.view.editable;
  }
  /**
   * Returns the editor state.
   */
  get state() {
    return this.view.state;
  }
  /**
   * 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(e, t) {
    const r = P_(t) ? t(e, [...this.state.plugins]) : [...this.state.plugins, e], i = this.state.reconfigure({ plugins: r });
    return this.view.updateState(i), i;
  }
  /**
   * Unregister a ProseMirror plugin.
   *
   * @param nameOrPluginKeyToRemove The plugins name
   * @returns The new editor state or undefined if the editor is destroyed
   */
  unregisterPlugin(e) {
    if (this.isDestroyed)
      return;
    const t = this.state.plugins;
    let r = t;
    if ([].concat(e).forEach((o) => {
      const s = typeof o == "string" ? `${o}$` : o.key;
      r = r.filter((l) => !l.key.startsWith(s));
    }), t.length === r.length)
      return;
    const i = this.state.reconfigure({
      plugins: r
    });
    return this.view.updateState(i), i;
  }
  /**
   * Creates an extension manager.
   */
  createExtensionManager() {
    var e, t;
    const i = [...this.options.enableCoreExtensions ? [
      tw,
      U_.configure({
        blockSeparator: (t = (e = this.options.coreExtensionOptions) === null || e === void 0 ? void 0 : e.clipboardTextSerializer) === null || t === void 0 ? void 0 : t.blockSeparator
      }),
      Q_,
      rw,
      iw,
      sw,
      ew,
      ow
    ].filter((o) => typeof this.options.enableCoreExtensions == "object" ? this.options.enableCoreExtensions[o.name] !== !1 : !0) : [], ...this.options.extensions].filter((o) => ["extension", "node", "mark"].includes(o == null ? void 0 : o.type));
    this.extensionManager = new ti(i, this);
  }
  /**
   * Creates an command manager.
   */
  createCommandManager() {
    this.commandManager = new _c({
      editor: this
    });
  }
  /**
   * Creates a ProseMirror schema.
   */
  createSchema() {
    this.schema = this.extensionManager.schema;
  }
  /**
   * Creates a ProseMirror view.
   */
  createView() {
    var e;
    let t;
    try {
      t = Ca(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: this.options.enableContentCheck });
    } catch (s) {
      if (!(s instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(s.message))
        throw s;
      this.emit("contentError", {
        editor: this,
        error: s,
        disableCollaboration: () => {
          this.storage.collaboration && (this.storage.collaboration.isDisabled = !0), this.options.extensions = this.options.extensions.filter((l) => l.name !== "collaboration"), this.createExtensionManager();
        }
      }), t = Ca(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: !1 });
    }
    const r = j_(t, this.options.autofocus);
    this.view = new Vh(this.options.element, {
      ...this.options.editorProps,
      attributes: {
        // add `role="textbox"` to the editor element
        role: "textbox",
        ...(e = this.options.editorProps) === null || e === void 0 ? void 0 : e.attributes
      },
      dispatchTransaction: this.dispatchTransaction.bind(this),
      state: Zr.create({
        doc: t,
        selection: r || void 0
      })
    });
    const i = this.state.reconfigure({
      plugins: this.extensionManager.plugins
    });
    this.view.updateState(i), this.createNodeViews(), this.prependClass();
    const o = this.view.dom;
    o.editor = this;
  }
  /**
   * Creates all node views.
   */
  createNodeViews() {
    this.view.isDestroyed || this.view.setProps({
      nodeViews: this.extensionManager.nodeViews
    });
  }
  /**
   * Prepend class name to element.
   */
  prependClass() {
    this.view.dom.className = `tiptap ${this.view.dom.className}`;
  }
  captureTransaction(e) {
    this.isCapturingTransaction = !0, e(), this.isCapturingTransaction = !1;
    const t = this.capturedTransaction;
    return this.capturedTransaction = null, t;
  }
  /**
   * The callback over which to send transactions (state updates) produced by the view.
   *
   * @param transaction An editor state transaction
   */
  dispatchTransaction(e) {
    if (this.view.isDestroyed)
      return;
    if (this.isCapturingTransaction) {
      if (!this.capturedTransaction) {
        this.capturedTransaction = e;
        return;
      }
      e.steps.forEach((s) => {
        var l;
        return (l = this.capturedTransaction) === null || l === void 0 ? void 0 : l.step(s);
      });
      return;
    }
    const t = this.state.apply(e), r = !this.state.selection.eq(t.selection);
    this.emit("beforeTransaction", {
      editor: this,
      transaction: e,
      nextState: t
    }), this.view.updateState(t), this.emit("transaction", {
      editor: this,
      transaction: e
    }), r && this.emit("selectionUpdate", {
      editor: this,
      transaction: e
    });
    const i = e.getMeta("focus"), o = e.getMeta("blur");
    i && this.emit("focus", {
      editor: this,
      event: i.event,
      transaction: e
    }), o && this.emit("blur", {
      editor: this,
      event: o.event,
      transaction: e
    }), !(!e.docChanged || e.getMeta("preventUpdate")) && this.emit("update", {
      editor: this,
      transaction: e
    });
  }
  /**
   * Get attributes of the currently selected node or mark.
   */
  getAttributes(e) {
    return X_(this.state, e);
  }
  isActive(e, t) {
    const r = typeof e == "string" ? e : null, i = typeof e == "string" ? t : e;
    return yM(this.state, r, i);
  }
  /**
   * Get the document as JSON.
   */
  getJSON() {
    return this.state.doc.toJSON();
  }
  /**
   * Get the document as HTML.
   */
  getHTML() {
    return Jh(this.state.doc.content, this.schema);
  }
  /**
   * Get the document as text.
   */
  getText(e) {
    const { blockSeparator: t = `

`, textSerializers: r = {} } = e || {};
    return pM(this.state.doc, {
      blockSeparator: t,
      textSerializers: {
        ...V_(this.schema),
        ...r
      }
    });
  }
  /**
   * Check if there is no content.
   */
  get isEmpty() {
    return ef(this.state.doc);
  }
  /**
   * Get the number of characters for the current document.
   *
   * @deprecated
   */
  getCharacterCount() {
    return console.warn('[tiptap warn]: "editor.getCharacterCount()" is deprecated. Please use "editor.storage.characterCount.characters()" instead.'), this.state.doc.content.size - 2;
  }
  /**
   * Destroy the editor.
   */
  destroy() {
    if (this.emit("destroy"), this.view) {
      const e = this.view.dom;
      e && e.editor && delete e.editor, this.view.destroy();
    }
    this.removeAllListeners();
  }
  /**
   * Check if the editor is already destroyed.
   */
  get isDestroyed() {
    var e;
    return !(!((e = this.view) === null || e === void 0) && e.docView);
  }
  $node(e, t) {
    var r;
    return ((r = this.$doc) === null || r === void 0 ? void 0 : r.querySelector(e, t)) || null;
  }
  $nodes(e, t) {
    var r;
    return ((r = this.$doc) === null || r === void 0 ? void 0 : r.querySelectorAll(e, t)) || null;
  }
  $pos(e) {
    const t = this.state.doc.resolve(e);
    return new Kr(t, this);
  }
  get $doc() {
    return this.$pos(0);
  }
}
function ao(n) {
  return new Fr({
    find: n.find,
    handler: ({ state: e, range: t, match: r }) => {
      const i = X(n.getAttributes, void 0, r);
      if (i === !1 || i === null)
        return null;
      const { tr: o } = e, s = r[r.length - 1], l = r[0];
      if (s) {
        const a = l.search(/\S/), c = t.from + l.indexOf(s), d = c + s.length;
        if (Qh(t.from, t.to, e.doc).filter((f) => f.mark.type.excluded.find((m) => m === n.type && m !== f.mark.type)).filter((f) => f.to > c).length)
          return null;
        d < t.to && o.delete(d, t.to), c > t.from && o.delete(t.from + a, c);
        const h = t.from + a + s.length;
        o.addMark(t.from + a, h, n.type.create(i || {})), o.removeStoredMark(n.type);
      }
    }
  });
}
class Mt {
  constructor(e = {}) {
    this.type = "node", this.name = "node", this.parent = null, this.child = null, this.config = {
      name: this.name,
      defaultOptions: {}
    }, this.config = {
      ...this.config,
      ...e
    }, this.name = this.config.name, e.defaultOptions && Object.keys(e.defaultOptions).length > 0 && console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`), this.options = this.config.defaultOptions, this.config.addOptions && (this.options = X(R(this, "addOptions", {
      name: this.name
    }))), this.storage = X(R(this, "addStorage", {
      name: this.name,
      options: this.options
    })) || {};
  }
  static create(e = {}) {
    return new Mt(e);
  }
  configure(e = {}) {
    const t = this.extend({
      ...this.config,
      addOptions: () => kc(this.options, e)
    });
    return t.name = this.name, t.parent = this.parent, t;
  }
  extend(e = {}) {
    const t = new Mt(e);
    return t.parent = this, this.child = t, t.name = e.name ? e.name : t.parent.name, e.defaultOptions && Object.keys(e.defaultOptions).length > 0 && console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${t.name}".`), t.options = X(R(t, "addOptions", {
      name: t.name
    })), t.storage = X(R(t, "addStorage", {
      name: t.name,
      options: t.options
    })), t;
  }
}
function gi(n) {
  return new gT({
    find: n.find,
    handler: ({ state: e, range: t, match: r, pasteEvent: i }) => {
      const o = X(n.getAttributes, void 0, r, i);
      if (o === !1 || o === null)
        return null;
      const { tr: s } = e, l = r[r.length - 1], a = r[0];
      let c = t.to;
      if (l) {
        const d = a.search(/\S/), u = t.from + a.indexOf(l), h = u + l.length;
        if (Qh(t.from, t.to, e.doc).filter((p) => p.mark.type.excluded.find((g) => g === n.type && g !== p.mark.type)).filter((p) => p.to > u).length)
          return null;
        h < t.to && s.delete(h, t.to), u > t.from && s.delete(t.from + d, u), c = t.from + d + l.length, s.addMark(t.from + d, c, n.type.create(o || {})), s.removeStoredMark(n.type);
      }
    }
  });
}
var El, VM = new Uint8Array(16);
function UM() {
  if (!El && (El = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto < "u" && typeof msCrypto.getRandomValues == "function" && msCrypto.getRandomValues.bind(msCrypto), !El))
    throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
  return El(VM);
}
const qM = /^(?:[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;
function jM(n) {
  return typeof n == "string" && qM.test(n);
}
var je = [];
for (var Fd = 0; Fd < 256; ++Fd)
  je.push((Fd + 256).toString(16).substr(1));
function WM(n) {
  var e = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0, t = (je[n[e + 0]] + je[n[e + 1]] + je[n[e + 2]] + je[n[e + 3]] + "-" + je[n[e + 4]] + je[n[e + 5]] + "-" + je[n[e + 6]] + je[n[e + 7]] + "-" + je[n[e + 8]] + je[n[e + 9]] + "-" + je[n[e + 10]] + je[n[e + 11]] + je[n[e + 12]] + je[n[e + 13]] + je[n[e + 14]] + je[n[e + 15]]).toLowerCase();
  if (!jM(t))
    throw TypeError("Stringified UUID is invalid");
  return t;
}
function lw(n, e, t) {
  n = n || {};
  var r = n.random || (n.rng || UM)();
  return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, WM(r);
}
var GM = class aw {
  constructor(e) {
    this.cache = new Map(e);
  }
  /**
   * 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(e) {
    return this.cache.get(e);
  }
  /**
   * 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(e, t, r) {
    e < 0 || this.cache.set(e, [t, r]);
  }
  /**
   * 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(e, t, r, i) {
    this.remove(e), this.set(t, r, i);
  }
  /**
   * Removes the cache entry at the given position
   * @param pos The doc position to remove from cache
   */
  remove(e) {
    this.cache.delete(e);
  }
  /**
   * 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(e) {
    const t = new aw(this.cache), r = e.mapping;
    return this.cache.forEach(([i, o], s) => {
      if (s < 0)
        return;
      const l = r.mapResult(s), a = e.doc.nodeAt(l.pos);
      if (l.deleted || !(a != null && a.eq(i)))
        t.remove(s);
      else if (s !== l.pos) {
        const c = o.map((d) => d.map(r, 0, 0)).filter((d) => d != null);
        t.replace(s, l.pos, a, c);
      }
    }), t;
  }
};
function KM({
  parser: n,
  nodeTypes: e = ["code_block", "codeBlock"],
  languageExtractor: t = (r) => r.attrs.language
}) {
  const r = new te("prosemirror-highlight");
  return new G({
    key: r,
    state: {
      init(i, o) {
        const s = new GM(), [l, a] = zg(
          o.doc,
          n,
          e,
          t,
          s
        );
        return { cache: s, decorations: l, promises: a };
      },
      apply: (i, o) => {
        const s = o.cache.invalidate(i), l = !!i.getMeta("prosemirror-highlight-refresh");
        if (!i.docChanged && !l) {
          const d = o.decorations.map(i.mapping, i.doc), u = o.promises;
          return { cache: s, decorations: d, promises: u };
        }
        const [a, c] = zg(
          i.doc,
          n,
          e,
          t,
          s
        );
        return { cache: s, decorations: a, promises: c };
      }
    },
    view: (i) => {
      const o = /* @__PURE__ */ new Set(), s = () => {
        if (o.size > 0)
          return;
        const a = i.state.tr.setMeta("prosemirror-highlight-refresh", !0);
        i.dispatch(a);
      }, l = () => {
        var a;
        const c = r.getState(i.state);
        for (const d of (a = c == null ? void 0 : c.promises) != null ? a : [])
          o.add(d), d.then(() => {
            o.delete(d), s();
          }).catch(() => {
            o.delete(d);
          });
      };
      return l(), {
        update: () => {
          l();
        }
      };
    },
    props: {
      decorations(i) {
        var o;
        return (o = this.getState(i)) == null ? void 0 : o.decorations;
      }
    }
  });
}
function zg(n, e, t, r, i) {
  const o = [], s = [];
  return n.descendants((l, a) => {
    if (!l.type.isTextblock)
      return !0;
    if (t.includes(l.type.name)) {
      const c = r(l), d = i.get(a);
      if (d) {
        const [u, h] = d;
        o.push(...h);
      } else {
        const u = e({
          content: l.textContent,
          language: c || void 0,
          pos: a,
          size: l.nodeSize
        });
        u && Array.isArray(u) ? (i.set(a, l, u), o.push(...u)) : u instanceof Promise && (i.remove(a), s.push(u));
      }
    }
    return !1;
  }), [Q.create(n, o), s];
}
function JM(n, e) {
  return function({ content: r, language: i, pos: o, size: s }) {
    var l;
    const a = [], { tokens: c, fg: d, bg: u, rootStyle: h } = n.codeToTokens(r, {
      lang: i,
      theme: n.getLoadedThemes()[0]
    }), f = h || (d && u ? `--prosemirror-highlight:${d};--prosemirror-highlight-bg:${u}` : "");
    if (f) {
      const m = se.node(o, o + s, { style: f });
      a.push(m);
    }
    let p = o + 1;
    for (const m of c) {
      for (const g of m) {
        const y = p + g.content.length, _ = se.inline(p, y, {
          // When using `options.themes` the `htmlStyle` field will be set, otherwise `color` will be set
          style: YM(
            (l = g.htmlStyle) != null ? l : `color: ${g.color}`
          ),
          class: "shiki"
        });
        a.push(_), p = y;
      }
      p += 1;
    }
    return a;
  };
}
function YM(n) {
  return typeof n == "string" ? n : Object.entries(n).map(([e, t]) => `${e}:${t}`).join(";");
}
const XM = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/, ZM = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g, QM = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/, e2 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g, t2 = Je.create({
  name: "bold",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "strong"
      },
      {
        tag: "b",
        getAttrs: (n) => n.style.fontWeight !== "normal" && null
      },
      {
        style: "font-weight=400",
        clearMark: (n) => n.type.name === this.name
      },
      {
        style: "font-weight",
        getAttrs: (n) => /^(bold(er)?|[5-9]\d{2,})$/.test(n) && null
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["strong", Tt(this.options.HTMLAttributes, n), 0];
  },
  addCommands() {
    return {
      setBold: () => ({ commands: n }) => n.setMark(this.name),
      toggleBold: () => ({ commands: n }) => n.toggleMark(this.name),
      unsetBold: () => ({ commands: n }) => n.unsetMark(this.name)
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-b": () => this.editor.commands.toggleBold(),
      "Mod-B": () => this.editor.commands.toggleBold()
    };
  },
  addInputRules() {
    return [
      ao({
        find: XM,
        type: this.type
      }),
      ao({
        find: QM,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      gi({
        find: ZM,
        type: this.type
      }),
      gi({
        find: e2,
        type: this.type
      })
    ];
  }
}), n2 = /(^|[^`])`([^`]+)`(?!`)/, r2 = /(^|[^`])`([^`]+)`(?!`)/g, i2 = Je.create({
  name: "code",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  excludes: "_",
  code: !0,
  exitable: !0,
  parseHTML() {
    return [
      { tag: "code" }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["code", Tt(this.options.HTMLAttributes, n), 0];
  },
  addCommands() {
    return {
      setCode: () => ({ commands: n }) => n.setMark(this.name),
      toggleCode: () => ({ commands: n }) => n.toggleMark(this.name),
      unsetCode: () => ({ commands: n }) => n.unsetMark(this.name)
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-e": () => this.editor.commands.toggleCode()
    };
  },
  addInputRules() {
    return [
      ao({
        find: n2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      gi({
        find: r2,
        type: this.type
      })
    ];
  }
}), o2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/, s2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g, l2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/, a2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g, c2 = Je.create({
  name: "italic",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "em"
      },
      {
        tag: "i",
        getAttrs: (n) => n.style.fontStyle !== "normal" && null
      },
      {
        style: "font-style=normal",
        clearMark: (n) => n.type.name === this.name
      },
      {
        style: "font-style=italic"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["em", Tt(this.options.HTMLAttributes, n), 0];
  },
  addCommands() {
    return {
      setItalic: () => ({ commands: n }) => n.setMark(this.name),
      toggleItalic: () => ({ commands: n }) => n.toggleMark(this.name),
      unsetItalic: () => ({ commands: n }) => n.unsetMark(this.name)
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-i": () => this.editor.commands.toggleItalic(),
      "Mod-I": () => this.editor.commands.toggleItalic()
    };
  },
  addInputRules() {
    return [
      ao({
        find: o2,
        type: this.type
      }),
      ao({
        find: l2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      gi({
        find: s2,
        type: this.type
      }),
      gi({
        find: a2,
        type: this.type
      })
    ];
  }
}), d2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/, u2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g, h2 = Je.create({
  name: "strike",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "s"
      },
      {
        tag: "del"
      },
      {
        tag: "strike"
      },
      {
        style: "text-decoration",
        consuming: !1,
        getAttrs: (n) => n.includes("line-through") ? {} : !1
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["s", Tt(this.options.HTMLAttributes, n), 0];
  },
  addCommands() {
    return {
      setStrike: () => ({ commands: n }) => n.setMark(this.name),
      toggleStrike: () => ({ commands: n }) => n.toggleMark(this.name),
      unsetStrike: () => ({ commands: n }) => n.unsetMark(this.name)
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-s": () => this.editor.commands.toggleStrike()
    };
  },
  addInputRules() {
    return [
      ao({
        find: d2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      gi({
        find: u2,
        type: this.type
      })
    ];
  }
}), f2 = Je.create({
  name: "underline",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "u"
      },
      {
        style: "text-decoration",
        consuming: !1,
        getAttrs: (n) => n.includes("underline") ? {} : !1
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["u", Tt(this.options.HTMLAttributes, n), 0];
  },
  addCommands() {
    return {
      setUnderline: () => ({ commands: n }) => n.setMark(this.name),
      toggleUnderline: () => ({ commands: n }) => n.toggleMark(this.name),
      unsetUnderline: () => ({ commands: n }) => n.unsetMark(this.name)
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-u": () => this.editor.commands.toggleUnderline(),
      "Mod-U": () => this.editor.commands.toggleUnderline()
    };
  }
}), p2 = Mt.create({
  name: "tableCell",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "block+",
  addAttributes() {
    return {
      colspan: {
        default: 1
      },
      rowspan: {
        default: 1
      },
      colwidth: {
        default: null,
        parseHTML: (n) => {
          const e = n.getAttribute("colwidth");
          return e ? e.split(",").map((r) => parseInt(r, 10)) : null;
        }
      }
    };
  },
  tableRole: "cell",
  isolating: !0,
  parseHTML() {
    return [
      { tag: "td" }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["td", Tt(this.options.HTMLAttributes, n), 0];
  }
}), m2 = Mt.create({
  name: "tableHeader",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "block+",
  addAttributes() {
    return {
      colspan: {
        default: 1
      },
      rowspan: {
        default: 1
      },
      colwidth: {
        default: null,
        parseHTML: (n) => {
          const e = n.getAttribute("colwidth");
          return e ? e.split(",").map((r) => parseInt(r, 10)) : null;
        }
      }
    };
  },
  tableRole: "header_cell",
  isolating: !0,
  parseHTML() {
    return [
      { tag: "th" }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["th", Tt(this.options.HTMLAttributes, n), 0];
  }
});
var Iu, Lu;
if (typeof WeakMap < "u") {
  let n = /* @__PURE__ */ new WeakMap();
  Iu = (e) => n.get(e), Lu = (e, t) => (n.set(e, t), t);
} else {
  const n = [];
  let t = 0;
  Iu = (r) => {
    for (let i = 0; i < n.length; i += 2)
      if (n[i] == r) return n[i + 1];
  }, Lu = (r, i) => (t == 10 && (t = 0), n[t++] = r, n[t++] = i);
}
var we = class {
  constructor(n, e, t, r) {
    this.width = n, this.height = e, this.map = t, this.problems = r;
  }
  // Find the dimensions of the cell at the given position.
  findCell(n) {
    for (let e = 0; e < this.map.length; e++) {
      const t = this.map[e];
      if (t != n) continue;
      const r = e % this.width, i = e / this.width | 0;
      let o = r + 1, s = i + 1;
      for (let l = 1; o < this.width && this.map[e + l] == t; l++)
        o++;
      for (let l = 1; s < this.height && this.map[e + this.width * l] == t; l++)
        s++;
      return { left: r, top: i, right: o, bottom: s };
    }
    throw new RangeError(`No cell with offset ${n} found`);
  }
  // Find the left side of the cell at the given position.
  colCount(n) {
    for (let e = 0; e < this.map.length; e++)
      if (this.map[e] == n)
        return e % this.width;
    throw new RangeError(`No cell with offset ${n} found`);
  }
  // Find the next cell in the given direction, starting from the cell
  // at `pos`, if any.
  nextCell(n, e, t) {
    const { left: r, right: i, top: o, bottom: s } = this.findCell(n);
    return e == "horiz" ? (t < 0 ? r == 0 : i == this.width) ? null : this.map[o * this.width + (t < 0 ? r - 1 : i)] : (t < 0 ? o == 0 : s == this.height) ? null : this.map[r + this.width * (t < 0 ? o - 1 : s)];
  }
  // Get the rectangle spanning the two given cells.
  rectBetween(n, e) {
    const {
      left: t,
      right: r,
      top: i,
      bottom: o
    } = this.findCell(n), {
      left: s,
      right: l,
      top: a,
      bottom: c
    } = this.findCell(e);
    return {
      left: Math.min(t, s),
      top: Math.min(i, a),
      right: Math.max(r, l),
      bottom: Math.max(o, c)
    };
  }
  // Return the position of all cells that have the top left corner in
  // the given rectangle.
  cellsInRect(n) {
    const e = [], t = {};
    for (let r = n.top; r < n.bottom; r++)
      for (let i = n.left; i < n.right; i++) {
        const o = r * this.width + i, s = this.map[o];
        t[s] || (t[s] = !0, !(i == n.left && i && this.map[o - 1] == s || r == n.top && r && this.map[o - this.width] == s) && e.push(s));
      }
    return e;
  }
  // Return the position at which the cell at the given row and column
  // starts, or would start, if a cell started there.
  positionAt(n, e, t) {
    for (let r = 0, i = 0; ; r++) {
      const o = i + t.child(r).nodeSize;
      if (r == n) {
        let s = e + n * this.width;
        const l = (n + 1) * this.width;
        for (; s < l && this.map[s] < i; ) s++;
        return s == l ? o - 1 : this.map[s];
      }
      i = o;
    }
  }
  // Find the table map for the given table node.
  static get(n) {
    return Iu(n) || Lu(n, g2(n));
  }
};
function g2(n) {
  if (n.type.spec.tableRole != "table")
    throw new RangeError("Not a table node: " + n.type.name);
  const e = b2(n), t = n.childCount, r = [];
  let i = 0, o = null;
  const s = [];
  for (let c = 0, d = e * t; c < d; c++) r[c] = 0;
  for (let c = 0, d = 0; c < t; c++) {
    const u = n.child(c);
    d++;
    for (let p = 0; ; p++) {
      for (; i < r.length && r[i] != 0; ) i++;
      if (p == u.childCount) break;
      const m = u.child(p), { colspan: g, rowspan: y, colwidth: _ } = m.attrs;
      for (let b = 0; b < y; b++) {
        if (b + c >= t) {
          (o || (o = [])).push({
            type: "overlong_rowspan",
            pos: d,
            n: y - b
          });
          break;
        }
        const k = i + b * e;
        for (let C = 0; C < g; C++) {
          r[k + C] == 0 ? r[k + C] = d : (o || (o = [])).push({
            type: "collision",
            row: c,
            pos: d,
            n: g - C
          });
          const w = _ && _[C];
          if (w) {
            const x = (k + C) % e * 2, S = s[x];
            S == null || S != w && s[x + 1] == 1 ? (s[x] = w, s[x + 1] = 1) : S == w && s[x + 1]++;
          }
        }
      }
      i += g, d += m.nodeSize;
    }
    const h = (c + 1) * e;
    let f = 0;
    for (; i < h; ) r[i++] == 0 && f++;
    f && (o || (o = [])).push({ type: "missing", row: c, n: f }), d++;
  }
  (e === 0 || t === 0) && (o || (o = [])).push({ type: "zero_sized" });
  const l = new we(e, t, r, o);
  let a = !1;
  for (let c = 0; !a && c < s.length; c += 2)
    s[c] != null && s[c + 1] < t && (a = !0);
  return a && y2(l, s, n), l;
}
function b2(n) {
  let e = -1, t = !1;
  for (let r = 0; r < n.childCount; r++) {
    const i = n.child(r);
    let o = 0;
    if (t)
      for (let s = 0; s < r; s++) {
        const l = n.child(s);
        for (let a = 0; a < l.childCount; a++) {
          const c = l.child(a);
          s + c.attrs.rowspan > r && (o += c.attrs.colspan);
        }
      }
    for (let s = 0; s < i.childCount; s++) {
      const l = i.child(s);
      o += l.attrs.colspan, l.attrs.rowspan > 1 && (t = !0);
    }
    e == -1 ? e = o : e != o && (e = Math.max(e, o));
  }
  return e;
}
function y2(n, e, t) {
  n.problems || (n.problems = []);
  const r = {};
  for (let i = 0; i < n.map.length; i++) {
    const o = n.map[i];
    if (r[o]) continue;
    r[o] = !0;
    const s = t.nodeAt(o);
    if (!s)
      throw new RangeError(`No cell with offset ${o} found`);
    let l = null;
    const a = s.attrs;
    for (let c = 0; c < a.colspan; c++) {
      const d = (i + c) % n.width, u = e[d * 2];
      u != null && (!a.colwidth || a.colwidth[c] != u) && ((l || (l = _2(a)))[c] = u);
    }
    l && n.problems.unshift({
      type: "colwidth mismatch",
      pos: o,
      colwidth: l
    });
  }
}
function _2(n) {
  if (n.colwidth) return n.colwidth.slice();
  const e = [];
  for (let t = 0; t < n.colspan; t++) e.push(0);
  return e;
}
function ot(n) {
  let e = n.cached.tableNodeTypes;
  if (!e) {
    e = n.cached.tableNodeTypes = {};
    for (const t in n.nodes) {
      const r = n.nodes[t], i = r.spec.tableRole;
      i && (e[i] = r);
    }
  }
  return e;
}
var wr = new te("selectingCells");
function bo(n) {
  for (let e = n.depth - 1; e > 0; e--)
    if (n.node(e).type.spec.tableRole == "row")
      return n.node(0).resolve(n.before(e + 1));
  return null;
}
function w2(n) {
  for (let e = n.depth; e > 0; e--) {
    const t = n.node(e).type.spec.tableRole;
    if (t === "cell" || t === "header_cell") return n.node(e);
  }
  return null;
}
function Ln(n) {
  const e = n.selection.$head;
  for (let t = e.depth; t > 0; t--)
    if (e.node(t).type.spec.tableRole == "row") return !0;
  return !1;
}
function tf(n) {
  const e = n.selection;
  if ("$anchorCell" in e && e.$anchorCell)
    return e.$anchorCell.pos > e.$headCell.pos ? e.$anchorCell : e.$headCell;
  if ("node" in e && e.node && e.node.type.spec.tableRole == "cell")
    return e.$anchor;
  const t = bo(e.$head) || k2(e.$head);
  if (t)
    return t;
  throw new RangeError(`No cell found around position ${e.head}`);
}
function k2(n) {
  for (let e = n.nodeAfter, t = n.pos; e; e = e.firstChild, t++) {
    const r = e.type.spec.tableRole;
    if (r == "cell" || r == "header_cell") return n.doc.resolve(t);
  }
  for (let e = n.nodeBefore, t = n.pos; e; e = e.lastChild, t--) {
    const r = e.type.spec.tableRole;
    if (r == "cell" || r == "header_cell")
      return n.doc.resolve(t - e.nodeSize);
  }
}
function Ru(n) {
  return n.parent.type.spec.tableRole == "row" && !!n.nodeAfter;
}
function v2(n) {
  return n.node(0).resolve(n.pos + n.nodeAfter.nodeSize);
}
function nf(n, e) {
  return n.depth == e.depth && n.pos >= e.start(-1) && n.pos <= e.end(-1);
}
function cw(n, e, t) {
  const r = n.node(-1), i = we.get(r), o = n.start(-1), s = i.nextCell(n.pos - o, e, t);
  return s == null ? null : n.node(0).resolve(o + s);
}
function bi(n, e, t = 1) {
  const r = { ...n, colspan: n.colspan - t };
  return r.colwidth && (r.colwidth = r.colwidth.slice(), r.colwidth.splice(e, t), r.colwidth.some((i) => i > 0) || (r.colwidth = null)), r;
}
function dw(n, e, t = 1) {
  const r = { ...n, colspan: n.colspan + t };
  if (r.colwidth) {
    r.colwidth = r.colwidth.slice();
    for (let i = 0; i < t; i++) r.colwidth.splice(e, 0, 0);
  }
  return r;
}
function C2(n, e, t) {
  const r = ot(e.type.schema).header_cell;
  for (let i = 0; i < n.height; i++)
    if (e.nodeAt(n.map[t + i * n.width]).type != r)
      return !1;
  return !0;
}
var le = class Kn extends V {
  // A table selection is identified by its anchor and head cells. The
  // positions given to this constructor should point _before_ two
  // cells in the same table. They may be the same, to select a single
  // cell.
  constructor(e, t = e) {
    const r = e.node(-1), i = we.get(r), o = e.start(-1), s = i.rectBetween(
      e.pos - o,
      t.pos - o
    ), l = e.node(0), a = i.cellsInRect(s).filter((d) => d != t.pos - o);
    a.unshift(t.pos - o);
    const c = a.map((d) => {
      const u = r.nodeAt(d);
      if (!u)
        throw RangeError(`No cell with offset ${d} found`);
      const h = o + d + 1;
      return new qy(
        l.resolve(h),
        l.resolve(h + u.content.size)
      );
    });
    super(c[0].$from, c[0].$to, c), this.$anchorCell = e, this.$headCell = t;
  }
  map(e, t) {
    const r = e.resolve(t.map(this.$anchorCell.pos)), i = e.resolve(t.map(this.$headCell.pos));
    if (Ru(r) && Ru(i) && nf(r, i)) {
      const o = this.$anchorCell.node(-1) != r.node(-1);
      return o && this.isRowSelection() ? Kn.rowSelection(r, i) : o && this.isColSelection() ? Kn.colSelection(r, i) : new Kn(r, i);
    }
    return L.between(r, i);
  }
  // Returns a rectangular slice of table rows containing the selected
  // cells.
  content() {
    const e = this.$anchorCell.node(-1), t = we.get(e), r = this.$anchorCell.start(-1), i = t.rectBetween(
      this.$anchorCell.pos - r,
      this.$headCell.pos - r
    ), o = {}, s = [];
    for (let a = i.top; a < i.bottom; a++) {
      const c = [];
      for (let d = a * t.width + i.left, u = i.left; u < i.right; u++, d++) {
        const h = t.map[d];
        if (o[h]) continue;
        o[h] = !0;
        const f = t.findCell(h);
        let p = e.nodeAt(h);
        if (!p)
          throw RangeError(`No cell with offset ${h} found`);
        const m = i.left - f.left, g = f.right - i.right;
        if (m > 0 || g > 0) {
          let y = p.attrs;
          if (m > 0 && (y = bi(y, 0, m)), g > 0 && (y = bi(
            y,
            y.colspan - g,
            g
          )), f.left < i.left) {
            if (p = p.type.createAndFill(y), !p)
              throw RangeError(
                `Could not create cell with attrs ${JSON.stringify(y)}`
              );
          } else
            p = p.type.create(y, p.content);
        }
        if (f.top < i.top || f.bottom > i.bottom) {
          const y = {
            ...p.attrs,
            rowspan: Math.min(f.bottom, i.bottom) - Math.max(f.top, i.top)
          };
          f.top < i.top ? p = p.type.createAndFill(y) : p = p.type.create(y, p.content);
        }
        c.push(p);
      }
      s.push(e.child(a).copy(A.from(c)));
    }
    const l = this.isColSelection() && this.isRowSelection() ? e : s;
    return new O(A.from(l), 1, 1);
  }
  replace(e, t = O.empty) {
    const r = e.steps.length, i = this.ranges;
    for (let s = 0; s < i.length; s++) {
      const { $from: l, $to: a } = i[s], c = e.mapping.slice(r);
      e.replace(
        c.map(l.pos),
        c.map(a.pos),
        s ? O.empty : t
      );
    }
    const o = V.findFrom(
      e.doc.resolve(e.mapping.slice(r).map(this.to)),
      -1
    );
    o && e.setSelection(o);
  }
  replaceWith(e, t) {
    this.replace(e, new O(A.from(t), 0, 0));
  }
  forEachCell(e) {
    const t = this.$anchorCell.node(-1), r = we.get(t), i = this.$anchorCell.start(-1), o = r.cellsInRect(
      r.rectBetween(
        this.$anchorCell.pos - i,
        this.$headCell.pos - i
      )
    );
    for (let s = 0; s < o.length; s++)
      e(t.nodeAt(o[s]), i + o[s]);
  }
  // True if this selection goes all the way from the top to the
  // bottom of the table.
  isColSelection() {
    const e = this.$anchorCell.index(-1), t = this.$headCell.index(-1);
    if (Math.min(e, t) > 0) return !1;
    const r = e + this.$anchorCell.nodeAfter.attrs.rowspan, i = t + this.$headCell.nodeAfter.attrs.rowspan;
    return Math.max(r, i) == this.$headCell.node(-1).childCount;
  }
  // Returns the smallest column selection that covers the given anchor
  // and head cell.
  static colSelection(e, t = e) {
    const r = e.node(-1), i = we.get(r), o = e.start(-1), s = i.findCell(e.pos - o), l = i.findCell(t.pos - o), a = e.node(0);
    return s.top <= l.top ? (s.top > 0 && (e = a.resolve(o + i.map[s.left])), l.bottom < i.height && (t = a.resolve(
      o + i.map[i.width * (i.height - 1) + l.right - 1]
    ))) : (l.top > 0 && (t = a.resolve(o + i.map[l.left])), s.bottom < i.height && (e = a.resolve(
      o + i.map[i.width * (i.height - 1) + s.right - 1]
    ))), new Kn(e, t);
  }
  // True if this selection goes all the way from the left to the
  // right of the table.
  isRowSelection() {
    const e = this.$anchorCell.node(-1), t = we.get(e), r = this.$anchorCell.start(-1), i = t.colCount(this.$anchorCell.pos - r), o = t.colCount(this.$headCell.pos - r);
    if (Math.min(i, o) > 0) return !1;
    const s = i + this.$anchorCell.nodeAfter.attrs.colspan, l = o + this.$headCell.nodeAfter.attrs.colspan;
    return Math.max(s, l) == t.width;
  }
  eq(e) {
    return e instanceof Kn && e.$anchorCell.pos == this.$anchorCell.pos && e.$headCell.pos == this.$headCell.pos;
  }
  // Returns the smallest row selection that covers the given anchor
  // and head cell.
  static rowSelection(e, t = e) {
    const r = e.node(-1), i = we.get(r), o = e.start(-1), s = i.findCell(e.pos - o), l = i.findCell(t.pos - o), a = e.node(0);
    return s.left <= l.left ? (s.left > 0 && (e = a.resolve(
      o + i.map[s.top * i.width]
    )), l.right < i.width && (t = a.resolve(
      o + i.map[i.width * (l.top + 1) - 1]
    ))) : (l.left > 0 && (t = a.resolve(o + i.map[l.top * i.width])), s.right < i.width && (e = a.resolve(
      o + i.map[i.width * (s.top + 1) - 1]
    ))), new Kn(e, t);
  }
  toJSON() {
    return {
      type: "cell",
      anchor: this.$anchorCell.pos,
      head: this.$headCell.pos
    };
  }
  static fromJSON(e, t) {
    return new Kn(e.resolve(t.anchor), e.resolve(t.head));
  }
  static create(e, t, r = t) {
    return new Kn(e.resolve(t), e.resolve(r));
  }
  getBookmark() {
    return new S2(this.$anchorCell.pos, this.$headCell.pos);
  }
};
le.prototype.visible = !1;
V.jsonID("cell", le);
var S2 = class uw {
  constructor(e, t) {
    this.anchor = e, this.head = t;
  }
  map(e) {
    return new uw(e.map(this.anchor), e.map(this.head));
  }
  resolve(e) {
    const t = e.resolve(this.anchor), r = e.resolve(this.head);
    return t.parent.type.spec.tableRole == "row" && r.parent.type.spec.tableRole == "row" && t.index() < t.parent.childCount && r.index() < r.parent.childCount && nf(t, r) ? new le(t, r) : V.near(r, 1);
  }
};
function E2(n) {
  if (!(n.selection instanceof le)) return null;
  const e = [];
  return n.selection.forEachCell((t, r) => {
    e.push(
      se.node(r, r + t.nodeSize, { class: "selectedCell" })
    );
  }), Q.create(n.doc, e);
}
function x2({ $from: n, $to: e }) {
  if (n.pos == e.pos || n.pos < e.pos - 6) return !1;
  let t = n.pos, r = e.pos, i = n.depth;
  for (; i >= 0 && !(n.after(i + 1) < n.end(i)); i--, t++)
    ;
  for (let o = e.depth; o >= 0 && !(e.before(o + 1) > e.start(o)); o--, r--)
    ;
  return t == r && /row|table/.test(n.node(i).type.spec.tableRole);
}
function D2({ $from: n, $to: e }) {
  let t, r;
  for (let i = n.depth; i > 0; i--) {
    const o = n.node(i);
    if (o.type.spec.tableRole === "cell" || o.type.spec.tableRole === "header_cell") {
      t = o;
      break;
    }
  }
  for (let i = e.depth; i > 0; i--) {
    const o = e.node(i);
    if (o.type.spec.tableRole === "cell" || o.type.spec.tableRole === "header_cell") {
      r = o;
      break;
    }
  }
  return t !== r && e.parentOffset === 0;
}
function A2(n, e, t) {
  const r = (e || n).selection, i = (e || n).doc;
  let o, s;
  if (r instanceof P && (s = r.node.type.spec.tableRole)) {
    if (s == "cell" || s == "header_cell")
      o = le.create(i, r.from);
    else if (s == "row") {
      const l = i.resolve(r.from + 1);
      o = le.rowSelection(l, l);
    } else if (!t) {
      const l = we.get(r.node), a = r.from + 1, c = a + l.map[l.width * l.height - 1];
      o = le.create(i, a + 1, c);
    }
  } else r instanceof L && x2(r) ? o = L.create(i, r.from) : r instanceof L && D2(r) && (o = L.create(i, r.$from.start(), r.$from.end()));
  return o && (e || (e = n.tr)).setSelection(o), e;
}
var T2 = new te("fix-tables");
function hw(n, e, t, r) {
  const i = n.childCount, o = e.childCount;
  e: for (let s = 0, l = 0; s < o; s++) {
    const a = e.child(s);
    for (let c = l, d = Math.min(i, s + 3); c < d; c++)
      if (n.child(c) == a) {
        l = c + 1, t += a.nodeSize;
        continue e;
      }
    r(a, t), l < i && n.child(l).sameMarkup(a) ? hw(n.child(l), a, t + 1, r) : a.nodesBetween(0, a.content.size, r, t + 1), t += a.nodeSize;
  }
}
function M2(n, e) {
  let t;
  const r = (i, o) => {
    i.type.spec.tableRole == "table" && (t = O2(n, i, o, t));
  };
  return e ? e.doc != n.doc && hw(e.doc, n.doc, 0, r) : n.doc.descendants(r), t;
}
function O2(n, e, t, r) {
  const i = we.get(e);
  if (!i.problems) return r;
  r || (r = n.tr);
  const o = [];
  for (let a = 0; a < i.height; a++) o.push(0);
  for (let a = 0; a < i.problems.length; a++) {
    const c = i.problems[a];
    if (c.type == "collision") {
      const d = e.nodeAt(c.pos);
      if (!d) continue;
      const u = d.attrs;
      for (let h = 0; h < u.rowspan; h++) o[c.row + h] += c.n;
      r.setNodeMarkup(
        r.mapping.map(t + 1 + c.pos),
        null,
        bi(u, u.colspan - c.n, c.n)
      );
    } else if (c.type == "missing")
      o[c.row] += c.n;
    else if (c.type == "overlong_rowspan") {
      const d = e.nodeAt(c.pos);
      if (!d) continue;
      r.setNodeMarkup(r.mapping.map(t + 1 + c.pos), null, {
        ...d.attrs,
        rowspan: d.attrs.rowspan - c.n
      });
    } else if (c.type == "colwidth mismatch") {
      const d = e.nodeAt(c.pos);
      if (!d) continue;
      r.setNodeMarkup(r.mapping.map(t + 1 + c.pos), null, {
        ...d.attrs,
        colwidth: c.colwidth
      });
    } else if (c.type == "zero_sized") {
      const d = r.mapping.map(t);
      r.delete(d, d + e.nodeSize);
    }
  }
  let s, l;
  for (let a = 0; a < o.length; a++)
    o[a] && (s == null && (s = a), l = a);
  for (let a = 0, c = t + 1; a < i.height; a++) {
    const d = e.child(a), u = c + d.nodeSize, h = o[a];
    if (h > 0) {
      let f = "cell";
      d.firstChild && (f = d.firstChild.type.spec.tableRole);
      const p = [];
      for (let g = 0; g < h; g++) {
        const y = ot(n.schema)[f].createAndFill();
        y && p.push(y);
      }
      const m = (a == 0 || s == a - 1) && l == a ? c + 1 : u - 1;
      r.insert(r.mapping.map(m), p);
    }
    c = u;
  }
  return r.setMeta(T2, { fixTables: !0 });
}
function Rn(n) {
  const e = n.selection, t = tf(n), r = t.node(-1), i = t.start(-1), o = we.get(r);
  return { ...e instanceof le ? o.rectBetween(
    e.$anchorCell.pos - i,
    e.$headCell.pos - i
  ) : o.findCell(t.pos - i), tableStart: i, map: o, table: r };
}
function fw(n, { map: e, tableStart: t, table: r }, i) {
  let o = i > 0 ? -1 : 0;
  C2(e, r, i + o) && (o = i == 0 || i == e.width ? null : 0);
  for (let s = 0; s < e.height; s++) {
    const l = s * e.width + i;
    if (i > 0 && i < e.width && e.map[l - 1] == e.map[l]) {
      const a = e.map[l], c = r.nodeAt(a);
      n.setNodeMarkup(
        n.mapping.map(t + a),
        null,
        dw(c.attrs, i - e.colCount(a))
      ), s += c.attrs.rowspan - 1;
    } else {
      const a = o == null ? ot(r.type.schema).cell : r.nodeAt(e.map[l + o]).type, c = e.positionAt(s, i, r);
      n.insert(n.mapping.map(t + c), a.createAndFill());
    }
  }
  return n;
}
function F2(n, e) {
  if (!Ln(n)) return !1;
  if (e) {
    const t = Rn(n);
    e(fw(n.tr, t, t.left));
  }
  return !0;
}
function N2(n, e) {
  if (!Ln(n)) return !1;
  if (e) {
    const t = Rn(n);
    e(fw(n.tr, t, t.right));
  }
  return !0;
}
function $2(n, { map: e, table: t, tableStart: r }, i) {
  const o = n.mapping.maps.length;
  for (let s = 0; s < e.height; ) {
    const l = s * e.width + i, a = e.map[l], c = t.nodeAt(a), d = c.attrs;
    if (i > 0 && e.map[l - 1] == a || i < e.width - 1 && e.map[l + 1] == a)
      n.setNodeMarkup(
        n.mapping.slice(o).map(r + a),
        null,
        bi(d, i - e.colCount(a))
      );
    else {
      const u = n.mapping.slice(o).map(r + a);
      n.delete(u, u + c.nodeSize);
    }
    s += d.rowspan;
  }
}
function I2(n, e) {
  if (!Ln(n)) return !1;
  if (e) {
    const t = Rn(n), r = n.tr;
    if (t.left == 0 && t.right == t.map.width) return !1;
    for (let i = t.right - 1; $2(r, t, i), i != t.left; i--) {
      const o = t.tableStart ? r.doc.nodeAt(t.tableStart - 1) : r.doc;
      if (!o)
        throw RangeError("No table found");
      t.table = o, t.map = we.get(o);
    }
    e(r);
  }
  return !0;
}
function L2(n, e, t) {
  var r;
  const i = ot(e.type.schema).header_cell;
  for (let o = 0; o < n.width; o++)
    if (((r = e.nodeAt(n.map[o + t * n.width])) == null ? void 0 : r.type) != i)
      return !1;
  return !0;
}
function pw(n, { map: e, tableStart: t, table: r }, i) {
  var o;
  let s = t;
  for (let c = 0; c < i; c++) s += r.child(c).nodeSize;
  const l = [];
  let a = i > 0 ? -1 : 0;
  L2(e, r, i + a) && (a = i == 0 || i == e.height ? null : 0);
  for (let c = 0, d = e.width * i; c < e.width; c++, d++)
    if (i > 0 && i < e.height && e.map[d] == e.map[d - e.width]) {
      const u = e.map[d], h = r.nodeAt(u).attrs;
      n.setNodeMarkup(t + u, null, {
        ...h,
        rowspan: h.rowspan + 1
      }), c += h.colspan - 1;
    } else {
      const u = a == null ? ot(r.type.schema).cell : (o = r.nodeAt(e.map[d + a * e.width])) == null ? void 0 : o.type, h = u == null ? void 0 : u.createAndFill();
      h && l.push(h);
    }
  return n.insert(s, ot(r.type.schema).row.create(null, l)), n;
}
function R2(n, e) {
  if (!Ln(n)) return !1;
  if (e) {
    const t = Rn(n);
    e(pw(n.tr, t, t.top));
  }
  return !0;
}
function B2(n, e) {
  if (!Ln(n)) return !1;
  if (e) {
    const t = Rn(n);
    e(pw(n.tr, t, t.bottom));
  }
  return !0;
}
function P2(n, { map: e, table: t, tableStart: r }, i) {
  let o = 0;
  for (let c = 0; c < i; c++) o += t.child(c).nodeSize;
  const s = o + t.child(i).nodeSize, l = n.mapping.maps.length;
  n.delete(o + r, s + r);
  const a = /* @__PURE__ */ new Set();
  for (let c = 0, d = i * e.width; c < e.width; c++, d++) {
    const u = e.map[d];
    if (!a.has(u)) {
      if (a.add(u), i > 0 && u == e.map[d - e.width]) {
        const h = t.nodeAt(u).attrs;
        n.setNodeMarkup(n.mapping.slice(l).map(u + r), null, {
          ...h,
          rowspan: h.rowspan - 1
        }), c += h.colspan - 1;
      } else if (i < e.height && u == e.map[d + e.width]) {
        const h = t.nodeAt(u), f = h.attrs, p = h.type.create(
          { ...f, rowspan: h.attrs.rowspan - 1 },
          h.content
        ), m = e.positionAt(i + 1, c, t);
        n.insert(n.mapping.slice(l).map(r + m), p), c += f.colspan - 1;
      }
    }
  }
}
function z2(n, e) {
  if (!Ln(n)) return !1;
  if (e) {
    const t = Rn(n), r = n.tr;
    if (t.top == 0 && t.bottom == t.map.height) return !1;
    for (let i = t.bottom - 1; P2(r, t, i), i != t.top; i--) {
      const o = t.tableStart ? r.doc.nodeAt(t.tableStart - 1) : r.doc;
      if (!o)
        throw RangeError("No table found");
      t.table = o, t.map = we.get(t.table);
    }
    e(r);
  }
  return !0;
}
function Hg(n) {
  const e = n.content;
  return e.childCount == 1 && e.child(0).isTextblock && e.child(0).childCount == 0;
}
function H2({ width: n, height: e, map: t }, r) {
  let i = r.top * n + r.left, o = i, s = (r.bottom - 1) * n + r.left, l = i + (r.right - r.left - 1);
  for (let a = r.top; a < r.bottom; a++) {
    if (r.left > 0 && t[o] == t[o - 1] || r.right < n && t[l] == t[l + 1])
      return !0;
    o += n, l += n;
  }
  for (let a = r.left; a < r.right; a++) {
    if (r.top > 0 && t[i] == t[i - n] || r.bottom < e && t[s] == t[s + n])
      return !0;
    i++, s++;
  }
  return !1;
}
function V2(n, e) {
  const t = n.selection;
  if (!(t instanceof le) || t.$anchorCell.pos == t.$headCell.pos)
    return !1;
  const r = Rn(n), { map: i } = r;
  if (H2(i, r)) return !1;
  if (e) {
    const o = n.tr, s = {};
    let l = A.empty, a, c;
    for (let d = r.top; d < r.bottom; d++)
      for (let u = r.left; u < r.right; u++) {
        const h = i.map[d * i.width + u], f = r.table.nodeAt(h);
        if (!(s[h] || !f))
          if (s[h] = !0, a == null)
            a = h, c = f;
          else {
            Hg(f) || (l = l.append(f.content));
            const p = o.mapping.map(h + r.tableStart);
            o.delete(p, p + f.nodeSize);
          }
      }
    if (a == null || c == null)
      return !0;
    if (o.setNodeMarkup(a + r.tableStart, null, {
      ...dw(
        c.attrs,
        c.attrs.colspan,
        r.right - r.left - c.attrs.colspan
      ),
      rowspan: r.bottom - r.top
    }), l.size) {
      const d = a + 1 + c.content.size, u = Hg(c) ? a + 1 : d;
      o.replaceWith(u + r.tableStart, d + r.tableStart, l);
    }
    o.setSelection(
      new le(o.doc.resolve(a + r.tableStart))
    ), e(o);
  }
  return !0;
}
function U2(n, e) {
  const t = ot(n.schema);
  return q2(({ node: r }) => t[r.type.spec.tableRole])(n, e);
}
function q2(n) {
  return (e, t) => {
    var r;
    const i = e.selection;
    let o, s;
    if (i instanceof le) {
      if (i.$anchorCell.pos != i.$headCell.pos) return !1;
      o = i.$anchorCell.nodeAfter, s = i.$anchorCell.pos;
    } else {
      if (o = w2(i.$from), !o) return !1;
      s = (r = bo(i.$from)) == null ? void 0 : r.pos;
    }
    if (o == null || s == null || o.attrs.colspan == 1 && o.attrs.rowspan == 1)
      return !1;
    if (t) {
      let l = o.attrs;
      const a = [], c = l.colwidth;
      l.rowspan > 1 && (l = { ...l, rowspan: 1 }), l.colspan > 1 && (l = { ...l, colspan: 1 });
      const d = Rn(e), u = e.tr;
      for (let f = 0; f < d.right - d.left; f++)
        a.push(
          c ? {
            ...l,
            colwidth: c && c[f] ? [c[f]] : null
          } : l
        );
      let h;
      for (let f = d.top; f < d.bottom; f++) {
        let p = d.map.positionAt(f, d.left, d.table);
        f == d.top && (p += o.nodeSize);
        for (let m = d.left, g = 0; m < d.right; m++, g++)
          m == d.left && f == d.top || u.insert(
            h = u.mapping.map(p + d.tableStart, 1),
            n({ node: o, row: f, col: m }).createAndFill(a[g])
          );
      }
      u.setNodeMarkup(
        s,
        n({ node: o, row: d.top, col: d.left }),
        a[0]
      ), i instanceof le && u.setSelection(
        new le(
          u.doc.resolve(i.$anchorCell.pos),
          h ? u.doc.resolve(h) : void 0
        )
      ), t(u);
    }
    return !0;
  };
}
function j2(n) {
  return function(e, t) {
    if (!Ln(e)) return !1;
    if (t) {
      const r = ot(e.schema), i = Rn(e), o = e.tr, s = i.map.cellsInRect(
        n == "column" ? {
          left: i.left,
          top: 0,
          right: i.right,
          bottom: i.map.height
        } : n == "row" ? {
          left: 0,
          top: i.top,
          right: i.map.width,
          bottom: i.bottom
        } : i
      ), l = s.map((a) => i.table.nodeAt(a));
      for (let a = 0; a < s.length; a++)
        l[a].type == r.header_cell && o.setNodeMarkup(
          i.tableStart + s[a],
          r.cell,
          l[a].attrs
        );
      if (o.steps.length == 0)
        for (let a = 0; a < s.length; a++)
          o.setNodeMarkup(
            i.tableStart + s[a],
            r.header_cell,
            l[a].attrs
          );
      t(o);
    }
    return !0;
  };
}
function Vg(n, e, t) {
  const r = e.map.cellsInRect({
    left: 0,
    top: 0,
    right: n == "row" ? e.map.width : 1,
    bottom: n == "column" ? e.map.height : 1
  });
  for (let i = 0; i < r.length; i++) {
    const o = e.table.nodeAt(r[i]);
    if (o && o.type !== t.header_cell)
      return !1;
  }
  return !0;
}
function rf(n, e) {
  return e = e || { useDeprecatedLogic: !1 }, e.useDeprecatedLogic ? j2(n) : function(t, r) {
    if (!Ln(t)) return !1;
    if (r) {
      const i = ot(t.schema), o = Rn(t), s = t.tr, l = Vg("row", o, i), a = Vg(
        "column",
        o,
        i
      ), d = (n === "column" ? l : n === "row" ? a : !1) ? 1 : 0, u = n == "column" ? {
        left: 0,
        top: d,
        right: 1,
        bottom: o.map.height
      } : n == "row" ? {
        left: d,
        top: 0,
        right: o.map.width,
        bottom: 1
      } : o, h = n == "column" ? a ? i.cell : i.header_cell : n == "row" ? l ? i.cell : i.header_cell : i.cell;
      o.map.cellsInRect(u).forEach((f) => {
        const p = f + o.tableStart, m = s.doc.nodeAt(p);
        m && s.setNodeMarkup(p, h, m.attrs);
      }), r(s);
    }
    return !0;
  };
}
rf("row", {
  useDeprecatedLogic: !0
});
rf("column", {
  useDeprecatedLogic: !0
});
rf("cell", {
  useDeprecatedLogic: !0
});
function W2(n, e) {
  if (e < 0) {
    const t = n.nodeBefore;
    if (t) return n.pos - t.nodeSize;
    for (let r = n.index(-1) - 1, i = n.before(); r >= 0; r--) {
      const o = n.node(-1).child(r), s = o.lastChild;
      if (s)
        return i - 1 - s.nodeSize;
      i -= o.nodeSize;
    }
  } else {
    if (n.index() < n.parent.childCount - 1)
      return n.pos + n.nodeAfter.nodeSize;
    const t = n.node(-1);
    for (let r = n.indexAfter(-1), i = n.after(); r < t.childCount; r++) {
      const o = t.child(r);
      if (o.childCount) return i + 1;
      i += o.nodeSize;
    }
  }
  return null;
}
function Ug(n) {
  return function(e, t) {
    if (!Ln(e)) return !1;
    const r = W2(tf(e), n);
    if (r == null) return !1;
    if (t) {
      const i = e.doc.resolve(r);
      t(
        e.tr.setSelection(L.between(i, v2(i))).scrollIntoView()
      );
    }
    return !0;
  };
}
function xl(n, e) {
  const t = n.selection;
  if (!(t instanceof le)) return !1;
  if (e) {
    const r = n.tr, i = ot(n.schema).cell.createAndFill().content;
    t.forEachCell((o, s) => {
      o.content.eq(i) || r.replace(
        r.mapping.map(s + 1),
        r.mapping.map(s + o.nodeSize - 1),
        new O(i, 0, 0)
      );
    }), r.docChanged && e(r);
  }
  return !0;
}
function G2(n) {
  if (!n.size) return null;
  let { content: e, openStart: t, openEnd: r } = n;
  for (; e.childCount == 1 && (t > 0 && r > 0 || e.child(0).type.spec.tableRole == "table"); )
    t--, r--, e = e.child(0).content;
  const i = e.child(0), o = i.type.spec.tableRole, s = i.type.schema, l = [];
  if (o == "row")
    for (let a = 0; a < e.childCount; a++) {
      let c = e.child(a).content;
      const d = a ? 0 : Math.max(0, t - 1), u = a < e.childCount - 1 ? 0 : Math.max(0, r - 1);
      (d || u) && (c = Bu(
        ot(s).row,
        new O(c, d, u)
      ).content), l.push(c);
    }
  else if (o == "cell" || o == "header_cell")
    l.push(
      t || r ? Bu(
        ot(s).row,
        new O(e, t, r)
      ).content : e
    );
  else
    return null;
  return K2(s, l);
}
function K2(n, e) {
  const t = [];
  for (let i = 0; i < e.length; i++) {
    const o = e[i];
    for (let s = o.childCount - 1; s >= 0; s--) {
      const { rowspan: l, colspan: a } = o.child(s).attrs;
      for (let c = i; c < i + l; c++)
        t[c] = (t[c] || 0) + a;
    }
  }
  let r = 0;
  for (let i = 0; i < t.length; i++) r = Math.max(r, t[i]);
  for (let i = 0; i < t.length; i++)
    if (i >= e.length && e.push(A.empty), t[i] < r) {
      const o = ot(n).cell.createAndFill(), s = [];
      for (let l = t[i]; l < r; l++)
        s.push(o);
      e[i] = e[i].append(A.from(s));
    }
  return { height: e.length, width: r, rows: e };
}
function Bu(n, e) {
  const t = n.createAndFill();
  return new Oh(t).replace(0, t.content.size, e).doc;
}
function J2({ width: n, height: e, rows: t }, r, i) {
  if (n != r) {
    const o = [], s = [];
    for (let l = 0; l < t.length; l++) {
      const a = t[l], c = [];
      for (let d = o[l] || 0, u = 0; d < r; u++) {
        let h = a.child(u % a.childCount);
        d + h.attrs.colspan > r && (h = h.type.createChecked(
          bi(
            h.attrs,
            h.attrs.colspan,
            d + h.attrs.colspan - r
          ),
          h.content
        )), c.push(h), d += h.attrs.colspan;
        for (let f = 1; f < h.attrs.rowspan; f++)
          o[l + f] = (o[l + f] || 0) + h.attrs.colspan;
      }
      s.push(A.from(c));
    }
    t = s, n = r;
  }
  if (e != i) {
    const o = [];
    for (let s = 0, l = 0; s < i; s++, l++) {
      const a = [], c = t[l % e];
      for (let d = 0; d < c.childCount; d++) {
        let u = c.child(d);
        s + u.attrs.rowspan > i && (u = u.type.create(
          {
            ...u.attrs,
            rowspan: Math.max(1, i - u.attrs.rowspan)
          },
          u.content
        )), a.push(u);
      }
      o.push(A.from(a));
    }
    t = o, e = i;
  }
  return { width: n, height: e, rows: t };
}
function Y2(n, e, t, r, i, o, s) {
  const l = n.doc.type.schema, a = ot(l);
  let c, d;
  if (i > e.width)
    for (let u = 0, h = 0; u < e.height; u++) {
      const f = t.child(u);
      h += f.nodeSize;
      const p = [];
      let m;
      f.lastChild == null || f.lastChild.type == a.cell ? m = c || (c = a.cell.createAndFill()) : m = d || (d = a.header_cell.createAndFill());
      for (let g = e.width; g < i; g++) p.push(m);
      n.insert(n.mapping.slice(s).map(h - 1 + r), p);
    }
  if (o > e.height) {
    const u = [];
    for (let p = 0, m = (e.height - 1) * e.width; p < Math.max(e.width, i); p++) {
      const g = p >= e.width ? !1 : t.nodeAt(e.map[m + p]).type == a.header_cell;
      u.push(
        g ? d || (d = a.header_cell.createAndFill()) : c || (c = a.cell.createAndFill())
      );
    }
    const h = a.row.create(null, A.from(u)), f = [];
    for (let p = e.height; p < o; p++) f.push(h);
    n.insert(n.mapping.slice(s).map(r + t.nodeSize - 2), f);
  }
  return !!(c || d);
}
function qg(n, e, t, r, i, o, s, l) {
  if (s == 0 || s == e.height) return !1;
  let a = !1;
  for (let c = i; c < o; c++) {
    const d = s * e.width + c, u = e.map[d];
    if (e.map[d - e.width] == u) {
      a = !0;
      const h = t.nodeAt(u), { top: f, left: p } = e.findCell(u);
      n.setNodeMarkup(n.mapping.slice(l).map(u + r), null, {
        ...h.attrs,
        rowspan: s - f
      }), n.insert(
        n.mapping.slice(l).map(e.positionAt(s, p, t)),
        h.type.createAndFill({
          ...h.attrs,
          rowspan: f + h.attrs.rowspan - s
        })
      ), c += h.attrs.colspan - 1;
    }
  }
  return a;
}
function jg(n, e, t, r, i, o, s, l) {
  if (s == 0 || s == e.width) return !1;
  let a = !1;
  for (let c = i; c < o; c++) {
    const d = c * e.width + s, u = e.map[d];
    if (e.map[d - 1] == u) {
      a = !0;
      const h = t.nodeAt(u), f = e.colCount(u), p = n.mapping.slice(l).map(u + r);
      n.setNodeMarkup(
        p,
        null,
        bi(
          h.attrs,
          s - f,
          h.attrs.colspan - (s - f)
        )
      ), n.insert(
        p + h.nodeSize,
        h.type.createAndFill(
          bi(h.attrs, 0, s - f)
        )
      ), c += h.attrs.rowspan - 1;
    }
  }
  return a;
}
function Wg(n, e, t, r, i) {
  let o = t ? n.doc.nodeAt(t - 1) : n.doc;
  if (!o)
    throw new Error("No table found");
  let s = we.get(o);
  const { top: l, left: a } = r, c = a + i.width, d = l + i.height, u = n.tr;
  let h = 0;
  function f() {
    if (o = t ? u.doc.nodeAt(t - 1) : u.doc, !o)
      throw new Error("No table found");
    s = we.get(o), h = u.mapping.maps.length;
  }
  Y2(u, s, o, t, c, d, h) && f(), qg(u, s, o, t, a, c, l, h) && f(), qg(u, s, o, t, a, c, d, h) && f(), jg(u, s, o, t, l, d, a, h) && f(), jg(u, s, o, t, l, d, c, h) && f();
  for (let p = l; p < d; p++) {
    const m = s.positionAt(p, a, o), g = s.positionAt(p, c, o);
    u.replace(
      u.mapping.slice(h).map(m + t),
      u.mapping.slice(h).map(g + t),
      new O(i.rows[p - l], 0, 0)
    );
  }
  f(), u.setSelection(
    new le(
      u.doc.resolve(t + s.positionAt(l, a, o)),
      u.doc.resolve(t + s.positionAt(d - 1, c - 1, o))
    )
  ), e(u);
}
var X2 = Uh({
  ArrowLeft: Dl("horiz", -1),
  ArrowRight: Dl("horiz", 1),
  ArrowUp: Dl("vert", -1),
  ArrowDown: Dl("vert", 1),
  "Shift-ArrowLeft": Al("horiz", -1),
  "Shift-ArrowRight": Al("horiz", 1),
  "Shift-ArrowUp": Al("vert", -1),
  "Shift-ArrowDown": Al("vert", 1),
  Backspace: xl,
  "Mod-Backspace": xl,
  Delete: xl,
  "Mod-Delete": xl
});
function Yl(n, e, t) {
  return t.eq(n.selection) ? !1 : (e && e(n.tr.setSelection(t).scrollIntoView()), !0);
}
function Dl(n, e) {
  return (t, r, i) => {
    if (!i) return !1;
    const o = t.selection;
    if (o instanceof le)
      return Yl(
        t,
        r,
        V.near(o.$headCell, e)
      );
    if (n != "horiz" && !o.empty) return !1;
    const s = mw(i, n, e);
    if (s == null) return !1;
    if (n == "horiz")
      return Yl(
        t,
        r,
        V.near(t.doc.resolve(o.head + e), e)
      );
    {
      const l = t.doc.resolve(s), a = cw(l, n, e);
      let c;
      return a ? c = V.near(a, 1) : e < 0 ? c = V.near(t.doc.resolve(l.before(-1)), -1) : c = V.near(t.doc.resolve(l.after(-1)), 1), Yl(t, r, c);
    }
  };
}
function Al(n, e) {
  return (t, r, i) => {
    if (!i) return !1;
    const o = t.selection;
    let s;
    if (o instanceof le)
      s = o;
    else {
      const a = mw(i, n, e);
      if (a == null) return !1;
      s = new le(t.doc.resolve(a));
    }
    const l = cw(s.$headCell, n, e);
    return l ? Yl(
      t,
      r,
      new le(s.$anchorCell, l)
    ) : !1;
  };
}
function Z2(n, e) {
  const t = n.state.doc, r = bo(t.resolve(e));
  return r ? (n.dispatch(n.state.tr.setSelection(new le(r))), !0) : !1;
}
function Q2(n, e, t) {
  if (!Ln(n.state)) return !1;
  let r = G2(t);
  const i = n.state.selection;
  if (i instanceof le) {
    r || (r = {
      width: 1,
      height: 1,
      rows: [
        A.from(
          Bu(ot(n.state.schema).cell, t)
        )
      ]
    });
    const o = i.$anchorCell.node(-1), s = i.$anchorCell.start(-1), l = we.get(o).rectBetween(
      i.$anchorCell.pos - s,
      i.$headCell.pos - s
    );
    return r = J2(r, l.right - l.left, l.bottom - l.top), Wg(n.state, n.dispatch, s, l, r), !0;
  } else if (r) {
    const o = tf(n.state), s = o.start(-1);
    return Wg(
      n.state,
      n.dispatch,
      s,
      we.get(o.node(-1)).findCell(o.pos - s),
      r
    ), !0;
  } else
    return !1;
}
function eO(n, e) {
  var t;
  if (e.ctrlKey || e.metaKey) return;
  const r = Gg(n, e.target);
  let i;
  if (e.shiftKey && n.state.selection instanceof le)
    o(n.state.selection.$anchorCell, e), e.preventDefault();
  else if (e.shiftKey && r && (i = bo(n.state.selection.$anchor)) != null && ((t = Nd(n, e)) == null ? void 0 : t.pos) != i.pos)
    o(i, e), e.preventDefault();
  else if (!r)
    return;
  function o(a, c) {
    let d = Nd(n, c);
    const u = wr.getState(n.state) == null;
    if (!d || !nf(a, d))
      if (u) d = a;
      else return;
    const h = new le(a, d);
    if (u || !n.state.selection.eq(h)) {
      const f = n.state.tr.setSelection(h);
      u && f.setMeta(wr, a.pos), n.dispatch(f);
    }
  }
  function s() {
    n.root.removeEventListener("mouseup", s), n.root.removeEventListener("dragstart", s), n.root.removeEventListener("mousemove", l), wr.getState(n.state) != null && n.dispatch(n.state.tr.setMeta(wr, -1));
  }
  function l(a) {
    const c = a, d = wr.getState(n.state);
    let u;
    if (d != null)
      u = n.state.doc.resolve(d);
    else if (Gg(n, c.target) != r && (u = Nd(n, e), !u))
      return s();
    u && o(u, c);
  }
  n.root.addEventListener("mouseup", s), n.root.addEventListener("dragstart", s), n.root.addEventListener("mousemove", l);
}
function mw(n, e, t) {
  if (!(n.state.selection instanceof L)) return null;
  const { $head: r } = n.state.selection;
  for (let i = r.depth - 1; i >= 0; i--) {
    const o = r.node(i);
    if ((t < 0 ? r.index(i) : r.indexAfter(i)) != (t < 0 ? 0 : o.childCount)) return null;
    if (o.type.spec.tableRole == "cell" || o.type.spec.tableRole == "header_cell") {
      const l = r.before(i), a = e == "vert" ? t > 0 ? "down" : "up" : t > 0 ? "right" : "left";
      return n.endOfTextblock(a) ? l : null;
    }
  }
  return null;
}
function Gg(n, e) {
  for (; e && e != n.dom; e = e.parentNode)
    if (e.nodeName == "TD" || e.nodeName == "TH")
      return e;
  return null;
}
function Nd(n, e) {
  const t = n.posAtCoords({
    left: e.clientX,
    top: e.clientY
  });
  return t && t ? bo(n.state.doc.resolve(t.pos)) : null;
}
var gw = class {
  constructor(n, e) {
    this.node = n, this.defaultCellMinWidth = e, 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",
      `${e}px`
    ), this.colgroup = this.table.appendChild(document.createElement("colgroup")), Pu(n, this.colgroup, this.table, e), this.contentDOM = this.table.appendChild(document.createElement("tbody"));
  }
  update(n) {
    return n.type != this.node.type ? !1 : (this.node = n, Pu(
      n,
      this.colgroup,
      this.table,
      this.defaultCellMinWidth
    ), !0);
  }
  ignoreMutation(n) {
    return n.type == "attributes" && (n.target == this.table || this.colgroup.contains(n.target));
  }
};
function Pu(n, e, t, r, i, o) {
  var s;
  let l = 0, a = !0, c = e.firstChild;
  const d = n.firstChild;
  if (d) {
    for (let u = 0, h = 0; u < d.childCount; u++) {
      const { colspan: f, colwidth: p } = d.child(u).attrs;
      for (let m = 0; m < f; m++, h++) {
        const g = i == h ? o : p && p[m], y = g ? g + "px" : "";
        if (l += g || r, g || (a = !1), c)
          c.style.width != y && (c.style.width = y), c = c.nextSibling;
        else {
          const _ = document.createElement("col");
          _.style.width = y, e.appendChild(_);
        }
      }
    }
    for (; c; ) {
      const u = c.nextSibling;
      (s = c.parentNode) == null || s.removeChild(c), c = u;
    }
    a ? (t.style.width = l + "px", t.style.minWidth = "") : (t.style.width = "", t.style.minWidth = l + "px");
  }
}
var Dt = new te(
  "tableColumnResizing"
);
function tO({
  handleWidth: n = 5,
  cellMinWidth: e = 25,
  defaultCellMinWidth: t = 100,
  View: r = gw,
  lastColumnResizable: i = !0
} = {}) {
  const o = new G({
    key: Dt,
    state: {
      init(s, l) {
        var a, c;
        const d = (c = (a = o.spec) == null ? void 0 : a.props) == null ? void 0 : c.nodeViews, u = ot(l.schema).table.name;
        return r && d && (d[u] = (h, f) => new r(h, t, f)), new nO(-1, !1);
      },
      apply(s, l) {
        return l.apply(s);
      }
    },
    props: {
      attributes: (s) => {
        const l = Dt.getState(s);
        return l && l.activeHandle > -1 ? { class: "resize-cursor" } : {};
      },
      handleDOMEvents: {
        mousemove: (s, l) => {
          rO(s, l, n, i);
        },
        mouseleave: (s) => {
          iO(s);
        },
        mousedown: (s, l) => {
          oO(s, l, e, t);
        }
      },
      decorations: (s) => {
        const l = Dt.getState(s);
        if (l && l.activeHandle > -1)
          return dO(s, l.activeHandle);
      },
      nodeViews: {}
    }
  });
  return o;
}
var nO = class Xl {
  constructor(e, t) {
    this.activeHandle = e, this.dragging = t;
  }
  apply(e) {
    const t = this, r = e.getMeta(Dt);
    if (r && r.setHandle != null)
      return new Xl(r.setHandle, !1);
    if (r && r.setDragging !== void 0)
      return new Xl(t.activeHandle, r.setDragging);
    if (t.activeHandle > -1 && e.docChanged) {
      let i = e.mapping.map(t.activeHandle, -1);
      return Ru(e.doc.resolve(i)) || (i = -1), new Xl(i, t.dragging);
    }
    return t;
  }
};
function rO(n, e, t, r) {
  if (!n.editable) return;
  const i = Dt.getState(n.state);
  if (i && !i.dragging) {
    const o = lO(e.target);
    let s = -1;
    if (o) {
      const { left: l, right: a } = o.getBoundingClientRect();
      e.clientX - l <= t ? s = Kg(n, e, "left", t) : a - e.clientX <= t && (s = Kg(n, e, "right", t));
    }
    if (s != i.activeHandle) {
      if (!r && s !== -1) {
        const l = n.state.doc.resolve(s), a = l.node(-1), c = we.get(a), d = l.start(-1);
        if (c.colCount(l.pos - d) + l.nodeAfter.attrs.colspan - 1 == c.width - 1)
          return;
      }
      bw(n, s);
    }
  }
}
function iO(n) {
  if (!n.editable) return;
  const e = Dt.getState(n.state);
  e && e.activeHandle > -1 && !e.dragging && bw(n, -1);
}
function oO(n, e, t, r) {
  var i;
  if (!n.editable) return !1;
  const o = (i = n.dom.ownerDocument.defaultView) != null ? i : window, s = Dt.getState(n.state);
  if (!s || s.activeHandle == -1 || s.dragging)
    return !1;
  const l = n.state.doc.nodeAt(s.activeHandle), a = sO(n, s.activeHandle, l.attrs);
  n.dispatch(
    n.state.tr.setMeta(Dt, {
      setDragging: { startX: e.clientX, startWidth: a }
    })
  );
  function c(u) {
    o.removeEventListener("mouseup", c), o.removeEventListener("mousemove", d);
    const h = Dt.getState(n.state);
    h != null && h.dragging && (aO(
      n,
      h.activeHandle,
      Jg(h.dragging, u, t)
    ), n.dispatch(
      n.state.tr.setMeta(Dt, { setDragging: null })
    ));
  }
  function d(u) {
    if (!u.which) return c(u);
    const h = Dt.getState(n.state);
    if (h && h.dragging) {
      const f = Jg(h.dragging, u, t);
      Yg(
        n,
        h.activeHandle,
        f,
        r
      );
    }
  }
  return Yg(
    n,
    s.activeHandle,
    a,
    r
  ), o.addEventListener("mouseup", c), o.addEventListener("mousemove", d), e.preventDefault(), !0;
}
function sO(n, e, { colspan: t, colwidth: r }) {
  const i = r && r[r.length - 1];
  if (i) return i;
  const o = n.domAtPos(e);
  let l = o.node.childNodes[o.offset].offsetWidth, a = t;
  if (r)
    for (let c = 0; c < t; c++)
      r[c] && (l -= r[c], a--);
  return l / a;
}
function lO(n) {
  for (; n && n.nodeName != "TD" && n.nodeName != "TH"; )
    n = n.classList && n.classList.contains("ProseMirror") ? null : n.parentNode;
  return n;
}
function Kg(n, e, t, r) {
  const i = t == "right" ? -r : r, o = n.posAtCoords({
    left: e.clientX + i,
    top: e.clientY
  });
  if (!o) return -1;
  const { pos: s } = o, l = bo(n.state.doc.resolve(s));
  if (!l) return -1;
  if (t == "right") return l.pos;
  const a = we.get(l.node(-1)), c = l.start(-1), d = a.map.indexOf(l.pos - c);
  return d % a.width == 0 ? -1 : c + a.map[d - 1];
}
function Jg(n, e, t) {
  const r = e.clientX - n.startX;
  return Math.max(t, n.startWidth + r);
}
function bw(n, e) {
  n.dispatch(
    n.state.tr.setMeta(Dt, { setHandle: e })
  );
}
function aO(n, e, t) {
  const r = n.state.doc.resolve(e), i = r.node(-1), o = we.get(i), s = r.start(-1), l = o.colCount(r.pos - s) + r.nodeAfter.attrs.colspan - 1, a = n.state.tr;
  for (let c = 0; c < o.height; c++) {
    const d = c * o.width + l;
    if (c && o.map[d] == o.map[d - o.width]) continue;
    const u = o.map[d], h = i.nodeAt(u).attrs, f = h.colspan == 1 ? 0 : l - o.colCount(u);
    if (h.colwidth && h.colwidth[f] == t) continue;
    const p = h.colwidth ? h.colwidth.slice() : cO(h.colspan);
    p[f] = t, a.setNodeMarkup(s + u, null, { ...h, colwidth: p });
  }
  a.docChanged && n.dispatch(a);
}
function Yg(n, e, t, r) {
  const i = n.state.doc.resolve(e), o = i.node(-1), s = i.start(-1), l = we.get(o).colCount(i.pos - s) + i.nodeAfter.attrs.colspan - 1;
  let a = n.domAtPos(i.start(-1)).node;
  for (; a && a.nodeName != "TABLE"; )
    a = a.parentNode;
  a && Pu(
    o,
    a.firstChild,
    a,
    r,
    l,
    t
  );
}
function cO(n) {
  return Array(n).fill(0);
}
function dO(n, e) {
  var t;
  const r = [], i = n.doc.resolve(e), o = i.node(-1);
  if (!o)
    return Q.empty;
  const s = we.get(o), l = i.start(-1), a = s.colCount(i.pos - l) + i.nodeAfter.attrs.colspan - 1;
  for (let c = 0; c < s.height; c++) {
    const d = a + c * s.width;
    if ((a == s.width - 1 || s.map[d] != s.map[d + 1]) && (c == 0 || s.map[d] != s.map[d - s.width])) {
      const u = s.map[d], h = l + u + o.nodeAt(u).nodeSize - 1, f = document.createElement("div");
      f.className = "column-resize-handle", (t = Dt.getState(n)) != null && t.dragging && r.push(
        se.node(
          l + u,
          l + u + o.nodeAt(u).nodeSize,
          {
            class: "column-resize-dragging"
          }
        )
      ), r.push(se.widget(h, f));
    }
  }
  return Q.create(n.doc, r);
}
function uO({
  allowTableNodeSelection: n = !1
} = {}) {
  return new G({
    key: wr,
    // This piece of state is used to remember when a mouse-drag
    // cell-selection is happening, so that it can continue even as
    // transactions (which might move its anchor cell) come in.
    state: {
      init() {
        return null;
      },
      apply(e, t) {
        const r = e.getMeta(wr);
        if (r != null) return r == -1 ? null : r;
        if (t == null || !e.docChanged) return t;
        const { deleted: i, pos: o } = e.mapping.mapResult(t);
        return i ? null : o;
      }
    },
    props: {
      decorations: E2,
      handleDOMEvents: {
        mousedown: eO
      },
      createSelectionBetween(e) {
        return wr.getState(e.state) != null ? e.state.selection : null;
      },
      handleTripleClick: Z2,
      handleKeyDown: X2,
      handlePaste: Q2
    },
    appendTransaction(e, t, r) {
      return A2(
        r,
        M2(r, t),
        n
      );
    }
  });
}
class xe extends V {
  /**
  Create a gap cursor.
  */
  constructor(e) {
    super(e, e);
  }
  map(e, t) {
    let r = e.resolve(t.map(this.head));
    return xe.valid(r) ? new xe(r) : V.near(r);
  }
  content() {
    return O.empty;
  }
  eq(e) {
    return e instanceof xe && e.head == this.head;
  }
  toJSON() {
    return { type: "gapcursor", pos: this.head };
  }
  /**
  @internal
  */
  static fromJSON(e, t) {
    if (typeof t.pos != "number")
      throw new RangeError("Invalid input for GapCursor.fromJSON");
    return new xe(e.resolve(t.pos));
  }
  /**
  @internal
  */
  getBookmark() {
    return new of(this.anchor);
  }
  /**
  @internal
  */
  static valid(e) {
    let t = e.parent;
    if (t.isTextblock || !hO(e) || !fO(e))
      return !1;
    let r = t.type.spec.allowGapCursor;
    if (r != null)
      return r;
    let i = t.contentMatchAt(e.index()).defaultType;
    return i && i.isTextblock;
  }
  /**
  @internal
  */
  static findGapCursorFrom(e, t, r = !1) {
    e: for (; ; ) {
      if (!r && xe.valid(e))
        return e;
      let i = e.pos, o = null;
      for (let s = e.depth; ; s--) {
        let l = e.node(s);
        if (t > 0 ? e.indexAfter(s) < l.childCount : e.index(s) > 0) {
          o = l.child(t > 0 ? e.indexAfter(s) : e.index(s) - 1);
          break;
        } else if (s == 0)
          return null;
        i += t;
        let a = e.doc.resolve(i);
        if (xe.valid(a))
          return a;
      }
      for (; ; ) {
        let s = t > 0 ? o.firstChild : o.lastChild;
        if (!s) {
          if (o.isAtom && !o.isText && !P.isSelectable(o)) {
            e = e.doc.resolve(i + o.nodeSize * t), r = !1;
            continue e;
          }
          break;
        }
        o = s, i += t;
        let l = e.doc.resolve(i);
        if (xe.valid(l))
          return l;
      }
      return null;
    }
  }
}
xe.prototype.visible = !1;
xe.findFrom = xe.findGapCursorFrom;
V.jsonID("gapcursor", xe);
class of {
  constructor(e) {
    this.pos = e;
  }
  map(e) {
    return new of(e.map(this.pos));
  }
  resolve(e) {
    let t = e.resolve(this.pos);
    return xe.valid(t) ? new xe(t) : V.near(t);
  }
}
function hO(n) {
  for (let e = n.depth; e >= 0; e--) {
    let t = n.index(e), r = n.node(e);
    if (t == 0) {
      if (r.type.spec.isolating)
        return !0;
      continue;
    }
    for (let i = r.child(t - 1); ; i = i.lastChild) {
      if (i.childCount == 0 && !i.inlineContent || i.isAtom || i.type.spec.isolating)
        return !0;
      if (i.inlineContent)
        return !1;
    }
  }
  return !0;
}
function fO(n) {
  for (let e = n.depth; e >= 0; e--) {
    let t = n.indexAfter(e), r = n.node(e);
    if (t == r.childCount) {
      if (r.type.spec.isolating)
        return !0;
      continue;
    }
    for (let i = r.child(t); ; i = i.firstChild) {
      if (i.childCount == 0 && !i.inlineContent || i.isAtom || i.type.spec.isolating)
        return !0;
      if (i.inlineContent)
        return !1;
    }
  }
  return !0;
}
function pO() {
  return new G({
    props: {
      decorations: yO,
      createSelectionBetween(n, e, t) {
        return e.pos == t.pos && xe.valid(t) ? new xe(t) : null;
      },
      handleClick: gO,
      handleKeyDown: mO,
      handleDOMEvents: { beforeinput: bO }
    }
  });
}
const mO = Uh({
  ArrowLeft: Tl("horiz", -1),
  ArrowRight: Tl("horiz", 1),
  ArrowUp: Tl("vert", -1),
  ArrowDown: Tl("vert", 1)
});
function Tl(n, e) {
  const t = n == "vert" ? e > 0 ? "down" : "up" : e > 0 ? "right" : "left";
  return function(r, i, o) {
    let s = r.selection, l = e > 0 ? s.$to : s.$from, a = s.empty;
    if (s instanceof L) {
      if (!o.endOfTextblock(t) || l.depth == 0)
        return !1;
      a = !1, l = r.doc.resolve(e > 0 ? l.after() : l.before());
    }
    let c = xe.findGapCursorFrom(l, e, a);
    return c ? (i && i(r.tr.setSelection(new xe(c))), !0) : !1;
  };
}
function gO(n, e, t) {
  if (!n || !n.editable)
    return !1;
  let r = n.state.doc.resolve(e);
  if (!xe.valid(r))
    return !1;
  let i = n.posAtCoords({ left: t.clientX, top: t.clientY });
  return i && i.inside > -1 && P.isSelectable(n.state.doc.nodeAt(i.inside)) ? !1 : (n.dispatch(n.state.tr.setSelection(new xe(r))), !0);
}
function bO(n, e) {
  if (e.inputType != "insertCompositionText" || !(n.state.selection instanceof xe))
    return !1;
  let { $from: t } = n.state.selection, r = t.parent.contentMatchAt(t.index()).findWrapping(n.state.schema.nodes.text);
  if (!r)
    return !1;
  let i = A.empty;
  for (let s = r.length - 1; s >= 0; s--)
    i = A.from(r[s].createAndFill(null, i));
  let o = n.state.tr.replace(t.pos, t.pos, new O(i, 0, 0));
  return o.setSelection(L.near(o.doc.resolve(t.pos + 1))), n.dispatch(o), !1;
}
function yO(n) {
  if (!(n.selection instanceof xe))
    return null;
  let e = document.createElement("div");
  return e.className = "ProseMirror-gapcursor", Q.create(n.doc, [se.widget(n.selection.head, e, { key: "gapcursor" })]);
}
const _O = he.create({
  name: "gapCursor",
  addProseMirrorPlugins() {
    return [
      pO()
    ];
  },
  extendNodeSchema(n) {
    var e;
    const t = {
      name: n.name,
      options: n.options,
      storage: n.storage
    };
    return {
      allowGapCursor: (e = X(R(n, "allowGapCursor", t))) !== null && e !== void 0 ? e : null
    };
  }
});
var Ea = 200, Pe = function() {
};
Pe.prototype.append = function(e) {
  return e.length ? (e = Pe.from(e), !this.length && e || e.length < Ea && this.leafAppend(e) || this.length < Ea && e.leafPrepend(this) || this.appendInner(e)) : this;
};
Pe.prototype.prepend = function(e) {
  return e.length ? Pe.from(e).append(this) : this;
};
Pe.prototype.appendInner = function(e) {
  return new wO(this, e);
};
Pe.prototype.slice = function(e, t) {
  return e === void 0 && (e = 0), t === void 0 && (t = this.length), e >= t ? Pe.empty : this.sliceInner(Math.max(0, e), Math.min(this.length, t));
};
Pe.prototype.get = function(e) {
  if (!(e < 0 || e >= this.length))
    return this.getInner(e);
};
Pe.prototype.forEach = function(e, t, r) {
  t === void 0 && (t = 0), r === void 0 && (r = this.length), t <= r ? this.forEachInner(e, t, r, 0) : this.forEachInvertedInner(e, t, r, 0);
};
Pe.prototype.map = function(e, t, r) {
  t === void 0 && (t = 0), r === void 0 && (r = this.length);
  var i = [];
  return this.forEach(function(o, s) {
    return i.push(e(o, s));
  }, t, r), i;
};
Pe.from = function(e) {
  return e instanceof Pe ? e : e && e.length ? new yw(e) : Pe.empty;
};
var yw = /* @__PURE__ */ function(n) {
  function e(r) {
    n.call(this), this.values = r;
  }
  n && (e.__proto__ = n), e.prototype = Object.create(n && n.prototype), e.prototype.constructor = e;
  var t = { length: { configurable: !0 }, depth: { configurable: !0 } };
  return e.prototype.flatten = function() {
    return this.values;
  }, e.prototype.sliceInner = function(i, o) {
    return i == 0 && o == this.length ? this : new e(this.values.slice(i, o));
  }, e.prototype.getInner = function(i) {
    return this.values[i];
  }, e.prototype.forEachInner = function(i, o, s, l) {
    for (var a = o; a < s; a++)
      if (i(this.values[a], l + a) === !1)
        return !1;
  }, e.prototype.forEachInvertedInner = function(i, o, s, l) {
    for (var a = o - 1; a >= s; a--)
      if (i(this.values[a], l + a) === !1)
        return !1;
  }, e.prototype.leafAppend = function(i) {
    if (this.length + i.length <= Ea)
      return new e(this.values.concat(i.flatten()));
  }, e.prototype.leafPrepend = function(i) {
    if (this.length + i.length <= Ea)
      return new e(i.flatten().concat(this.values));
  }, t.length.get = function() {
    return this.values.length;
  }, t.depth.get = function() {
    return 0;
  }, Object.defineProperties(e.prototype, t), e;
}(Pe);
Pe.empty = new yw([]);
var wO = /* @__PURE__ */ function(n) {
  function e(t, r) {
    n.call(this), this.left = t, this.right = r, this.length = t.length + r.length, this.depth = Math.max(t.depth, r.depth) + 1;
  }
  return n && (e.__proto__ = n), e.prototype = Object.create(n && n.prototype), e.prototype.constructor = e, e.prototype.flatten = function() {
    return this.left.flatten().concat(this.right.flatten());
  }, e.prototype.getInner = function(r) {
    return r < this.left.length ? this.left.get(r) : this.right.get(r - this.left.length);
  }, e.prototype.forEachInner = function(r, i, o, s) {
    var l = this.left.length;
    if (i < l && this.left.forEachInner(r, i, Math.min(o, l), s) === !1 || o > l && this.right.forEachInner(r, Math.max(i - l, 0), Math.min(this.length, o) - l, s + l) === !1)
      return !1;
  }, e.prototype.forEachInvertedInner = function(r, i, o, s) {
    var l = this.left.length;
    if (i > l && this.right.forEachInvertedInner(r, i - l, Math.max(o, l) - l, s + l) === !1 || o < l && this.left.forEachInvertedInner(r, Math.min(i, l), o, s) === !1)
      return !1;
  }, e.prototype.sliceInner = function(r, i) {
    if (r == 0 && i == this.length)
      return this;
    var o = this.left.length;
    return i <= o ? this.left.slice(r, i) : r >= o ? this.right.slice(r - o, i - o) : this.left.slice(r, o).append(this.right.slice(0, i - o));
  }, e.prototype.leafAppend = function(r) {
    var i = this.right.leafAppend(r);
    if (i)
      return new e(this.left, i);
  }, e.prototype.leafPrepend = function(r) {
    var i = this.left.leafPrepend(r);
    if (i)
      return new e(i, this.right);
  }, e.prototype.appendInner = function(r) {
    return this.left.depth >= Math.max(this.right.depth, r.depth) + 1 ? new e(this.left, new e(this.right, r)) : new e(this, r);
  }, e;
}(Pe);
const kO = 500;
class ln {
  constructor(e, t) {
    this.items = e, this.eventCount = t;
  }
  // Pop the latest event off the branch's history and apply it
  // to a document transform.
  popEvent(e, t) {
    if (this.eventCount == 0)
      return null;
    let r = this.items.length;
    for (; ; r--)
      if (this.items.get(r - 1).selection) {
        --r;
        break;
      }
    let i, o;
    t && (i = this.remapping(r, this.items.length), o = i.maps.length);
    let s = e.tr, l, a, c = [], d = [];
    return this.items.forEach((u, h) => {
      if (!u.step) {
        i || (i = this.remapping(r, h + 1), o = i.maps.length), o--, d.push(u);
        return;
      }
      if (i) {
        d.push(new hr(u.map));
        let f = u.step.map(i.slice(o)), p;
        f && s.maybeStep(f).doc && (p = s.mapping.maps[s.mapping.maps.length - 1], c.push(new hr(p, void 0, void 0, c.length + d.length))), o--, p && i.appendMap(p, o);
      } else
        s.maybeStep(u.step);
      if (u.selection)
        return l = i ? u.selection.map(i.slice(o)) : u.selection, a = new ln(this.items.slice(0, r).append(d.reverse().concat(c)), this.eventCount - 1), !1;
    }, this.items.length, 0), { remaining: a, transform: s, selection: l };
  }
  // Create a new branch with the given transform added.
  addTransform(e, t, r, i) {
    let o = [], s = this.eventCount, l = this.items, a = !i && l.length ? l.get(l.length - 1) : null;
    for (let d = 0; d < e.steps.length; d++) {
      let u = e.steps[d].invert(e.docs[d]), h = new hr(e.mapping.maps[d], u, t), f;
      (f = a && a.merge(h)) && (h = f, d ? o.pop() : l = l.slice(0, l.length - 1)), o.push(h), t && (s++, t = void 0), i || (a = h);
    }
    let c = s - r.depth;
    return c > CO && (l = vO(l, c), s -= c), new ln(l.append(o), s);
  }
  remapping(e, t) {
    let r = new ro();
    return this.items.forEach((i, o) => {
      let s = i.mirrorOffset != null && o - i.mirrorOffset >= e ? r.maps.length - i.mirrorOffset : void 0;
      r.appendMap(i.map, s);
    }, e, t), r;
  }
  addMaps(e) {
    return this.eventCount == 0 ? this : new ln(this.items.append(e.map((t) => new hr(t))), 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(e, t) {
    if (!this.eventCount)
      return this;
    let r = [], i = Math.max(0, this.items.length - t), o = e.mapping, s = e.steps.length, l = this.eventCount;
    this.items.forEach((h) => {
      h.selection && l--;
    }, i);
    let a = t;
    this.items.forEach((h) => {
      let f = o.getMirror(--a);
      if (f == null)
        return;
      s = Math.min(s, f);
      let p = o.maps[f];
      if (h.step) {
        let m = e.steps[f].invert(e.docs[f]), g = h.selection && h.selection.map(o.slice(a + 1, f));
        g && l++, r.push(new hr(p, m, g));
      } else
        r.push(new hr(p));
    }, i);
    let c = [];
    for (let h = t; h < s; h++)
      c.push(new hr(o.maps[h]));
    let d = this.items.slice(0, i).append(c).append(r), u = new ln(d, l);
    return u.emptyItemCount() > kO && (u = u.compress(this.items.length - r.length)), u;
  }
  emptyItemCount() {
    let e = 0;
    return this.items.forEach((t) => {
      t.step || e++;
    }), e;
  }
  // 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(e = this.items.length) {
    let t = this.remapping(0, e), r = t.maps.length, i = [], o = 0;
    return this.items.forEach((s, l) => {
      if (l >= e)
        i.push(s), s.selection && o++;
      else if (s.step) {
        let a = s.step.map(t.slice(r)), c = a && a.getMap();
        if (r--, c && t.appendMap(c, r), a) {
          let d = s.selection && s.selection.map(t.slice(r));
          d && o++;
          let u = new hr(c.invert(), a, d), h, f = i.length - 1;
          (h = i.length && i[f].merge(u)) ? i[f] = h : i.push(u);
        }
      } else s.map && r--;
    }, this.items.length, 0), new ln(Pe.from(i.reverse()), o);
  }
}
ln.empty = new ln(Pe.empty, 0);
function vO(n, e) {
  let t;
  return n.forEach((r, i) => {
    if (r.selection && e-- == 0)
      return t = i, !1;
  }), n.slice(t);
}
let hr = class _w {
  constructor(e, t, r, i) {
    this.map = e, this.step = t, this.selection = r, this.mirrorOffset = i;
  }
  merge(e) {
    if (this.step && e.step && !e.selection) {
      let t = e.step.merge(this.step);
      if (t)
        return new _w(t.getMap().invert(), t, this.selection);
    }
  }
};
class br {
  constructor(e, t, r, i, o) {
    this.done = e, this.undone = t, this.prevRanges = r, this.prevTime = i, this.prevComposition = o;
  }
}
const CO = 20;
function SO(n, e, t, r) {
  let i = t.getMeta(li), o;
  if (i)
    return i.historyState;
  t.getMeta(DO) && (n = new br(n.done, n.undone, null, 0, -1));
  let s = t.getMeta("appendedTransaction");
  if (t.steps.length == 0)
    return n;
  if (s && s.getMeta(li))
    return s.getMeta(li).redo ? new br(n.done.addTransform(t, void 0, r, Zl(e)), n.undone, Xg(t.mapping.maps), n.prevTime, n.prevComposition) : new br(n.done, n.undone.addTransform(t, void 0, r, Zl(e)), null, n.prevTime, n.prevComposition);
  if (t.getMeta("addToHistory") !== !1 && !(s && s.getMeta("addToHistory") === !1)) {
    let l = t.getMeta("composition"), a = n.prevTime == 0 || !s && n.prevComposition != l && (n.prevTime < (t.time || 0) - r.newGroupDelay || !EO(t, n.prevRanges)), c = s ? $d(n.prevRanges, t.mapping) : Xg(t.mapping.maps);
    return new br(n.done.addTransform(t, a ? e.selection.getBookmark() : void 0, r, Zl(e)), ln.empty, c, t.time, l ?? n.prevComposition);
  } else return (o = t.getMeta("rebased")) ? new br(n.done.rebased(t, o), n.undone.rebased(t, o), $d(n.prevRanges, t.mapping), n.prevTime, n.prevComposition) : new br(n.done.addMaps(t.mapping.maps), n.undone.addMaps(t.mapping.maps), $d(n.prevRanges, t.mapping), n.prevTime, n.prevComposition);
}
function EO(n, e) {
  if (!e)
    return !1;
  if (!n.docChanged)
    return !0;
  let t = !1;
  return n.mapping.maps[0].forEach((r, i) => {
    for (let o = 0; o < e.length; o += 2)
      r <= e[o + 1] && i >= e[o] && (t = !0);
  }), t;
}
function Xg(n) {
  let e = [];
  for (let t = n.length - 1; t >= 0 && e.length == 0; t--)
    n[t].forEach((r, i, o, s) => e.push(o, s));
  return e;
}
function $d(n, e) {
  if (!n)
    return null;
  let t = [];
  for (let r = 0; r < n.length; r += 2) {
    let i = e.map(n[r], 1), o = e.map(n[r + 1], -1);
    i <= o && t.push(i, o);
  }
  return t;
}
function xO(n, e, t) {
  let r = Zl(e), i = li.get(e).spec.config, o = (t ? n.undone : n.done).popEvent(e, r);
  if (!o)
    return null;
  let s = o.selection.resolve(o.transform.doc), l = (t ? n.done : n.undone).addTransform(o.transform, e.selection.getBookmark(), i, r), a = new br(t ? l : o.remaining, t ? o.remaining : l, null, 0, -1);
  return o.transform.setSelection(s).setMeta(li, { redo: t, historyState: a });
}
let Id = !1, Zg = null;
function Zl(n) {
  let e = n.plugins;
  if (Zg != e) {
    Id = !1, Zg = e;
    for (let t = 0; t < e.length; t++)
      if (e[t].spec.historyPreserveItems) {
        Id = !0;
        break;
      }
  }
  return Id;
}
const li = new te("history"), DO = new te("closeHistory");
function AO(n = {}) {
  return n = {
    depth: n.depth || 100,
    newGroupDelay: n.newGroupDelay || 500
  }, new G({
    key: li,
    state: {
      init() {
        return new br(ln.empty, ln.empty, null, 0, -1);
      },
      apply(e, t, r) {
        return SO(t, r, e, n);
      }
    },
    config: n,
    props: {
      handleDOMEvents: {
        beforeinput(e, t) {
          let r = t.inputType, i = r == "historyUndo" ? sf : r == "historyRedo" ? lf : null;
          return i ? (t.preventDefault(), i(e.state, e.dispatch)) : !1;
        }
      }
    }
  });
}
function ww(n, e) {
  return (t, r) => {
    let i = li.getState(t);
    if (!i || (n ? i.undone : i.done).eventCount == 0)
      return !1;
    if (r) {
      let o = xO(i, t, n);
      o && r(e ? o.scrollIntoView() : o);
    }
    return !0;
  };
}
const sf = ww(!1, !0), lf = ww(!0, !0), TO = he.create({
  name: "history",
  addOptions() {
    return {
      depth: 100,
      newGroupDelay: 500
    };
  },
  addCommands() {
    return {
      undo: () => ({ state: n, dispatch: e }) => sf(n, e),
      redo: () => ({ state: n, dispatch: e }) => lf(n, e)
    };
  },
  addProseMirrorPlugins() {
    return [
      AO(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()
    };
  }
}), MO = " ögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2", OO = "ελ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", zu = "numeric", Hu = "ascii", Vu = "alpha", Qo = "asciinumeric", Ho = "alphanumeric", Uu = "domain", kw = "emoji", FO = "scheme", NO = "slashscheme", Ld = "whitespace";
function $O(n, e) {
  return n in e || (e[n] = []), e[n];
}
function ni(n, e, t) {
  e[zu] && (e[Qo] = !0, e[Ho] = !0), e[Hu] && (e[Qo] = !0, e[Vu] = !0), e[Qo] && (e[Ho] = !0), e[Vu] && (e[Ho] = !0), e[Ho] && (e[Uu] = !0), e[kw] && (e[Uu] = !0);
  for (const r in e) {
    const i = $O(r, t);
    i.indexOf(n) < 0 && i.push(n);
  }
}
function IO(n, e) {
  const t = {};
  for (const r in e)
    e[r].indexOf(n) >= 0 && (t[r] = !0);
  return t;
}
function yt(n = null) {
  this.j = {}, this.jr = [], this.jd = null, this.t = n;
}
yt.groups = {};
yt.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(n) {
    const e = this, t = e.j[n];
    if (t)
      return t;
    for (let r = 0; r < e.jr.length; r++) {
      const i = e.jr[r][0], o = e.jr[r][1];
      if (o && i.test(n))
        return o;
    }
    return e.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(n, e = !1) {
    return e ? n in this.j : !!this.go(n);
  },
  /**
   * 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(n, e, t, r) {
    for (let i = 0; i < n.length; i++)
      this.tt(n[i], e, t, r);
  },
  /**
   * 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(n, e, t, r) {
    r = r || yt.groups;
    let i;
    return e && e.j ? i = e : (i = new yt(e), t && r && ni(e, t, r)), this.jr.push([n, i]), i;
  },
  /**
   * 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(n, e, t, r) {
    let i = this;
    const o = n.length;
    if (!o)
      return i;
    for (let s = 0; s < o - 1; s++)
      i = i.tt(n[s]);
    return i.tt(n[o - 1], e, t, r);
  },
  /**
   * 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(n, e, t, r) {
    r = r || yt.groups;
    const i = this;
    if (e && e.j)
      return i.j[n] = e, e;
    const o = e;
    let s, l = i.go(n);
    if (l ? (s = new yt(), Object.assign(s.j, l.j), s.jr.push.apply(s.jr, l.jr), s.jd = l.jd, s.t = l.t) : s = new yt(), o) {
      if (r)
        if (s.t && typeof s.t == "string") {
          const a = Object.assign(IO(s.t, r), t);
          ni(o, a, r);
        } else t && ni(o, t, r);
      s.t = o;
    }
    return i.j[n] = s, s;
  }
};
const W = (n, e, t, r, i) => n.ta(e, t, r, i), Ee = (n, e, t, r, i) => n.tr(e, t, r, i), Qg = (n, e, t, r, i) => n.ts(e, t, r, i), M = (n, e, t, r, i) => n.tt(e, t, r, i), Jn = "WORD", qu = "UWORD", vw = "ASCIINUMERICAL", Cw = "ALPHANUMERICAL", ws = "LOCALHOST", ju = "TLD", Wu = "UTLD", Ql = "SCHEME", Ui = "SLASH_SCHEME", af = "NUM", Gu = "WS", cf = "NL", es = "OPENBRACE", ts = "CLOSEBRACE", xa = "OPENBRACKET", Da = "CLOSEBRACKET", Aa = "OPENPAREN", Ta = "CLOSEPAREN", Ma = "OPENANGLEBRACKET", Oa = "CLOSEANGLEBRACKET", Fa = "FULLWIDTHLEFTPAREN", Na = "FULLWIDTHRIGHTPAREN", $a = "LEFTCORNERBRACKET", Ia = "RIGHTCORNERBRACKET", La = "LEFTWHITECORNERBRACKET", Ra = "RIGHTWHITECORNERBRACKET", Ba = "FULLWIDTHLESSTHAN", Pa = "FULLWIDTHGREATERTHAN", za = "AMPERSAND", Ha = "APOSTROPHE", Va = "ASTERISK", yr = "AT", Ua = "BACKSLASH", qa = "BACKTICK", ja = "CARET", kr = "COLON", df = "COMMA", Wa = "DOLLAR", kn = "DOT", Ga = "EQUALS", uf = "EXCLAMATION", Bt = "HYPHEN", ns = "PERCENT", Ka = "PIPE", Ja = "PLUS", Ya = "POUND", rs = "QUERY", hf = "QUOTE", Sw = "FULLWIDTHMIDDLEDOT", ff = "SEMI", vn = "SLASH", is = "TILDE", Xa = "UNDERSCORE", Ew = "EMOJI", Za = "SYM";
var xw = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ALPHANUMERICAL: Cw,
  AMPERSAND: za,
  APOSTROPHE: Ha,
  ASCIINUMERICAL: vw,
  ASTERISK: Va,
  AT: yr,
  BACKSLASH: Ua,
  BACKTICK: qa,
  CARET: ja,
  CLOSEANGLEBRACKET: Oa,
  CLOSEBRACE: ts,
  CLOSEBRACKET: Da,
  CLOSEPAREN: Ta,
  COLON: kr,
  COMMA: df,
  DOLLAR: Wa,
  DOT: kn,
  EMOJI: Ew,
  EQUALS: Ga,
  EXCLAMATION: uf,
  FULLWIDTHGREATERTHAN: Pa,
  FULLWIDTHLEFTPAREN: Fa,
  FULLWIDTHLESSTHAN: Ba,
  FULLWIDTHMIDDLEDOT: Sw,
  FULLWIDTHRIGHTPAREN: Na,
  HYPHEN: Bt,
  LEFTCORNERBRACKET: $a,
  LEFTWHITECORNERBRACKET: La,
  LOCALHOST: ws,
  NL: cf,
  NUM: af,
  OPENANGLEBRACKET: Ma,
  OPENBRACE: es,
  OPENBRACKET: xa,
  OPENPAREN: Aa,
  PERCENT: ns,
  PIPE: Ka,
  PLUS: Ja,
  POUND: Ya,
  QUERY: rs,
  QUOTE: hf,
  RIGHTCORNERBRACKET: Ia,
  RIGHTWHITECORNERBRACKET: Ra,
  SCHEME: Ql,
  SEMI: ff,
  SLASH: vn,
  SLASH_SCHEME: Ui,
  SYM: Za,
  TILDE: is,
  TLD: ju,
  UNDERSCORE: Xa,
  UTLD: Wu,
  UWORD: qu,
  WORD: Jn,
  WS: Gu
});
const Un = /[a-z]/, Lo = new RegExp("\\p{L}", "u"), Rd = new RegExp("\\p{Emoji}", "u"), qn = /\d/, Bd = /\s/, e0 = "\r", Pd = `
`, LO = "️", RO = "‍", zd = "￼";
let Ml = null, Ol = null;
function BO(n = []) {
  const e = {};
  yt.groups = e;
  const t = new yt();
  Ml == null && (Ml = t0(MO)), Ol == null && (Ol = t0(OO)), M(t, "'", Ha), M(t, "{", es), M(t, "}", ts), M(t, "[", xa), M(t, "]", Da), M(t, "(", Aa), M(t, ")", Ta), M(t, "<", Ma), M(t, ">", Oa), M(t, "（", Fa), M(t, "）", Na), M(t, "「", $a), M(t, "」", Ia), M(t, "『", La), M(t, "』", Ra), M(t, "＜", Ba), M(t, "＞", Pa), M(t, "&", za), M(t, "*", Va), M(t, "@", yr), M(t, "`", qa), M(t, "^", ja), M(t, ":", kr), M(t, ",", df), M(t, "$", Wa), M(t, ".", kn), M(t, "=", Ga), M(t, "!", uf), M(t, "-", Bt), M(t, "%", ns), M(t, "|", Ka), M(t, "+", Ja), M(t, "#", Ya), M(t, "?", rs), M(t, '"', hf), M(t, "/", vn), M(t, ";", ff), M(t, "~", is), M(t, "_", Xa), M(t, "\\", Ua), M(t, "・", Sw);
  const r = Ee(t, qn, af, {
    [zu]: !0
  });
  Ee(r, qn, r);
  const i = Ee(r, Un, vw, {
    [Qo]: !0
  }), o = Ee(r, Lo, Cw, {
    [Ho]: !0
  }), s = Ee(t, Un, Jn, {
    [Hu]: !0
  });
  Ee(s, qn, i), Ee(s, Un, s), Ee(i, qn, i), Ee(i, Un, i);
  const l = Ee(t, Lo, qu, {
    [Vu]: !0
  });
  Ee(l, Un), Ee(l, qn, o), Ee(l, Lo, l), Ee(o, qn, o), Ee(o, Un), Ee(o, Lo, o);
  const a = M(t, Pd, cf, {
    [Ld]: !0
  }), c = M(t, e0, Gu, {
    [Ld]: !0
  }), d = Ee(t, Bd, Gu, {
    [Ld]: !0
  });
  M(t, zd, d), M(c, Pd, a), M(c, zd, d), Ee(c, Bd, d), M(d, e0), M(d, Pd), Ee(d, Bd, d), M(d, zd, d);
  const u = Ee(t, Rd, Ew, {
    [kw]: !0
  });
  M(u, "#"), Ee(u, Rd, u), M(u, LO, u);
  const h = M(u, RO);
  M(h, "#"), Ee(h, Rd, u);
  const f = [[Un, s], [qn, i]], p = [[Un, null], [Lo, l], [qn, o]];
  for (let m = 0; m < Ml.length; m++)
    fr(t, Ml[m], ju, Jn, f);
  for (let m = 0; m < Ol.length; m++)
    fr(t, Ol[m], Wu, qu, p);
  ni(ju, {
    tld: !0,
    ascii: !0
  }, e), ni(Wu, {
    utld: !0,
    alpha: !0
  }, e), fr(t, "file", Ql, Jn, f), fr(t, "mailto", Ql, Jn, f), fr(t, "http", Ui, Jn, f), fr(t, "https", Ui, Jn, f), fr(t, "ftp", Ui, Jn, f), fr(t, "ftps", Ui, Jn, f), ni(Ql, {
    scheme: !0,
    ascii: !0
  }, e), ni(Ui, {
    slashscheme: !0,
    ascii: !0
  }, e), n = n.sort((m, g) => m[0] > g[0] ? 1 : -1);
  for (let m = 0; m < n.length; m++) {
    const g = n[m][0], _ = n[m][1] ? {
      [FO]: !0
    } : {
      [NO]: !0
    };
    g.indexOf("-") >= 0 ? _[Uu] = !0 : Un.test(g) ? qn.test(g) ? _[Qo] = !0 : _[Hu] = !0 : _[zu] = !0, Qg(t, g, g, _);
  }
  return Qg(t, "localhost", ws, {
    ascii: !0
  }), t.jd = new yt(Za), {
    start: t,
    tokens: Object.assign({
      groups: e
    }, xw)
  };
}
function Dw(n, e) {
  const t = PO(e.replace(/[A-Z]/g, (l) => l.toLowerCase())), r = t.length, i = [];
  let o = 0, s = 0;
  for (; s < r; ) {
    let l = n, a = null, c = 0, d = null, u = -1, h = -1;
    for (; s < r && (a = l.go(t[s])); )
      l = a, l.accepts() ? (u = 0, h = 0, d = l) : u >= 0 && (u += t[s].length, h++), c += t[s].length, o += t[s].length, s++;
    o -= u, s -= h, c -= u, i.push({
      t: d.t,
      // token type/name
      v: e.slice(o - c, o),
      // string value
      s: o - c,
      // start index
      e: o
      // end index (excluding)
    });
  }
  return i;
}
function PO(n) {
  const e = [], t = n.length;
  let r = 0;
  for (; r < t; ) {
    let i = n.charCodeAt(r), o, s = i < 55296 || i > 56319 || r + 1 === t || (o = n.charCodeAt(r + 1)) < 56320 || o > 57343 ? n[r] : n.slice(r, r + 2);
    e.push(s), r += s.length;
  }
  return e;
}
function fr(n, e, t, r, i) {
  let o;
  const s = e.length;
  for (let l = 0; l < s - 1; l++) {
    const a = e[l];
    n.j[a] ? o = n.j[a] : (o = new yt(r), o.jr = i.slice(), n.j[a] = o), n = o;
  }
  return o = new yt(t), o.jr = i.slice(), n.j[e[s - 1]] = o, o;
}
function t0(n) {
  const e = [], t = [];
  let r = 0, i = "0123456789";
  for (; r < n.length; ) {
    let o = 0;
    for (; i.indexOf(n[r + o]) >= 0; )
      o++;
    if (o > 0) {
      e.push(t.join(""));
      for (let s = parseInt(n.substring(r, r + o), 10); s > 0; s--)
        t.pop();
      r += o;
    } else
      t.push(n[r]), r++;
  }
  return e;
}
const ks = {
  defaultProtocol: "http",
  events: null,
  format: n0,
  formatHref: n0,
  nl2br: !1,
  tagName: "a",
  target: null,
  rel: null,
  validate: !0,
  truncate: 1 / 0,
  className: null,
  attributes: null,
  ignoreTags: [],
  render: null
};
function pf(n, e = null) {
  let t = Object.assign({}, ks);
  n && (t = Object.assign(t, n instanceof pf ? n.o : n));
  const r = t.ignoreTags, i = [];
  for (let o = 0; o < r.length; o++)
    i.push(r[o].toUpperCase());
  this.o = t, e && (this.defaultRender = e), this.ignoreTags = i;
}
pf.prototype = {
  o: ks,
  /**
   * @type string[]
   */
  ignoreTags: [],
  /**
   * @param {IntermediateRepresentation} ir
   * @returns {any}
   */
  defaultRender(n) {
    return n;
  },
  /**
   * 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(n) {
    return this.get("validate", n.toString(), n);
  },
  // 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(n, e, t) {
    const r = e != null;
    let i = this.o[n];
    return i && (typeof i == "object" ? (i = t.t in i ? i[t.t] : ks[n], typeof i == "function" && r && (i = i(e, t))) : typeof i == "function" && r && (i = i(e, t.t, t)), i);
  },
  /**
   * @template {keyof Opts} L
   * @param {L} key Name of options object to use
   * @param {string} [operator]
   * @param {MultiToken} [token]
   * @returns {Opts[L] | any}
   */
  getObj(n, e, t) {
    let r = this.o[n];
    return typeof r == "function" && e != null && (r = r(e, t.t, t)), r;
  },
  /**
   * 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(n) {
    const e = n.render(this);
    return (this.get("render", null, n) || this.defaultRender)(e, n.t, n);
  }
};
function n0(n) {
  return n;
}
function Aw(n, e) {
  this.t = "token", this.v = n, this.tk = e;
}
Aw.prototype = {
  isLink: !1,
  /**
   * 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(n) {
    return this.toString();
  },
  /**
   * @param {Options} options Formatting options
   * @returns {string}
   */
  toFormattedString(n) {
    const e = this.toString(), t = n.get("truncate", e, this), r = n.get("format", e, this);
    return t && r.length > t ? r.substring(0, t) + "…" : r;
  },
  /**
   *
   * @param {Options} options
   * @returns {string}
   */
  toFormattedHref(n) {
    return n.get("formatHref", this.toHref(n.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(n = ks.defaultProtocol) {
    return {
      type: this.t,
      value: this.toString(),
      isLink: this.isLink,
      href: this.toHref(n),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   *
   * @param {Options} options Formatting option
   */
  toFormattedObject(n) {
    return {
      type: this.t,
      value: this.toFormattedString(n),
      isLink: this.isLink,
      href: this.toFormattedHref(n),
      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(n) {
    return n.get("validate", this.toString(), this);
  },
  /**
   * Return an object that represents how this link should be rendered.
   * @param {Options} options Formattinng options
   */
  render(n) {
    const e = this, t = this.toHref(n.get("defaultProtocol")), r = n.get("formatHref", t, this), i = n.get("tagName", t, e), o = this.toFormattedString(n), s = {}, l = n.get("className", t, e), a = n.get("target", t, e), c = n.get("rel", t, e), d = n.getObj("attributes", t, e), u = n.getObj("events", t, e);
    return s.href = r, l && (s.class = l), a && (s.target = a), c && (s.rel = c), d && Object.assign(s, d), {
      tagName: i,
      attributes: s,
      content: o,
      eventListeners: u
    };
  }
};
function Ec(n, e) {
  class t extends Aw {
    constructor(i, o) {
      super(i, o), this.t = n;
    }
  }
  for (const r in e)
    t.prototype[r] = e[r];
  return t.t = n, t;
}
const r0 = Ec("email", {
  isLink: !0,
  toHref() {
    return "mailto:" + this.toString();
  }
}), i0 = Ec("text"), zO = Ec("nl"), Fl = Ec("url", {
  isLink: !0,
  /**
  	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(n = ks.defaultProtocol) {
    return this.hasProtocol() ? this.v : `${n}://${this.v}`;
  },
  /**
   * Check whether this URL token has a protocol
   * @return {boolean}
   */
  hasProtocol() {
    const n = this.tk;
    return n.length >= 2 && n[0].t !== ws && n[1].t === kr;
  }
}), Lt = (n) => new yt(n);
function HO({
  groups: n
}) {
  const e = n.domain.concat([za, Va, yr, Ua, qa, ja, Wa, Ga, Bt, af, ns, Ka, Ja, Ya, vn, Za, is, Xa]), t = [Ha, kr, df, kn, uf, ns, rs, hf, ff, Ma, Oa, es, ts, Da, xa, Aa, Ta, Fa, Na, $a, Ia, La, Ra, Ba, Pa], r = [za, Ha, Va, Ua, qa, ja, Wa, Ga, Bt, es, ts, ns, Ka, Ja, Ya, rs, vn, Za, is, Xa], i = Lt(), o = M(i, is);
  W(o, r, o), W(o, n.domain, o);
  const s = Lt(), l = Lt(), a = Lt();
  W(i, n.domain, s), W(i, n.scheme, l), W(i, n.slashscheme, a), W(s, r, o), W(s, n.domain, s);
  const c = M(s, yr);
  M(o, yr, c), M(l, yr, c), M(a, yr, c);
  const d = M(o, kn);
  W(d, r, o), W(d, n.domain, o);
  const u = Lt();
  W(c, n.domain, u), W(u, n.domain, u);
  const h = M(u, kn);
  W(h, n.domain, u);
  const f = Lt(r0);
  W(h, n.tld, f), W(h, n.utld, f), M(c, ws, f);
  const p = M(u, Bt);
  M(p, Bt, p), W(p, n.domain, u), W(f, n.domain, u), M(f, kn, h), M(f, Bt, p);
  const m = M(f, kr);
  W(m, n.numeric, r0);
  const g = M(s, Bt), y = M(s, kn);
  M(g, Bt, g), W(g, n.domain, s), W(y, r, o), W(y, n.domain, s);
  const _ = Lt(Fl);
  W(y, n.tld, _), W(y, n.utld, _), W(_, n.domain, s), W(_, r, o), M(_, kn, y), M(_, Bt, g), M(_, yr, c);
  const b = M(_, kr), k = Lt(Fl);
  W(b, n.numeric, k);
  const C = Lt(Fl), w = Lt();
  W(C, e, C), W(C, t, w), W(w, e, C), W(w, t, w), M(_, vn, C), M(k, vn, C);
  const x = M(l, kr), S = M(a, kr), D = M(S, vn), T = M(D, vn);
  W(l, n.domain, s), M(l, kn, y), M(l, Bt, g), W(a, n.domain, s), M(a, kn, y), M(a, Bt, g), W(x, n.domain, C), M(x, vn, C), M(x, rs, C), W(T, n.domain, C), W(T, e, C), M(T, vn, C);
  const I = [
    [es, ts],
    // {}
    [xa, Da],
    // []
    [Aa, Ta],
    // ()
    [Ma, Oa],
    // <>
    [Fa, Na],
    // （）
    [$a, Ia],
    // 「」
    [La, Ra],
    // 『』
    [Ba, Pa]
    // ＜＞
  ];
  for (let U = 0; U < I.length; U++) {
    const [Te, ce] = I[U], fe = M(C, Te);
    M(w, Te, fe), M(fe, ce, C);
    const K = Lt(Fl);
    W(fe, e, K);
    const be = Lt();
    W(fe, t), W(K, e, K), W(K, t, be), W(be, e, K), W(be, t, be), M(K, ce, C), M(be, ce, C);
  }
  return M(i, ws, _), M(i, cf, zO), {
    start: i,
    tokens: xw
  };
}
function VO(n, e, t) {
  let r = t.length, i = 0, o = [], s = [];
  for (; i < r; ) {
    let l = n, a = null, c = null, d = 0, u = null, h = -1;
    for (; i < r && !(a = l.go(t[i].t)); )
      s.push(t[i++]);
    for (; i < r && (c = a || l.go(t[i].t)); )
      a = null, l = c, l.accepts() ? (h = 0, u = l) : h >= 0 && h++, i++, d++;
    if (h < 0)
      i -= d, i < r && (s.push(t[i]), i++);
    else {
      s.length > 0 && (o.push(Hd(i0, e, s)), s = []), i -= h, d -= h;
      const f = u.t, p = t.slice(i - d, i);
      o.push(Hd(f, e, p));
    }
  }
  return s.length > 0 && o.push(Hd(i0, e, s)), o;
}
function Hd(n, e, t) {
  const r = t[0].s, i = t[t.length - 1].e, o = e.slice(r, i);
  return new n(o, t);
}
const UO = typeof console < "u" && console && console.warn || (() => {
}), qO = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.", me = {
  scanner: null,
  parser: null,
  tokenQueue: [],
  pluginQueue: [],
  customSchemes: [],
  initialized: !1
};
function jO() {
  return yt.groups = {}, me.scanner = null, me.parser = null, me.tokenQueue = [], me.pluginQueue = [], me.customSchemes = [], me.initialized = !1, me;
}
function o0(n, e = !1) {
  if (me.initialized && UO(`linkifyjs: already initialized - will not register custom scheme "${n}" ${qO}`), !/^[0-9a-z]+(-[0-9a-z]+)*$/.test(n))
    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`);
  me.customSchemes.push([n, e]);
}
function WO() {
  me.scanner = BO(me.customSchemes);
  for (let n = 0; n < me.tokenQueue.length; n++)
    me.tokenQueue[n][1]({
      scanner: me.scanner
    });
  me.parser = HO(me.scanner.tokens);
  for (let n = 0; n < me.pluginQueue.length; n++)
    me.pluginQueue[n][1]({
      scanner: me.scanner,
      parser: me.parser
    });
  return me.initialized = !0, me;
}
function mf(n) {
  return me.initialized || WO(), VO(me.parser.start, n, Dw(me.scanner.start, n));
}
mf.scan = Dw;
function Tw(n, e = null, t = null) {
  if (e && typeof e == "object") {
    if (t)
      throw Error(`linkifyjs: Invalid link type ${e}; must be a string`);
    t = e, e = null;
  }
  const r = new pf(t), i = mf(n), o = [];
  for (let s = 0; s < i.length; s++) {
    const l = i[s];
    l.isLink && (!e || l.t === e) && r.check(l) && o.push(l.toFormattedObject(r));
  }
  return o;
}
const gf = "[\0-   ᠎ -\u2029 　]", GO = new RegExp(gf), KO = new RegExp(`${gf}$`), JO = new RegExp(gf, "g");
function YO(n) {
  return n.length === 1 ? n[0].isLink : n.length === 3 && n[1].isLink ? ["()", "[]"].includes(n[0].value + n[2].value) : !1;
}
function XO(n) {
  return new G({
    key: new te("autolink"),
    appendTransaction: (e, t, r) => {
      const i = e.some((c) => c.docChanged) && !t.doc.eq(r.doc), o = e.some((c) => c.getMeta("preventAutolink"));
      if (!i || o)
        return;
      const { tr: s } = r, l = Zh(t.doc, [...e]);
      if (Z_(l).forEach(({ newRange: c }) => {
        const d = Y_(r.doc, c, (f) => f.isTextblock);
        let u, h;
        if (d.length > 1)
          u = d[0], h = r.doc.textBetween(u.pos, u.pos + u.node.nodeSize, void 0, " ");
        else if (d.length) {
          const f = r.doc.textBetween(c.from, c.to, " ", " ");
          if (!KO.test(f))
            return;
          u = d[0], h = r.doc.textBetween(u.pos, c.to, void 0, " ");
        }
        if (u && h) {
          const f = h.split(GO).filter(Boolean);
          if (f.length <= 0)
            return !1;
          const p = f[f.length - 1], m = u.pos + h.lastIndexOf(p);
          if (!p)
            return !1;
          const g = mf(p).map((y) => y.toObject(n.defaultProtocol));
          if (!YO(g))
            return !1;
          g.filter((y) => y.isLink).map((y) => ({
            ...y,
            from: m + y.start + 1,
            to: m + y.end + 1
          })).filter((y) => r.schema.marks.code ? !r.doc.rangeHasMark(y.from, y.to, r.schema.marks.code) : !0).filter((y) => n.validate(y.value)).filter((y) => n.shouldAutoLink(y.value)).forEach((y) => {
            Qh(y.from, y.to, r.doc).some((_) => _.mark.type === n.type) || s.addMark(y.from, y.to, n.type.create({
              href: y.href
            }));
          });
        }
      }), !!s.steps.length)
        return s;
    }
  });
}
function ZO(n) {
  return new G({
    key: new te("handleClickLink"),
    props: {
      handleClick: (e, t, r) => {
        var i, o;
        if (r.button !== 0 || !e.editable)
          return !1;
        let s = r.target;
        const l = [];
        for (; s.nodeName !== "DIV"; )
          l.push(s), s = s.parentNode;
        if (!l.find((h) => h.nodeName === "A"))
          return !1;
        const a = X_(e.state, n.type.name), c = r.target, d = (i = c == null ? void 0 : c.href) !== null && i !== void 0 ? i : a.href, u = (o = c == null ? void 0 : c.target) !== null && o !== void 0 ? o : a.target;
        return c && d ? (window.open(d, u), !0) : !1;
      }
    }
  });
}
function QO(n) {
  return new G({
    key: new te("handlePasteLink"),
    props: {
      handlePaste: (e, t, r) => {
        const { state: i } = e, { selection: o } = i, { empty: s } = o;
        if (s)
          return !1;
        let l = "";
        r.content.forEach((c) => {
          l += c.textContent;
        });
        const a = Tw(l, { defaultProtocol: n.defaultProtocol }).find((c) => c.isLink && c.value === l);
        return !l || !a ? !1 : n.editor.commands.setMark(n.type, {
          href: a.href
        });
      }
    }
  });
}
function Wr(n, e) {
  const t = [
    "http",
    "https",
    "ftp",
    "ftps",
    "mailto",
    "tel",
    "callto",
    "sms",
    "cid",
    "xmpp"
  ];
  return e && e.forEach((r) => {
    const i = typeof r == "string" ? r : r.scheme;
    i && t.push(i);
  }), !n || n.replace(JO, "").match(new RegExp(
    // eslint-disable-next-line no-useless-escape
    `^(?:(?:${t.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,
    "i"
  ));
}
const eF = Je.create({
  name: "link",
  priority: 1e3,
  keepOnSplit: !1,
  exitable: !0,
  onCreate() {
    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((n) => {
      if (typeof n == "string") {
        o0(n);
        return;
      }
      o0(n.scheme, n.optionalSlashes);
    });
  },
  onDestroy() {
    jO();
  },
  inclusive() {
    return this.options.autolink;
  },
  addOptions() {
    return {
      openOnClick: !0,
      linkOnPaste: !0,
      autolink: !0,
      protocols: [],
      defaultProtocol: "http",
      HTMLAttributes: {
        target: "_blank",
        rel: "noopener noreferrer nofollow",
        class: null
      },
      isAllowedUri: (n, e) => !!Wr(n, e.protocols),
      validate: (n) => !!n,
      shouldAutoLink: (n) => !!n
    };
  },
  addAttributes() {
    return {
      href: {
        default: null,
        parseHTML(n) {
          return n.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: (n) => {
          const e = n.getAttribute("href");
          return !e || !this.options.isAllowedUri(e, {
            defaultValidate: (t) => !!Wr(t, this.options.protocols),
            protocols: this.options.protocols,
            defaultProtocol: this.options.defaultProtocol
          }) ? !1 : null;
        }
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return this.options.isAllowedUri(n.href, {
      defaultValidate: (e) => !!Wr(e, this.options.protocols),
      protocols: this.options.protocols,
      defaultProtocol: this.options.defaultProtocol
    }) ? ["a", Tt(this.options.HTMLAttributes, n), 0] : [
      "a",
      Tt(this.options.HTMLAttributes, { ...n, href: "" }),
      0
    ];
  },
  addCommands() {
    return {
      setLink: (n) => ({ chain: e }) => {
        const { href: t } = n;
        return this.options.isAllowedUri(t, {
          defaultValidate: (r) => !!Wr(r, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        }) ? e().setMark(this.name, n).setMeta("preventAutolink", !0).run() : !1;
      },
      toggleLink: (n) => ({ chain: e }) => {
        const { href: t } = n;
        return this.options.isAllowedUri(t, {
          defaultValidate: (r) => !!Wr(r, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        }) ? e().toggleMark(this.name, n, { extendEmptyMarkRange: !0 }).setMeta("preventAutolink", !0).run() : !1;
      },
      unsetLink: () => ({ chain: n }) => n().unsetMark(this.name, { extendEmptyMarkRange: !0 }).setMeta("preventAutolink", !0).run()
    };
  },
  addPasteRules() {
    return [
      gi({
        find: (n) => {
          const e = [];
          if (n) {
            const { protocols: t, defaultProtocol: r } = this.options, i = Tw(n).filter((o) => o.isLink && this.options.isAllowedUri(o.value, {
              defaultValidate: (s) => !!Wr(s, t),
              protocols: t,
              defaultProtocol: r
            }));
            i.length && i.forEach((o) => e.push({
              text: o.value,
              data: {
                href: o.href
              },
              index: o.start
            }));
          }
          return e;
        },
        type: this.type,
        getAttributes: (n) => {
          var e;
          return {
            href: (e = n.data) === null || e === void 0 ? void 0 : e.href
          };
        }
      })
    ];
  },
  addProseMirrorPlugins() {
    const n = [], { protocols: e, defaultProtocol: t } = this.options;
    return this.options.autolink && n.push(XO({
      type: this.type,
      defaultProtocol: this.options.defaultProtocol,
      validate: (r) => this.options.isAllowedUri(r, {
        defaultValidate: (i) => !!Wr(i, e),
        protocols: e,
        defaultProtocol: t
      }),
      shouldAutoLink: this.options.shouldAutoLink
    })), this.options.openOnClick === !0 && n.push(ZO({
      type: this.type
    })), this.options.linkOnPaste && n.push(QO({
      editor: this.editor,
      defaultProtocol: this.options.defaultProtocol,
      type: this.type
    })), n;
  }
}), tF = Mt.create({
  name: "text",
  group: "inline"
}), Kt = () => /* @__PURE__ */ new Map(), Ku = (n) => {
  const e = Kt();
  return n.forEach((t, r) => {
    e.set(r, t);
  }), e;
}, Bn = (n, e, t) => {
  let r = n.get(e);
  return r === void 0 && n.set(e, r = t()), r;
}, nF = (n, e) => {
  const t = [];
  for (const [r, i] of n)
    t.push(e(i, r));
  return t;
}, rF = (n, e) => {
  for (const [t, r] of n)
    if (e(r, t))
      return !0;
  return !1;
}, yi = () => /* @__PURE__ */ new Set(), Vd = (n) => n[n.length - 1], iF = (n, e) => {
  for (let t = 0; t < e.length; t++)
    n.push(e[t]);
}, Nr = Array.from, oF = (n, e) => {
  for (let t = 0; t < n.length; t++)
    if (e(n[t], t, n))
      return !0;
  return !1;
}, Ju = Array.isArray;
class Mw {
  constructor() {
    this._observers = Kt();
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  on(e, t) {
    return Bn(
      this._observers,
      /** @type {string} */
      e,
      yi
    ).add(t), t;
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  once(e, t) {
    const r = (...i) => {
      this.off(
        e,
        /** @type {any} */
        r
      ), t(...i);
    };
    this.on(
      e,
      /** @type {any} */
      r
    );
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  off(e, t) {
    const r = this._observers.get(e);
    r !== void 0 && (r.delete(t), r.size === 0 && this._observers.delete(e));
  }
  /**
   * 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(e, t) {
    return Nr((this._observers.get(e) || Kt()).values()).forEach((r) => r(...t));
  }
  destroy() {
    this._observers = Kt();
  }
}
const ir = Math.floor, ea = Math.abs, nr = (n, e) => n < e ? n : e, fn = (n, e) => n > e ? n : e, Ow = (n) => n !== 0 ? n < 0 : 1 / n < 0, s0 = 1, l0 = 2, Ud = 4, qd = 8, vs = 32, rr = 64, ct = 128, sF = 1 << 29, xc = 31, Yu = 63, ai = 127, lF = 2147483647, Fw = Number.MAX_SAFE_INTEGER, aF = Number.isInteger || ((n) => typeof n == "number" && isFinite(n) && ir(n) === n), cF = String.fromCharCode, dF = (n) => n.toLowerCase(), uF = /^\s*/g, hF = (n) => n.replace(uF, ""), fF = /([A-Z])/g, a0 = (n, e) => hF(n.replace(fF, (t) => `${e}${dF(t)}`)), pF = (n) => {
  const e = unescape(encodeURIComponent(n)), t = e.length, r = new Uint8Array(t);
  for (let i = 0; i < t; i++)
    r[i] = /** @type {number} */
    e.codePointAt(i);
  return r;
}, Cs = (
  /** @type {TextEncoder} */
  typeof TextEncoder < "u" ? new TextEncoder() : null
), mF = (n) => Cs.encode(n), gF = Cs ? mF : pF;
let ss = typeof TextDecoder > "u" ? null : new TextDecoder("utf-8", { fatal: !0, ignoreBOM: !0 });
ss && ss.decode(new Uint8Array()).length === 1 && (ss = null);
class Vs {
  constructor() {
    this.cpos = 0, this.cbuf = new Uint8Array(100), this.bufs = [];
  }
}
const Us = () => new Vs(), bF = (n) => {
  const e = Us();
  return n(e), cn(e);
}, yF = (n) => {
  let e = n.cpos;
  for (let t = 0; t < n.bufs.length; t++)
    e += n.bufs[t].length;
  return e;
}, cn = (n) => {
  const e = new Uint8Array(yF(n));
  let t = 0;
  for (let r = 0; r < n.bufs.length; r++) {
    const i = n.bufs[r];
    e.set(i, t), t += i.length;
  }
  return e.set(new Uint8Array(n.cbuf.buffer, 0, n.cpos), t), e;
}, _F = (n, e) => {
  const t = n.cbuf.length;
  t - n.cpos < e && (n.bufs.push(new Uint8Array(n.cbuf.buffer, 0, n.cpos)), n.cbuf = new Uint8Array(fn(t, e) * 2), n.cpos = 0);
}, Be = (n, e) => {
  const t = n.cbuf.length;
  n.cpos === t && (n.bufs.push(n.cbuf), n.cbuf = new Uint8Array(t * 2), n.cpos = 0), n.cbuf[n.cpos++] = e;
}, Xu = Be, Z = (n, e) => {
  for (; e > ai; )
    Be(n, ct | ai & e), e = ir(e / 128);
  Be(n, ai & e);
}, bf = (n, e) => {
  const t = Ow(e);
  for (t && (e = -e), Be(n, (e > Yu ? ct : 0) | (t ? rr : 0) | Yu & e), e = ir(e / 64); e > 0; )
    Be(n, (e > ai ? ct : 0) | ai & e), e = ir(e / 128);
}, Zu = new Uint8Array(3e4), wF = Zu.length / 3, kF = (n, e) => {
  if (e.length < wF) {
    const t = Cs.encodeInto(e, Zu).written || 0;
    Z(n, t);
    for (let r = 0; r < t; r++)
      Be(n, Zu[r]);
  } else
    Ct(n, gF(e));
}, vF = (n, e) => {
  const t = unescape(encodeURIComponent(e)), r = t.length;
  Z(n, r);
  for (let i = 0; i < r; i++)
    Be(
      n,
      /** @type {number} */
      t.codePointAt(i)
    );
}, Xi = Cs && /** @type {any} */
Cs.encodeInto ? kF : vF, Dc = (n, e) => {
  const t = n.cbuf.length, r = n.cpos, i = nr(t - r, e.length), o = e.length - i;
  n.cbuf.set(e.subarray(0, i), r), n.cpos += i, o > 0 && (n.bufs.push(n.cbuf), n.cbuf = new Uint8Array(fn(t * 2, o)), n.cbuf.set(e.subarray(i)), n.cpos = o);
}, Ct = (n, e) => {
  Z(n, e.byteLength), Dc(n, e);
}, yf = (n, e) => {
  _F(n, e);
  const t = new DataView(n.cbuf.buffer, n.cpos, e);
  return n.cpos += e, t;
}, CF = (n, e) => yf(n, 4).setFloat32(0, e, !1), SF = (n, e) => yf(n, 8).setFloat64(0, e, !1), EF = (n, e) => (
  /** @type {any} */
  yf(n, 8).setBigInt64(0, e, !1)
), c0 = new DataView(new ArrayBuffer(4)), xF = (n) => (c0.setFloat32(0, n), c0.getFloat32(0) === n), co = (n, e) => {
  switch (typeof e) {
    case "string":
      Be(n, 119), Xi(n, e);
      break;
    case "number":
      aF(e) && ea(e) <= lF ? (Be(n, 125), bf(n, e)) : xF(e) ? (Be(n, 124), CF(n, e)) : (Be(n, 123), SF(n, e));
      break;
    case "bigint":
      Be(n, 122), EF(n, e);
      break;
    case "object":
      if (e === null)
        Be(n, 126);
      else if (Ju(e)) {
        Be(n, 117), Z(n, e.length);
        for (let t = 0; t < e.length; t++)
          co(n, e[t]);
      } else if (e instanceof Uint8Array)
        Be(n, 116), Ct(n, e);
      else {
        Be(n, 118);
        const t = Object.keys(e);
        Z(n, t.length);
        for (let r = 0; r < t.length; r++) {
          const i = t[r];
          Xi(n, i), co(n, e[i]);
        }
      }
      break;
    case "boolean":
      Be(n, e ? 120 : 121);
      break;
    default:
      Be(n, 127);
  }
};
class d0 extends Vs {
  /**
   * @param {function(Encoder, T):void} writer
   */
  constructor(e) {
    super(), this.w = e, this.s = null, this.count = 0;
  }
  /**
   * @param {T} v
   */
  write(e) {
    this.s === e ? this.count++ : (this.count > 0 && Z(this, this.count - 1), this.count = 1, this.w(this, e), this.s = e);
  }
}
const u0 = (n) => {
  n.count > 0 && (bf(n.encoder, n.count === 1 ? n.s : -n.s), n.count > 1 && Z(n.encoder, n.count - 2));
};
class ta {
  constructor() {
    this.encoder = new Vs(), this.s = 0, this.count = 0;
  }
  /**
   * @param {number} v
   */
  write(e) {
    this.s === e ? this.count++ : (u0(this), this.count = 1, this.s = e);
  }
  /**
   * Flush the encoded state and transform this to a Uint8Array.
   *
   * Note that this should only be called once.
   */
  toUint8Array() {
    return u0(this), cn(this.encoder);
  }
}
const h0 = (n) => {
  if (n.count > 0) {
    const e = n.diff * 2 + (n.count === 1 ? 0 : 1);
    bf(n.encoder, e), n.count > 1 && Z(n.encoder, n.count - 2);
  }
};
class jd {
  constructor() {
    this.encoder = new Vs(), this.s = 0, this.count = 0, this.diff = 0;
  }
  /**
   * @param {number} v
   */
  write(e) {
    this.diff === e - this.s ? (this.s = e, this.count++) : (h0(this), this.count = 1, this.diff = e - this.s, this.s = e);
  }
  /**
   * Flush the encoded state and transform this to a Uint8Array.
   *
   * Note that this should only be called once.
   */
  toUint8Array() {
    return h0(this), cn(this.encoder);
  }
}
class DF {
  constructor() {
    this.sarr = [], this.s = "", this.lensE = new ta();
  }
  /**
   * @param {string} string
   */
  write(e) {
    this.s += e, this.s.length > 19 && (this.sarr.push(this.s), this.s = ""), this.lensE.write(e.length);
  }
  toUint8Array() {
    const e = new Vs();
    return this.sarr.push(this.s), this.s = "", Xi(e, this.sarr.join("")), Dc(e, this.lensE.toUint8Array()), cn(e);
  }
}
const $r = (n) => new Error(n), un = () => {
  throw $r("Method unimplemented");
}, Ot = () => {
  throw $r("Unexpected case");
}, Nw = $r("Unexpected end of array"), $w = $r("Integer out of Range");
class Ac {
  /**
   * @param {Uint8Array} uint8Array Binary data to decode
   */
  constructor(e) {
    this.arr = e, this.pos = 0;
  }
}
const yo = (n) => new Ac(n), AF = (n) => n.pos !== n.arr.length, TF = (n, e) => {
  const t = new Uint8Array(n.arr.buffer, n.pos + n.arr.byteOffset, e);
  return n.pos += e, t;
}, St = (n) => TF(n, J(n)), uo = (n) => n.arr[n.pos++], J = (n) => {
  let e = 0, t = 1;
  const r = n.arr.length;
  for (; n.pos < r; ) {
    const i = n.arr[n.pos++];
    if (e = e + (i & ai) * t, t *= 128, i < ct)
      return e;
    if (e > Fw)
      throw $w;
  }
  throw Nw;
}, _f = (n) => {
  let e = n.arr[n.pos++], t = e & Yu, r = 64;
  const i = (e & rr) > 0 ? -1 : 1;
  if (!(e & ct))
    return i * t;
  const o = n.arr.length;
  for (; n.pos < o; ) {
    if (e = n.arr[n.pos++], t = t + (e & ai) * r, r *= 128, e < ct)
      return i * t;
    if (t > Fw)
      throw $w;
  }
  throw Nw;
}, MF = (n) => {
  let e = J(n);
  if (e === 0)
    return "";
  {
    let t = String.fromCodePoint(uo(n));
    if (--e < 100)
      for (; e--; )
        t += String.fromCodePoint(uo(n));
    else
      for (; e > 0; ) {
        const r = e < 1e4 ? e : 1e4, i = n.arr.subarray(n.pos, n.pos + r);
        n.pos += r, t += String.fromCodePoint.apply(
          null,
          /** @type {any} */
          i
        ), e -= r;
      }
    return decodeURIComponent(escape(t));
  }
}, OF = (n) => (
  /** @type any */
  ss.decode(St(n))
), Zi = ss ? OF : MF, wf = (n, e) => {
  const t = new DataView(n.arr.buffer, n.arr.byteOffset + n.pos, e);
  return n.pos += e, t;
}, FF = (n) => wf(n, 4).getFloat32(0, !1), NF = (n) => wf(n, 8).getFloat64(0, !1), $F = (n) => (
  /** @type {any} */
  wf(n, 8).getBigInt64(0, !1)
), IF = [
  (n) => {
  },
  // CASE 127: undefined
  (n) => null,
  // CASE 126: null
  _f,
  // CASE 125: integer
  FF,
  // CASE 124: float32
  NF,
  // CASE 123: float64
  $F,
  // CASE 122: bigint
  (n) => !1,
  // CASE 121: boolean (false)
  (n) => !0,
  // CASE 120: boolean (true)
  Zi,
  // CASE 119: string
  (n) => {
    const e = J(n), t = {};
    for (let r = 0; r < e; r++) {
      const i = Zi(n);
      t[i] = Ss(n);
    }
    return t;
  },
  (n) => {
    const e = J(n), t = [];
    for (let r = 0; r < e; r++)
      t.push(Ss(n));
    return t;
  },
  St
  // CASE 116: Uint8Array
], Ss = (n) => IF[127 - uo(n)](n);
class f0 extends Ac {
  /**
   * @param {Uint8Array} uint8Array
   * @param {function(Decoder):T} reader
   */
  constructor(e, t) {
    super(e), this.reader = t, this.s = null, this.count = 0;
  }
  read() {
    return this.count === 0 && (this.s = this.reader(this), AF(this) ? this.count = J(this) + 1 : this.count = -1), this.count--, /** @type {T} */
    this.s;
  }
}
class na extends Ac {
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(e) {
    super(e), this.s = 0, this.count = 0;
  }
  read() {
    if (this.count === 0) {
      this.s = _f(this);
      const e = Ow(this.s);
      this.count = 1, e && (this.s = -this.s, this.count = J(this) + 2);
    }
    return this.count--, /** @type {number} */
    this.s;
  }
}
class Wd extends Ac {
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(e) {
    super(e), this.s = 0, this.count = 0, this.diff = 0;
  }
  /**
   * @return {number}
   */
  read() {
    if (this.count === 0) {
      const e = _f(this), t = e & 1;
      this.diff = ir(e / 2), this.count = 1, t && (this.count = J(this) + 2);
    }
    return this.s += this.diff, this.count--, this.s;
  }
}
class LF {
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(e) {
    this.decoder = new na(e), this.str = Zi(this.decoder), this.spos = 0;
  }
  /**
   * @return {string}
   */
  read() {
    const e = this.spos + this.decoder.read(), t = this.str.slice(this.spos, e);
    return this.spos = e, t;
  }
}
const RF = crypto.getRandomValues.bind(crypto), BF = Math.random, Iw = () => RF(new Uint32Array(1))[0], PF = (n) => n[ir(BF() * n.length)], zF = "10000000-1000-4000-8000" + -1e11, HF = () => zF.replace(
  /[018]/g,
  /** @param {number} c */
  (n) => (n ^ Iw() & 15 >> n / 4).toString(16)
), VF = Date.now, p0 = (n) => (
  /** @type {Promise<T>} */
  new Promise(n)
);
Promise.all.bind(Promise);
const m0 = (n) => n === void 0 ? null : n;
class UF {
  constructor() {
    this.map = /* @__PURE__ */ new Map();
  }
  /**
   * @param {string} key
   * @param {any} newValue
   */
  setItem(e, t) {
    this.map.set(e, t);
  }
  /**
   * @param {string} key
   */
  getItem(e) {
    return this.map.get(e);
  }
}
let Lw = new UF(), qF = !0;
try {
  typeof localStorage < "u" && localStorage && (Lw = localStorage, qF = !1);
} catch {
}
const jF = Lw, WF = Object.assign, Rw = Object.keys, GF = (n, e) => {
  for (const t in n)
    e(n[t], t);
}, g0 = (n) => Rw(n).length, KF = (n) => {
  for (const e in n)
    return !1;
  return !0;
}, Bw = (n, e) => {
  for (const t in n)
    if (!e(n[t], t))
      return !1;
  return !0;
}, JF = (n, e) => Object.prototype.hasOwnProperty.call(n, e), YF = (n, e) => n === e || g0(n) === g0(e) && Bw(n, (t, r) => (t !== void 0 || JF(e, r)) && e[r] === t), XF = Object.freeze, Pw = (n) => {
  for (const e in n) {
    const t = n[e];
    (typeof t == "object" || typeof t == "function") && Pw(n[e]);
  }
  return XF(n);
}, kf = (n, e, t = 0) => {
  try {
    for (; t < n.length; t++)
      n[t](...e);
  } finally {
    t < n.length && kf(n, e, t + 1);
  }
}, ZF = (n) => n, QF = (n, e) => e.includes(n), ho = typeof process < "u" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process < "u" ? process : 0) === "[object process]", zw = typeof window < "u" && typeof document < "u" && !ho;
let wn;
const eN = () => {
  if (wn === void 0)
    if (ho) {
      wn = Kt();
      const n = process.argv;
      let e = null;
      for (let t = 0; t < n.length; t++) {
        const r = n[t];
        r[0] === "-" ? (e !== null && wn.set(e, ""), e = r) : e !== null && (wn.set(e, r), e = null);
      }
      e !== null && wn.set(e, "");
    } else typeof location == "object" ? (wn = Kt(), (location.search || "?").slice(1).split("&").forEach((n) => {
      if (n.length !== 0) {
        const [e, t] = n.split("=");
        wn.set(`--${a0(e, "-")}`, t), wn.set(`-${a0(e, "-")}`, t);
      }
    })) : wn = Kt();
  return wn;
}, Qu = (n) => eN().has(n), Qa = (n) => m0(ho ? process.env[n.toUpperCase().replaceAll("-", "_")] : jF.getItem(n)), Hw = (n) => Qu("--" + n) || Qa(n) !== null;
Hw("production");
const tN = ho && QF(process.env.FORCE_COLOR, ["true", "1", "2"]), nN = tN || !Qu("--no-colors") && // @todo deprecate --no-colors
!Hw("no-color") && (!ho || process.stdout.isTTY) && (!ho || Qu("--color") || Qa("COLORTERM") !== null || (Qa("TERM") || "").includes("color")), rN = (n) => new Uint8Array(n), iN = (n) => {
  let e = "";
  for (let t = 0; t < n.byteLength; t++)
    e += cF(n[t]);
  return btoa(e);
}, oN = (n) => Buffer.from(n.buffer, n.byteOffset, n.byteLength).toString("base64"), sN = zw ? iN : oN, lN = (n) => {
  const e = rN(n.byteLength);
  return e.set(n), e;
}, aN = (n) => bF((e) => co(e, n));
class cN {
  /**
   * @param {L} left
   * @param {R} right
   */
  constructor(e, t) {
    this.left = e, this.right = t;
  }
}
const jn = (n, e) => new cN(n, e), dN = (
  /** @type {Document} */
  typeof document < "u" ? document : {}
);
typeof DOMParser < "u" && new DOMParser();
const uN = (n) => nF(n, (e, t) => `${t}:${e};`).join(""), hN = (n) => class {
  /**
   * @param {number} timeoutId
   */
  constructor(t) {
    this._ = t;
  }
  destroy() {
    n(this._);
  }
}, fN = hN(clearTimeout), vf = (n, e) => new fN(setTimeout(e, n)), lr = Symbol, Vw = lr(), Uw = lr(), pN = lr(), mN = lr(), gN = lr(), qw = lr(), bN = lr(), Cf = lr(), yN = lr(), _N = (n) => {
  var i;
  n.length === 1 && ((i = n[0]) == null ? void 0 : i.constructor) === Function && (n = /** @type {Array<string|Symbol|Object|number>} */
  /** @type {[function]} */
  n[0]());
  const e = [], t = [];
  let r = 0;
  for (; r < n.length; r++) {
    const o = n[r];
    if (o === void 0)
      break;
    if (o.constructor === String || o.constructor === Number)
      e.push(o);
    else if (o.constructor === Object)
      break;
  }
  for (r > 0 && t.push(e.join("")); r < n.length; r++) {
    const o = n[r];
    o instanceof Symbol || t.push(o);
  }
  return t;
}, wN = {
  [Vw]: jn("font-weight", "bold"),
  [Uw]: jn("font-weight", "normal"),
  [pN]: jn("color", "blue"),
  [gN]: jn("color", "green"),
  [mN]: jn("color", "grey"),
  [qw]: jn("color", "red"),
  [bN]: jn("color", "purple"),
  [Cf]: jn("color", "orange"),
  // not well supported in chrome when debugging node with inspector - TODO: deprecate
  [yN]: jn("color", "black")
}, kN = (n) => {
  var s;
  n.length === 1 && ((s = n[0]) == null ? void 0 : s.constructor) === Function && (n = /** @type {Array<string|Symbol|Object|number>} */
  /** @type {[function]} */
  n[0]());
  const e = [], t = [], r = Kt();
  let i = [], o = 0;
  for (; o < n.length; o++) {
    const l = n[o], a = wN[l];
    if (a !== void 0)
      r.set(a.left, a.right);
    else {
      if (l === void 0)
        break;
      if (l.constructor === String || l.constructor === Number) {
        const c = uN(r);
        o > 0 || c.length > 0 ? (e.push("%c" + l), t.push(c)) : e.push(l);
      } else
        break;
    }
  }
  for (o > 0 && (i = t, i.unshift(e.join(""))); o < n.length; o++) {
    const l = n[o];
    l instanceof Symbol || i.push(l);
  }
  return i;
}, jw = nN ? kN : _N, vN = (...n) => {
  console.log(...jw(n)), Gw.forEach((e) => e.print(n));
}, Ww = (...n) => {
  console.warn(...jw(n)), n.unshift(Cf), Gw.forEach((e) => e.print(n));
}, Gw = yi(), Kw = (n) => ({
  /**
   * @return {IterableIterator<T>}
   */
  [Symbol.iterator]() {
    return this;
  },
  // @ts-ignore
  next: n
}), CN = (n, e) => Kw(() => {
  let t;
  do
    t = n.next();
  while (!t.done && !e(t.value));
  return t;
}), Gd = (n, e) => Kw(() => {
  const { done: t, value: r } = n.next();
  return { done: t, value: t ? void 0 : e(r) };
});
class Sf {
  /**
   * @param {number} clock
   * @param {number} len
   */
  constructor(e, t) {
    this.clock = e, this.len = t;
  }
}
class _o {
  constructor() {
    this.clients = /* @__PURE__ */ new Map();
  }
}
const Ir = (n, e, t) => e.clients.forEach((r, i) => {
  const o = (
    /** @type {Array<GC|Item>} */
    n.doc.store.clients.get(i)
  );
  if (o != null) {
    const s = o[o.length - 1], l = s.id.clock + s.length;
    for (let a = 0, c = r[a]; a < r.length && c.clock < l; c = r[++a])
      a1(n, o, c.clock, c.len, t);
  }
}), SN = (n, e) => {
  let t = 0, r = n.length - 1;
  for (; t <= r; ) {
    const i = ir((t + r) / 2), o = n[i], s = o.clock;
    if (s <= e) {
      if (e < s + o.len)
        return i;
      t = i + 1;
    } else
      r = i - 1;
  }
  return null;
}, wo = (n, e) => {
  const t = n.clients.get(e.client);
  return t !== void 0 && SN(t, e.clock) !== null;
}, Ef = (n) => {
  n.clients.forEach((e) => {
    e.sort((i, o) => i.clock - o.clock);
    let t, r;
    for (t = 1, r = 1; t < e.length; t++) {
      const i = e[r - 1], o = e[t];
      i.clock + i.len >= o.clock ? i.len = fn(i.len, o.clock + o.len - i.clock) : (r < t && (e[r] = o), r++);
    }
    e.length = r;
  });
}, eh = (n) => {
  const e = new _o();
  for (let t = 0; t < n.length; t++)
    n[t].clients.forEach((r, i) => {
      if (!e.clients.has(i)) {
        const o = r.slice();
        for (let s = t + 1; s < n.length; s++)
          iF(o, n[s].clients.get(i) || []);
        e.clients.set(i, o);
      }
    });
  return Ef(e), e;
}, Es = (n, e, t, r) => {
  Bn(n.clients, e, () => (
    /** @type {Array<DeleteItem>} */
    []
  )).push(new Sf(t, r));
}, Jw = () => new _o(), Yw = (n) => {
  const e = Jw();
  return n.clients.forEach((t, r) => {
    const i = [];
    for (let o = 0; o < t.length; o++) {
      const s = t[o];
      if (s.deleted) {
        const l = s.id.clock;
        let a = s.length;
        if (o + 1 < t.length)
          for (let c = t[o + 1]; o + 1 < t.length && c.deleted; c = t[++o + 1])
            a += c.length;
        i.push(new Sf(l, a));
      }
    }
    i.length > 0 && e.clients.set(r, i);
  }), e;
}, ko = (n, e) => {
  Z(n.restEncoder, e.clients.size), Nr(e.clients.entries()).sort((t, r) => r[0] - t[0]).forEach(([t, r]) => {
    n.resetDsCurVal(), Z(n.restEncoder, t);
    const i = r.length;
    Z(n.restEncoder, i);
    for (let o = 0; o < i; o++) {
      const s = r[o];
      n.writeDsClock(s.clock), n.writeDsLen(s.len);
    }
  });
}, xf = (n) => {
  const e = new _o(), t = J(n.restDecoder);
  for (let r = 0; r < t; r++) {
    n.resetDsCurVal();
    const i = J(n.restDecoder), o = J(n.restDecoder);
    if (o > 0) {
      const s = Bn(e.clients, i, () => (
        /** @type {Array<DeleteItem>} */
        []
      ));
      for (let l = 0; l < o; l++)
        s.push(new Sf(n.readDsClock(), n.readDsLen()));
    }
  }
  return e;
}, b0 = (n, e, t) => {
  const r = new _o(), i = J(n.restDecoder);
  for (let o = 0; o < i; o++) {
    n.resetDsCurVal();
    const s = J(n.restDecoder), l = J(n.restDecoder), a = t.clients.get(s) || [], c = De(t, s);
    for (let d = 0; d < l; d++) {
      const u = n.readDsClock(), h = u + n.readDsLen();
      if (u < c) {
        c < h && Es(r, s, c, h - c);
        let f = Zt(a, u), p = a[f];
        for (!p.deleted && p.id.clock < u && (a.splice(f + 1, 0, sc(e, p, u - p.id.clock)), f++); f < a.length && (p = a[f++], p.id.clock < h); )
          p.deleted || (h < p.id.clock + p.length && a.splice(f, 0, sc(e, p, h - p.id.clock)), p.delete(e));
      } else
        Es(r, s, u, h - u);
    }
  }
  if (r.clients.size > 0) {
    const o = new _i();
    return Z(o.restEncoder, 0), ko(o, r), o.toUint8Array();
  }
  return null;
}, Xw = Iw;
class Hr extends Mw {
  /**
   * @param {DocOpts} opts configuration
   */
  constructor({ guid: e = HF(), collectionid: t = null, gc: r = !0, gcFilter: i = () => !0, meta: o = null, autoLoad: s = !1, shouldLoad: l = !0 } = {}) {
    super(), this.gc = r, this.gcFilter = i, this.clientID = Xw(), this.guid = e, this.collectionid = t, this.share = /* @__PURE__ */ new Map(), this.store = new s1(), this._transaction = null, this._transactionCleanups = [], this.subdocs = /* @__PURE__ */ new Set(), this._item = null, this.shouldLoad = l, this.autoLoad = s, this.meta = o, this.isLoaded = !1, this.isSynced = !1, this.isDestroyed = !1, this.whenLoaded = p0((c) => {
      this.on("load", () => {
        this.isLoaded = !0, c(this);
      });
    });
    const a = () => p0((c) => {
      const d = (u) => {
        (u === void 0 || u === !0) && (this.off("sync", d), c());
      };
      this.on("sync", d);
    });
    this.on("sync", (c) => {
      c === !1 && this.isSynced && (this.whenSynced = a()), this.isSynced = c === void 0 || c === !0, this.isSynced && !this.isLoaded && this.emit("load", [this]);
    }), this.whenSynced = a();
  }
  /**
   * 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 e = this._item;
    e !== null && !this.shouldLoad && de(
      /** @type {any} */
      e.parent.doc,
      (t) => {
        t.subdocsLoaded.add(this);
      },
      null,
      !0
    ), this.shouldLoad = !0;
  }
  getSubdocs() {
    return this.subdocs;
  }
  getSubdocGuids() {
    return new Set(Nr(this.subdocs).map((e) => e.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(e, t = null) {
    return de(this, e, t);
  }
  /**
   * 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(e, t = (
    /** @type {any} */
    ze
  )) {
    const r = Bn(this.share, e, () => {
      const o = new t();
      return o._integrate(this, null), o;
    }), i = r.constructor;
    if (t !== ze && i !== t)
      if (i === ze) {
        const o = new t();
        o._map = r._map, r._map.forEach(
          /** @param {Item?} n */
          (s) => {
            for (; s !== null; s = s.left)
              s.parent = o;
          }
        ), o._start = r._start;
        for (let s = o._start; s !== null; s = s.right)
          s.parent = o;
        return o._length = r._length, this.share.set(e, o), o._integrate(this, null), /** @type {InstanceType<Type>} */
        o;
      } else
        throw new Error(`Type with the name ${e} has already been defined with a different constructor`);
    return (
      /** @type {InstanceType<Type>} */
      r
    );
  }
  /**
   * @template T
   * @param {string} [name]
   * @return {YArray<T>}
   *
   * @public
   */
  getArray(e = "") {
    return (
      /** @type {YArray<T>} */
      this.get(e, to)
    );
  }
  /**
   * @param {string} [name]
   * @return {YText}
   *
   * @public
   */
  getText(e = "") {
    return this.get(e, Lr);
  }
  /**
   * @template T
   * @param {string} [name]
   * @return {YMap<T>}
   *
   * @public
   */
  getMap(e = "") {
    return (
      /** @type {YMap<T>} */
      this.get(e, po)
    );
  }
  /**
   * @param {string} [name]
   * @return {YXmlElement}
   *
   * @public
   */
  getXmlElement(e = "") {
    return (
      /** @type {YXmlElement<{[key:string]:string}>} */
      this.get(e, at)
    );
  }
  /**
   * @param {string} [name]
   * @return {YXmlFragment}
   *
   * @public
   */
  getXmlFragment(e = "") {
    return this.get(e, wi);
  }
  /**
   * 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 e = {};
    return this.share.forEach((t, r) => {
      e[r] = t.toJSON();
    }), e;
  }
  /**
   * Emit `destroy` event and unregister all event handlers.
   */
  destroy() {
    this.isDestroyed = !0, Nr(this.subdocs).forEach((t) => t.destroy());
    const e = this._item;
    if (e !== null) {
      this._item = null;
      const t = (
        /** @type {ContentDoc} */
        e.content
      );
      t.doc = new Hr({ guid: this.guid, ...t.opts, shouldLoad: !1 }), t.doc._item = e, de(
        /** @type {any} */
        e.parent.doc,
        (r) => {
          const i = t.doc;
          e.deleted || r.subdocsAdded.add(i), r.subdocsRemoved.add(this);
        },
        null,
        !0
      );
    }
    this.emit("destroyed", [!0]), this.emit("destroy", [this]), super.destroy();
  }
}
class Zw {
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(e) {
    this.restDecoder = e;
  }
  resetDsCurVal() {
  }
  /**
   * @return {number}
   */
  readDsClock() {
    return J(this.restDecoder);
  }
  /**
   * @return {number}
   */
  readDsLen() {
    return J(this.restDecoder);
  }
}
class Qw extends Zw {
  /**
   * @return {ID}
   */
  readLeftID() {
    return j(J(this.restDecoder), J(this.restDecoder));
  }
  /**
   * @return {ID}
   */
  readRightID() {
    return j(J(this.restDecoder), J(this.restDecoder));
  }
  /**
   * Read the next client id.
   * Use this in favor of readID whenever possible to reduce the number of objects created.
   */
  readClient() {
    return J(this.restDecoder);
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readInfo() {
    return uo(this.restDecoder);
  }
  /**
   * @return {string}
   */
  readString() {
    return Zi(this.restDecoder);
  }
  /**
   * @return {boolean} isKey
   */
  readParentInfo() {
    return J(this.restDecoder) === 1;
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readTypeRef() {
    return J(this.restDecoder);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @return {number} len
   */
  readLen() {
    return J(this.restDecoder);
  }
  /**
   * @return {any}
   */
  readAny() {
    return Ss(this.restDecoder);
  }
  /**
   * @return {Uint8Array}
   */
  readBuf() {
    return lN(St(this.restDecoder));
  }
  /**
   * Legacy implementation uses JSON parse. We use any-decoding in v2.
   *
   * @return {any}
   */
  readJSON() {
    return JSON.parse(Zi(this.restDecoder));
  }
  /**
   * @return {string}
   */
  readKey() {
    return Zi(this.restDecoder);
  }
}
class EN {
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(e) {
    this.dsCurrVal = 0, this.restDecoder = e;
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  /**
   * @return {number}
   */
  readDsClock() {
    return this.dsCurrVal += J(this.restDecoder), this.dsCurrVal;
  }
  /**
   * @return {number}
   */
  readDsLen() {
    const e = J(this.restDecoder) + 1;
    return this.dsCurrVal += e, e;
  }
}
class fo extends EN {
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(e) {
    super(e), this.keys = [], J(e), this.keyClockDecoder = new Wd(St(e)), this.clientDecoder = new na(St(e)), this.leftClockDecoder = new Wd(St(e)), this.rightClockDecoder = new Wd(St(e)), this.infoDecoder = new f0(St(e), uo), this.stringDecoder = new LF(St(e)), this.parentInfoDecoder = new f0(St(e), uo), this.typeRefDecoder = new na(St(e)), this.lenDecoder = new na(St(e));
  }
  /**
   * @return {ID}
   */
  readLeftID() {
    return new Qi(this.clientDecoder.read(), this.leftClockDecoder.read());
  }
  /**
   * @return {ID}
   */
  readRightID() {
    return new Qi(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 Ss(this.restDecoder);
  }
  /**
   * @return {Uint8Array}
   */
  readBuf() {
    return St(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 Ss(this.restDecoder);
  }
  /**
   * @return {string}
   */
  readKey() {
    const e = this.keyClockDecoder.read();
    if (e < this.keys.length)
      return this.keys[e];
    {
      const t = this.stringDecoder.read();
      return this.keys.push(t), t;
    }
  }
}
class e1 {
  constructor() {
    this.restEncoder = Us();
  }
  toUint8Array() {
    return cn(this.restEncoder);
  }
  resetDsCurVal() {
  }
  /**
   * @param {number} clock
   */
  writeDsClock(e) {
    Z(this.restEncoder, e);
  }
  /**
   * @param {number} len
   */
  writeDsLen(e) {
    Z(this.restEncoder, e);
  }
}
class qs extends e1 {
  /**
   * @param {ID} id
   */
  writeLeftID(e) {
    Z(this.restEncoder, e.client), Z(this.restEncoder, e.clock);
  }
  /**
   * @param {ID} id
   */
  writeRightID(e) {
    Z(this.restEncoder, e.client), Z(this.restEncoder, e.clock);
  }
  /**
   * Use writeClient and writeClock instead of writeID if possible.
   * @param {number} client
   */
  writeClient(e) {
    Z(this.restEncoder, e);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeInfo(e) {
    Xu(this.restEncoder, e);
  }
  /**
   * @param {string} s
   */
  writeString(e) {
    Xi(this.restEncoder, e);
  }
  /**
   * @param {boolean} isYKey
   */
  writeParentInfo(e) {
    Z(this.restEncoder, e ? 1 : 0);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeTypeRef(e) {
    Z(this.restEncoder, e);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @param {number} len
   */
  writeLen(e) {
    Z(this.restEncoder, e);
  }
  /**
   * @param {any} any
   */
  writeAny(e) {
    co(this.restEncoder, e);
  }
  /**
   * @param {Uint8Array} buf
   */
  writeBuf(e) {
    Ct(this.restEncoder, e);
  }
  /**
   * @param {any} embed
   */
  writeJSON(e) {
    Xi(this.restEncoder, JSON.stringify(e));
  }
  /**
   * @param {string} key
   */
  writeKey(e) {
    Xi(this.restEncoder, e);
  }
}
class t1 {
  constructor() {
    this.restEncoder = Us(), this.dsCurrVal = 0;
  }
  toUint8Array() {
    return cn(this.restEncoder);
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  /**
   * @param {number} clock
   */
  writeDsClock(e) {
    const t = e - this.dsCurrVal;
    this.dsCurrVal = e, Z(this.restEncoder, t);
  }
  /**
   * @param {number} len
   */
  writeDsLen(e) {
    e === 0 && Ot(), Z(this.restEncoder, e - 1), this.dsCurrVal += e;
  }
}
class _i extends t1 {
  constructor() {
    super(), this.keyMap = /* @__PURE__ */ new Map(), this.keyClock = 0, this.keyClockEncoder = new jd(), this.clientEncoder = new ta(), this.leftClockEncoder = new jd(), this.rightClockEncoder = new jd(), this.infoEncoder = new d0(Xu), this.stringEncoder = new DF(), this.parentInfoEncoder = new d0(Xu), this.typeRefEncoder = new ta(), this.lenEncoder = new ta();
  }
  toUint8Array() {
    const e = Us();
    return Z(e, 0), Ct(e, this.keyClockEncoder.toUint8Array()), Ct(e, this.clientEncoder.toUint8Array()), Ct(e, this.leftClockEncoder.toUint8Array()), Ct(e, this.rightClockEncoder.toUint8Array()), Ct(e, cn(this.infoEncoder)), Ct(e, this.stringEncoder.toUint8Array()), Ct(e, cn(this.parentInfoEncoder)), Ct(e, this.typeRefEncoder.toUint8Array()), Ct(e, this.lenEncoder.toUint8Array()), Dc(e, cn(this.restEncoder)), cn(e);
  }
  /**
   * @param {ID} id
   */
  writeLeftID(e) {
    this.clientEncoder.write(e.client), this.leftClockEncoder.write(e.clock);
  }
  /**
   * @param {ID} id
   */
  writeRightID(e) {
    this.clientEncoder.write(e.client), this.rightClockEncoder.write(e.clock);
  }
  /**
   * @param {number} client
   */
  writeClient(e) {
    this.clientEncoder.write(e);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeInfo(e) {
    this.infoEncoder.write(e);
  }
  /**
   * @param {string} s
   */
  writeString(e) {
    this.stringEncoder.write(e);
  }
  /**
   * @param {boolean} isYKey
   */
  writeParentInfo(e) {
    this.parentInfoEncoder.write(e ? 1 : 0);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeTypeRef(e) {
    this.typeRefEncoder.write(e);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @param {number} len
   */
  writeLen(e) {
    this.lenEncoder.write(e);
  }
  /**
   * @param {any} any
   */
  writeAny(e) {
    co(this.restEncoder, e);
  }
  /**
   * @param {Uint8Array} buf
   */
  writeBuf(e) {
    Ct(this.restEncoder, e);
  }
  /**
   * 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(e) {
    co(this.restEncoder, e);
  }
  /**
   * 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(e) {
    const t = this.keyMap.get(e);
    t === void 0 ? (this.keyClockEncoder.write(this.keyClock++), this.stringEncoder.write(e)) : this.keyClockEncoder.write(t);
  }
}
const xN = (n, e, t, r) => {
  r = fn(r, e[0].id.clock);
  const i = Zt(e, r);
  Z(n.restEncoder, e.length - i), n.writeClient(t), Z(n.restEncoder, r);
  const o = e[i];
  o.write(n, r - o.id.clock);
  for (let s = i + 1; s < e.length; s++)
    e[s].write(n, 0);
}, Df = (n, e, t) => {
  const r = /* @__PURE__ */ new Map();
  t.forEach((i, o) => {
    De(e, o) > i && r.set(o, i);
  }), js(e).forEach((i, o) => {
    t.has(o) || r.set(o, 0);
  }), Z(n.restEncoder, r.size), Nr(r.entries()).sort((i, o) => o[0] - i[0]).forEach(([i, o]) => {
    xN(
      n,
      /** @type {Array<GC|Item>} */
      e.clients.get(i),
      i,
      o
    );
  });
}, DN = (n, e) => {
  const t = Kt(), r = J(n.restDecoder);
  for (let i = 0; i < r; i++) {
    const o = J(n.restDecoder), s = new Array(o), l = n.readClient();
    let a = J(n.restDecoder);
    t.set(l, { i: 0, refs: s });
    for (let c = 0; c < o; c++) {
      const d = n.readInfo();
      switch (xc & d) {
        case 0: {
          const u = n.readLen();
          s[c] = new Vt(j(l, a), u), a += u;
          break;
        }
        case 10: {
          const u = J(n.restDecoder);
          s[c] = new Ut(j(l, a), u), a += u;
          break;
        }
        default: {
          const u = (d & (rr | ct)) === 0, h = new ie(
            j(l, a),
            null,
            // left
            (d & ct) === ct ? n.readLeftID() : null,
            // origin
            null,
            // right
            (d & rr) === rr ? n.readRightID() : null,
            // right origin
            u ? n.readParentInfo() ? e.get(n.readString()) : n.readLeftID() : null,
            // parent
            u && (d & vs) === vs ? n.readString() : null,
            // parentSub
            M1(n, d)
            // item content
          );
          s[c] = h, a += h.length;
        }
      }
    }
  }
  return t;
}, AN = (n, e, t) => {
  const r = [];
  let i = Nr(t.keys()).sort((f, p) => f - p);
  if (i.length === 0)
    return null;
  const o = () => {
    if (i.length === 0)
      return null;
    let f = (
      /** @type {{i:number,refs:Array<GC|Item>}} */
      t.get(i[i.length - 1])
    );
    for (; f.refs.length === f.i; )
      if (i.pop(), i.length > 0)
        f = /** @type {{i:number,refs:Array<GC|Item>}} */
        t.get(i[i.length - 1]);
      else
        return null;
    return f;
  };
  let s = o();
  if (s === null)
    return null;
  const l = new s1(), a = /* @__PURE__ */ new Map(), c = (f, p) => {
    const m = a.get(f);
    (m == null || m > p) && a.set(f, p);
  };
  let d = (
    /** @type {any} */
    s.refs[
      /** @type {any} */
      s.i++
    ]
  );
  const u = /* @__PURE__ */ new Map(), h = () => {
    for (const f of r) {
      const p = f.id.client, m = t.get(p);
      m ? (m.i--, l.clients.set(p, m.refs.slice(m.i)), t.delete(p), m.i = 0, m.refs = []) : l.clients.set(p, [f]), i = i.filter((g) => g !== p);
    }
    r.length = 0;
  };
  for (; ; ) {
    if (d.constructor !== Ut) {
      const p = Bn(u, d.id.client, () => De(e, d.id.client)) - d.id.clock;
      if (p < 0)
        r.push(d), c(d.id.client, d.id.clock - 1), h();
      else {
        const m = d.getMissing(n, e);
        if (m !== null) {
          r.push(d);
          const g = t.get(
            /** @type {number} */
            m
          ) || { refs: [], i: 0 };
          if (g.refs.length === g.i)
            c(
              /** @type {number} */
              m,
              De(e, m)
            ), h();
          else {
            d = g.refs[g.i++];
            continue;
          }
        } else (p === 0 || p < d.length) && (d.integrate(n, p), u.set(d.id.client, d.id.clock + d.length));
      }
    }
    if (r.length > 0)
      d = /** @type {GC|Item} */
      r.pop();
    else if (s !== null && s.i < s.refs.length)
      d = /** @type {GC|Item} */
      s.refs[s.i++];
    else {
      if (s = o(), s === null)
        break;
      d = /** @type {GC|Item} */
      s.refs[s.i++];
    }
  }
  if (l.clients.size > 0) {
    const f = new _i();
    return Df(f, l, /* @__PURE__ */ new Map()), Z(f.restEncoder, 0), { missing: a, update: f.toUint8Array() };
  }
  return null;
}, TN = (n, e) => Df(n, e.doc.store, e.beforeState), MN = (n, e, t, r = new fo(n)) => de(e, (i) => {
  i.local = !1;
  let o = !1;
  const s = i.doc, l = s.store, a = DN(r, s), c = AN(i, l, a), d = l.pendingStructs;
  if (d) {
    for (const [h, f] of d.missing)
      if (f < De(l, h)) {
        o = !0;
        break;
      }
    if (c) {
      for (const [h, f] of c.missing) {
        const p = d.missing.get(h);
        (p == null || p > f) && d.missing.set(h, f);
      }
      d.update = tc([d.update, c.update]);
    }
  } else
    l.pendingStructs = c;
  const u = b0(r, i, l);
  if (l.pendingDs) {
    const h = new fo(yo(l.pendingDs));
    J(h.restDecoder);
    const f = b0(h, i, l);
    u && f ? l.pendingDs = tc([u, f]) : l.pendingDs = u || f;
  } else
    l.pendingDs = u;
  if (o) {
    const h = (
      /** @type {{update: Uint8Array}} */
      l.pendingStructs.update
    );
    l.pendingStructs = null, ec(i.doc, h);
  }
}, t, !1), ec = (n, e, t, r = fo) => {
  const i = yo(e);
  MN(i, n, t, new r(i));
}, y0 = (n, e, t) => ec(n, e, t, Qw), ON = (n, e, t = /* @__PURE__ */ new Map()) => {
  Df(n, e.store, t), ko(n, Yw(e.store));
}, FN = (n, e = new Uint8Array([0]), t = new _i()) => {
  const r = n1(e);
  ON(t, n, r);
  const i = [t.toUint8Array()];
  if (n.store.pendingDs && i.push(n.store.pendingDs), n.store.pendingStructs && i.push(XN(n.store.pendingStructs.update, e)), i.length > 1) {
    if (t.constructor === qs)
      return JN(i.map((o, s) => s === 0 ? o : QN(o)));
    if (t.constructor === _i)
      return tc(i);
  }
  return i[0];
}, _0 = (n, e) => FN(n, e, new qs()), NN = (n) => {
  const e = /* @__PURE__ */ new Map(), t = J(n.restDecoder);
  for (let r = 0; r < t; r++) {
    const i = J(n.restDecoder), o = J(n.restDecoder);
    e.set(i, o);
  }
  return e;
}, n1 = (n) => NN(new Zw(yo(n))), r1 = (n, e) => (Z(n.restEncoder, e.size), Nr(e.entries()).sort((t, r) => r[0] - t[0]).forEach(([t, r]) => {
  Z(n.restEncoder, t), Z(n.restEncoder, r);
}), n), $N = (n, e) => r1(n, js(e.store)), IN = (n, e = new t1()) => (n instanceof Map ? r1(e, n) : $N(e, n), e.toUint8Array()), LN = (n) => IN(n, new e1());
class RN {
  constructor() {
    this.l = [];
  }
}
const w0 = () => new RN(), k0 = (n, e) => n.l.push(e), v0 = (n, e) => {
  const t = n.l, r = t.length;
  n.l = t.filter((i) => e !== i), r === n.l.length && console.error("[yjs] Tried to remove event handler that doesn't exist.");
}, i1 = (n, e, t) => kf(n.l, [e, t]);
class Qi {
  /**
   * @param {number} client client id
   * @param {number} clock unique per client id, continuous number
   */
  constructor(e, t) {
    this.client = e, this.clock = t;
  }
}
const ji = (n, e) => n === e || n !== null && e !== null && n.client === e.client && n.clock === e.clock, j = (n, e) => new Qi(n, e), xs = (n) => {
  for (const [e, t] of n.doc.share.entries())
    if (t === n)
      return e;
  throw Ot();
}, Ds = (n, e) => {
  for (; e !== null; ) {
    if (e.parent === n)
      return !0;
    e = /** @type {AbstractType<any>} */
    e.parent._item;
  }
  return !1;
};
class As {
  /**
   * @param {ID|null} type
   * @param {string|null} tname
   * @param {ID|null} item
   * @param {number} assoc
   */
  constructor(e, t, r, i = 0) {
    this.type = e, this.tname = t, this.item = r, this.assoc = i;
  }
}
const ls = (n) => new As(n.type == null ? null : j(n.type.client, n.type.clock), n.tname ?? null, n.item == null ? null : j(n.item.client, n.item.clock), n.assoc == null ? 0 : n.assoc);
class BN {
  /**
   * @param {AbstractType<any>} type
   * @param {number} index
   * @param {number} [assoc]
   */
  constructor(e, t, r = 0) {
    this.type = e, this.index = t, this.assoc = r;
  }
}
const PN = (n, e, t = 0) => new BN(n, e, t), Nl = (n, e, t) => {
  let r = null, i = null;
  return n._item === null ? i = xs(n) : r = j(n._item.id.client, n._item.id.clock), new As(r, i, e, t);
}, Kd = (n, e, t = 0) => {
  let r = n._start;
  if (t < 0) {
    if (e === 0)
      return Nl(n, null, t);
    e--;
  }
  for (; r !== null; ) {
    if (!r.deleted && r.countable) {
      if (r.length > e)
        return Nl(n, j(r.id.client, r.id.clock + e), t);
      e -= r.length;
    }
    if (r.right === null && t < 0)
      return Nl(n, r.lastId, t);
    r = r.right;
  }
  return Nl(n, null, t);
}, zN = (n, e) => {
  const t = eo(n, e), r = e.clock - t.id.clock;
  return {
    item: t,
    diff: r
  };
}, HN = (n, e, t = !0) => {
  const r = e.store, i = n.item, o = n.type, s = n.tname, l = n.assoc;
  let a = null, c = 0;
  if (i !== null) {
    if (De(r, i.client) <= i.clock)
      return null;
    const d = t ? ih(r, i) : zN(r, i), u = d.item;
    if (!(u instanceof ie))
      return null;
    if (a = /** @type {AbstractType<any>} */
    u.parent, a._item === null || !a._item.deleted) {
      c = u.deleted || !u.countable ? 0 : d.diff + (l >= 0 ? 0 : 1);
      let h = u.left;
      for (; h !== null; )
        !h.deleted && h.countable && (c += h.length), h = h.left;
    }
  } else {
    if (s !== null)
      a = e.get(s);
    else if (o !== null) {
      if (De(r, o.client) <= o.clock)
        return null;
      const { item: d } = t ? ih(r, o) : { item: eo(r, o) };
      if (d instanceof ie && d.content instanceof gn)
        a = d.content.type;
      else
        return null;
    } else
      throw Ot();
    l >= 0 ? c = a._length : c = 0;
  }
  return PN(a, c, n.assoc);
}, C0 = (n, e) => n === e || n !== null && e !== null && n.tname === e.tname && ji(n.item, e.item) && ji(n.type, e.type) && n.assoc === e.assoc;
class Af {
  /**
   * @param {DeleteSet} ds
   * @param {Map<number,number>} sv state map
   */
  constructor(e, t) {
    this.ds = e, this.sv = t;
  }
}
const o1 = (n, e) => new Af(n, e), Jd = (n) => o1(Yw(n.store), js(n.store)), Jr = (n, e) => e === void 0 ? !n.deleted : e.sv.has(n.id.client) && (e.sv.get(n.id.client) || 0) > n.id.clock && !wo(e.ds, n.id), th = (n, e) => {
  const t = Bn(n.meta, th, yi), r = n.doc.store;
  t.has(e) || (e.sv.forEach((i, o) => {
    i < De(r, o) && _t(n, j(o, i));
  }), Ir(n, e.ds, (i) => {
  }), t.add(e));
};
class s1 {
  constructor() {
    this.clients = /* @__PURE__ */ new Map(), this.pendingStructs = null, this.pendingDs = null;
  }
}
const js = (n) => {
  const e = /* @__PURE__ */ new Map();
  return n.clients.forEach((t, r) => {
    const i = t[t.length - 1];
    e.set(r, i.id.clock + i.length);
  }), e;
}, De = (n, e) => {
  const t = n.clients.get(e);
  if (t === void 0)
    return 0;
  const r = t[t.length - 1];
  return r.id.clock + r.length;
}, l1 = (n, e) => {
  let t = n.clients.get(e.id.client);
  if (t === void 0)
    t = [], n.clients.set(e.id.client, t);
  else {
    const r = t[t.length - 1];
    if (r.id.clock + r.length !== e.id.clock)
      throw Ot();
  }
  t.push(e);
}, Zt = (n, e) => {
  let t = 0, r = n.length - 1, i = n[r], o = i.id.clock;
  if (o === e)
    return r;
  let s = ir(e / (o + i.length - 1) * r);
  for (; t <= r; ) {
    if (i = n[s], o = i.id.clock, o <= e) {
      if (e < o + i.length)
        return s;
      t = s + 1;
    } else
      r = s - 1;
    s = ir((t + r) / 2);
  }
  throw Ot();
}, VN = (n, e) => {
  const t = n.clients.get(e.client);
  return t[Zt(t, e.clock)];
}, eo = (
  /** @type {function(StructStore,ID):Item} */
  VN
), nh = (n, e, t) => {
  const r = Zt(e, t), i = e[r];
  return i.id.clock < t && i instanceof ie ? (e.splice(r + 1, 0, sc(n, i, t - i.id.clock)), r + 1) : r;
}, _t = (n, e) => {
  const t = (
    /** @type {Array<Item>} */
    n.doc.store.clients.get(e.client)
  );
  return t[nh(n, t, e.clock)];
}, S0 = (n, e, t) => {
  const r = e.clients.get(t.client), i = Zt(r, t.clock), o = r[i];
  return t.clock !== o.id.clock + o.length - 1 && o.constructor !== Vt && r.splice(i + 1, 0, sc(n, o, t.clock - o.id.clock + 1)), o;
}, UN = (n, e, t) => {
  const r = (
    /** @type {Array<GC|Item>} */
    n.clients.get(e.id.client)
  );
  r[Zt(r, e.id.clock)] = t;
}, a1 = (n, e, t, r, i) => {
  if (r === 0)
    return;
  const o = t + r;
  let s = nh(n, e, t), l;
  do
    l = e[s++], o < l.id.clock + l.length && nh(n, e, o), i(l);
  while (s < e.length && e[s].id.clock < o);
};
class qN {
  /**
   * @param {Doc} doc
   * @param {any} origin
   * @param {boolean} local
   */
  constructor(e, t, r) {
    this.doc = e, this.deleteSet = new _o(), this.beforeState = js(e.store), this.afterState = /* @__PURE__ */ new Map(), this.changed = /* @__PURE__ */ new Map(), this.changedParentTypes = /* @__PURE__ */ new Map(), this._mergeStructs = [], this.origin = t, this.meta = /* @__PURE__ */ new Map(), this.local = r, this.subdocsAdded = /* @__PURE__ */ new Set(), this.subdocsRemoved = /* @__PURE__ */ new Set(), this.subdocsLoaded = /* @__PURE__ */ new Set(), this._needFormattingCleanup = !1;
  }
}
const E0 = (n, e) => e.deleteSet.clients.size === 0 && !rF(e.afterState, (t, r) => e.beforeState.get(r) !== t) ? !1 : (Ef(e.deleteSet), TN(n, e), ko(n, e.deleteSet), !0), x0 = (n, e, t) => {
  const r = e._item;
  (r === null || r.id.clock < (n.beforeState.get(r.id.client) || 0) && !r.deleted) && Bn(n.changed, e, yi).add(t);
}, ra = (n, e) => {
  let t = n[e], r = n[e - 1], i = e;
  for (; i > 0; t = r, r = n[--i - 1]) {
    if (r.deleted === t.deleted && r.constructor === t.constructor && r.mergeWith(t)) {
      t instanceof ie && t.parentSub !== null && /** @type {AbstractType<any>} */
      t.parent._map.get(t.parentSub) === t && t.parent._map.set(
        t.parentSub,
        /** @type {Item} */
        r
      );
      continue;
    }
    break;
  }
  const o = e - i;
  return o && n.splice(e + 1 - o, o), o;
}, jN = (n, e, t) => {
  for (const [r, i] of n.clients.entries()) {
    const o = (
      /** @type {Array<GC|Item>} */
      e.clients.get(r)
    );
    for (let s = i.length - 1; s >= 0; s--) {
      const l = i[s], a = l.clock + l.len;
      for (let c = Zt(o, l.clock), d = o[c]; c < o.length && d.id.clock < a; d = o[++c]) {
        const u = o[c];
        if (l.clock + l.len <= u.id.clock)
          break;
        u instanceof ie && u.deleted && !u.keep && t(u) && u.gc(e, !1);
      }
    }
  }
}, WN = (n, e) => {
  n.clients.forEach((t, r) => {
    const i = (
      /** @type {Array<GC|Item>} */
      e.clients.get(r)
    );
    for (let o = t.length - 1; o >= 0; o--) {
      const s = t[o], l = nr(i.length - 1, 1 + Zt(i, s.clock + s.len - 1));
      for (let a = l, c = i[a]; a > 0 && c.id.clock >= s.clock; c = i[a])
        a -= 1 + ra(i, a);
    }
  });
}, c1 = (n, e) => {
  if (e < n.length) {
    const t = n[e], r = t.doc, i = r.store, o = t.deleteSet, s = t._mergeStructs;
    try {
      Ef(o), t.afterState = js(t.doc.store), r.emit("beforeObserverCalls", [t, r]);
      const l = [];
      t.changed.forEach(
        (a, c) => l.push(() => {
          (c._item === null || !c._item.deleted) && c._callObserver(t, a);
        })
      ), l.push(() => {
        t.changedParentTypes.forEach((a, c) => {
          c._dEH.l.length > 0 && (c._item === null || !c._item.deleted) && (a = a.filter(
            (d) => d.target._item === null || !d.target._item.deleted
          ), a.forEach((d) => {
            d.currentTarget = c, d._path = null;
          }), a.sort((d, u) => d.path.length - u.path.length), i1(c._dEH, a, t));
        });
      }), l.push(() => r.emit("afterTransaction", [t, r])), kf(l, []), t._needFormattingCleanup && f$(t);
    } finally {
      r.gc && jN(o, i, r.gcFilter), WN(o, i), t.afterState.forEach((d, u) => {
        const h = t.beforeState.get(u) || 0;
        if (h !== d) {
          const f = (
            /** @type {Array<GC|Item>} */
            i.clients.get(u)
          ), p = fn(Zt(f, h), 1);
          for (let m = f.length - 1; m >= p; )
            m -= 1 + ra(f, m);
        }
      });
      for (let d = s.length - 1; d >= 0; d--) {
        const { client: u, clock: h } = s[d].id, f = (
          /** @type {Array<GC|Item>} */
          i.clients.get(u)
        ), p = Zt(f, h);
        p + 1 < f.length && ra(f, p + 1) > 1 || p > 0 && ra(f, p);
      }
      if (!t.local && t.afterState.get(r.clientID) !== t.beforeState.get(r.clientID) && (vN(Cf, Vw, "[yjs] ", Uw, qw, "Changed the client-id because another client seems to be using it."), r.clientID = Xw()), r.emit("afterTransactionCleanup", [t, r]), r._observers.has("update")) {
        const d = new qs();
        E0(d, t) && r.emit("update", [d.toUint8Array(), t.origin, r, t]);
      }
      if (r._observers.has("updateV2")) {
        const d = new _i();
        E0(d, t) && r.emit("updateV2", [d.toUint8Array(), t.origin, r, t]);
      }
      const { subdocsAdded: l, subdocsLoaded: a, subdocsRemoved: c } = t;
      (l.size > 0 || c.size > 0 || a.size > 0) && (l.forEach((d) => {
        d.clientID = r.clientID, d.collectionid == null && (d.collectionid = r.collectionid), r.subdocs.add(d);
      }), c.forEach((d) => r.subdocs.delete(d)), r.emit("subdocs", [{ loaded: a, added: l, removed: c }, r, t]), c.forEach((d) => d.destroy())), n.length <= e + 1 ? (r._transactionCleanups = [], r.emit("afterAllTransactions", [r, n])) : c1(n, e + 1);
    }
  }
}, de = (n, e, t = null, r = !0) => {
  const i = n._transactionCleanups;
  let o = !1, s = null;
  n._transaction === null && (o = !0, n._transaction = new qN(n, t, r), i.push(n._transaction), i.length === 1 && n.emit("beforeAllTransactions", [n]), n.emit("beforeTransaction", [n._transaction, n]));
  try {
    s = e(n._transaction);
  } finally {
    if (o) {
      const l = n._transaction === i[0];
      n._transaction = null, l && c1(i, 0);
    }
  }
  return s;
};
class GN {
  /**
   * @param {DeleteSet} deletions
   * @param {DeleteSet} insertions
   */
  constructor(e, t) {
    this.insertions = t, this.deletions = e, this.meta = /* @__PURE__ */ new Map();
  }
}
const D0 = (n, e, t) => {
  Ir(n, t.deletions, (r) => {
    r instanceof ie && e.scope.some((i) => i === n.doc || Ds(
      /** @type {AbstractType<any>} */
      i,
      r
    )) && Lf(r, !1);
  });
}, A0 = (n, e, t) => {
  let r = null;
  const i = n.doc, o = n.scope;
  de(i, (l) => {
    for (; e.length > 0 && n.currStackItem === null; ) {
      const a = i.store, c = (
        /** @type {StackItem} */
        e.pop()
      ), d = /* @__PURE__ */ new Set(), u = [];
      let h = !1;
      Ir(l, c.insertions, (f) => {
        if (f instanceof ie) {
          if (f.redone !== null) {
            let { item: p, diff: m } = ih(a, f.id);
            m > 0 && (p = _t(l, j(p.id.client, p.id.clock + m))), f = p;
          }
          !f.deleted && o.some((p) => p === l.doc || Ds(
            /** @type {AbstractType<any>} */
            p,
            /** @type {Item} */
            f
          )) && u.push(f);
        }
      }), Ir(l, c.deletions, (f) => {
        f instanceof ie && o.some((p) => p === l.doc || Ds(
          /** @type {AbstractType<any>} */
          p,
          f
        )) && // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.
        !wo(c.insertions, f.id) && d.add(f);
      }), d.forEach((f) => {
        h = T1(l, f, d, c.insertions, n.ignoreRemoteMapChanges, n) !== null || h;
      });
      for (let f = u.length - 1; f >= 0; f--) {
        const p = u[f];
        n.deleteFilter(p) && (p.delete(l), h = !0);
      }
      n.currStackItem = h ? c : null;
    }
    l.changed.forEach((a, c) => {
      a.has(null) && c._searchMarker && (c._searchMarker.length = 0);
    }), r = l;
  }, n);
  const s = n.currStackItem;
  if (s != null) {
    const l = r.changedParentTypes;
    n.emit("stack-item-popped", [{ stackItem: s, type: t, changedParentTypes: l, origin: n }, n]), n.currStackItem = null;
  }
  return s;
};
class d1 extends Mw {
  /**
   * @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(e, {
    captureTimeout: t = 500,
    captureTransaction: r = (a) => !0,
    deleteFilter: i = () => !0,
    trackedOrigins: o = /* @__PURE__ */ new Set([null]),
    ignoreRemoteMapChanges: s = !1,
    doc: l = (
      /** @type {Doc} */
      Ju(e) ? e[0].doc : e instanceof Hr ? e : e.doc
    )
  } = {}) {
    super(), this.scope = [], this.doc = l, this.addToScope(e), this.deleteFilter = i, o.add(this), this.trackedOrigins = o, this.captureTransaction = r, this.undoStack = [], this.redoStack = [], this.undoing = !1, this.redoing = !1, this.currStackItem = null, this.lastChange = 0, this.ignoreRemoteMapChanges = s, this.captureTimeout = t, this.afterTransactionHandler = (a) => {
      if (!this.captureTransaction(a) || !this.scope.some((g) => a.changedParentTypes.has(
        /** @type {AbstractType<any>} */
        g
      ) || g === this.doc) || !this.trackedOrigins.has(a.origin) && (!a.origin || !this.trackedOrigins.has(a.origin.constructor)))
        return;
      const c = this.undoing, d = this.redoing, u = c ? this.redoStack : this.undoStack;
      c ? this.stopCapturing() : d || this.clear(!1, !0);
      const h = new _o();
      a.afterState.forEach((g, y) => {
        const _ = a.beforeState.get(y) || 0, b = g - _;
        b > 0 && Es(h, y, _, b);
      });
      const f = VF();
      let p = !1;
      if (this.lastChange > 0 && f - this.lastChange < this.captureTimeout && u.length > 0 && !c && !d) {
        const g = u[u.length - 1];
        g.deletions = eh([g.deletions, a.deleteSet]), g.insertions = eh([g.insertions, h]);
      } else
        u.push(new GN(a.deleteSet, h)), p = !0;
      !c && !d && (this.lastChange = f), Ir(
        a,
        a.deleteSet,
        /** @param {Item|GC} item */
        (g) => {
          g instanceof ie && this.scope.some((y) => y === a.doc || Ds(
            /** @type {AbstractType<any>} */
            y,
            g
          )) && Lf(g, !0);
        }
      );
      const m = [{ stackItem: u[u.length - 1], origin: a.origin, type: c ? "redo" : "undo", changedParentTypes: a.changedParentTypes }, this];
      p ? this.emit("stack-item-added", m) : this.emit("stack-item-updated", m);
    }, 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(e) {
    const t = new Set(this.scope);
    e = Ju(e) ? e : [e], e.forEach((r) => {
      t.has(r) || (t.add(r), (r instanceof ze ? r.doc !== this.doc : r !== this.doc) && Ww("[yjs#509] Not same Y.Doc"), this.scope.push(r));
    });
  }
  /**
   * @param {any} origin
   */
  addTrackedOrigin(e) {
    this.trackedOrigins.add(e);
  }
  /**
   * @param {any} origin
   */
  removeTrackedOrigin(e) {
    this.trackedOrigins.delete(e);
  }
  clear(e = !0, t = !0) {
    (e && this.canUndo() || t && this.canRedo()) && this.doc.transact((r) => {
      e && (this.undoStack.forEach((i) => D0(r, this, i)), this.undoStack = []), t && (this.redoStack.forEach((i) => D0(r, this, i)), this.redoStack = []), this.emit("stack-cleared", [{ undoStackCleared: e, redoStackCleared: t }]);
    });
  }
  /**
   * 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 = !0;
    let e;
    try {
      e = A0(this, this.undoStack, "undo");
    } finally {
      this.undoing = !1;
    }
    return e;
  }
  /**
   * Redo last undo operation.
   *
   * @return {StackItem?} Returns StackItem if a change was applied
   */
  redo() {
    this.redoing = !0;
    let e;
    try {
      e = A0(this, this.redoStack, "redo");
    } finally {
      this.redoing = !1;
    }
    return e;
  }
  /**
   * 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* KN(n) {
  const e = J(n.restDecoder);
  for (let t = 0; t < e; t++) {
    const r = J(n.restDecoder), i = n.readClient();
    let o = J(n.restDecoder);
    for (let s = 0; s < r; s++) {
      const l = n.readInfo();
      if (l === 10) {
        const a = J(n.restDecoder);
        yield new Ut(j(i, o), a), o += a;
      } else if (xc & l) {
        const a = (l & (rr | ct)) === 0, c = new ie(
          j(i, o),
          null,
          // left
          (l & ct) === ct ? n.readLeftID() : null,
          // origin
          null,
          // right
          (l & rr) === rr ? n.readRightID() : null,
          // right origin
          // @ts-ignore Force writing a string here.
          a ? n.readParentInfo() ? n.readString() : n.readLeftID() : null,
          // parent
          a && (l & vs) === vs ? n.readString() : null,
          // parentSub
          M1(n, l)
          // item content
        );
        yield c, o += c.length;
      } else {
        const a = n.readLen();
        yield new Vt(j(i, o), a), o += a;
      }
    }
  }
}
class Tf {
  /**
   * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder
   * @param {boolean} filterSkips
   */
  constructor(e, t) {
    this.gen = KN(e), this.curr = null, this.done = !1, this.filterSkips = t, 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 === Ut);
    return this.curr;
  }
}
class Mf {
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  constructor(e) {
    this.currClient = 0, this.startClock = 0, this.written = 0, this.encoder = e, this.clientStructs = [];
  }
}
const JN = (n) => tc(n, Qw, qs), YN = (n, e) => {
  if (n.constructor === Vt) {
    const { client: t, clock: r } = n.id;
    return new Vt(j(t, r + e), n.length - e);
  } else if (n.constructor === Ut) {
    const { client: t, clock: r } = n.id;
    return new Ut(j(t, r + e), n.length - e);
  } else {
    const t = (
      /** @type {Item} */
      n
    ), { client: r, clock: i } = t.id;
    return new ie(
      j(r, i + e),
      null,
      j(r, i + e - 1),
      null,
      t.rightOrigin,
      t.parent,
      t.parentSub,
      t.content.splice(e)
    );
  }
}, tc = (n, e = fo, t = _i) => {
  if (n.length === 1)
    return n[0];
  const r = n.map((d) => new e(yo(d)));
  let i = r.map((d) => new Tf(d, !0)), o = null;
  const s = new t(), l = new Mf(s);
  for (; i = i.filter((h) => h.curr !== null), i.sort(
    /** @type {function(any,any):number} */
    (h, f) => {
      if (h.curr.id.client === f.curr.id.client) {
        const p = h.curr.id.clock - f.curr.id.clock;
        return p === 0 ? h.curr.constructor === f.curr.constructor ? 0 : h.curr.constructor === Ut ? 1 : -1 : p;
      } else
        return f.curr.id.client - h.curr.id.client;
    }
  ), i.length !== 0; ) {
    const d = i[0], u = (
      /** @type {Item | GC} */
      d.curr.id.client
    );
    if (o !== null) {
      let h = (
        /** @type {Item | GC | null} */
        d.curr
      ), f = !1;
      for (; h !== null && h.id.clock + h.length <= o.struct.id.clock + o.struct.length && h.id.client >= o.struct.id.client; )
        h = d.next(), f = !0;
      if (h === null || // current decoder is empty
      h.id.client !== u || // check whether there is another decoder that has has updates from `firstClient`
      f && h.id.clock > o.struct.id.clock + o.struct.length)
        continue;
      if (u !== o.struct.id.client)
        vr(l, o.struct, o.offset), o = { struct: h, offset: 0 }, d.next();
      else if (o.struct.id.clock + o.struct.length < h.id.clock)
        if (o.struct.constructor === Ut)
          o.struct.length = h.id.clock + h.length - o.struct.id.clock;
        else {
          vr(l, o.struct, o.offset);
          const p = h.id.clock - o.struct.id.clock - o.struct.length;
          o = { struct: new Ut(j(u, o.struct.id.clock + o.struct.length), p), offset: 0 };
        }
      else {
        const p = o.struct.id.clock + o.struct.length - h.id.clock;
        p > 0 && (o.struct.constructor === Ut ? o.struct.length -= p : h = YN(h, p)), o.struct.mergeWith(
          /** @type {any} */
          h
        ) || (vr(l, o.struct, o.offset), o = { struct: h, offset: 0 }, d.next());
      }
    } else
      o = { struct: (
        /** @type {Item | GC} */
        d.curr
      ), offset: 0 }, d.next();
    for (let h = d.curr; h !== null && h.id.client === u && h.id.clock === o.struct.id.clock + o.struct.length && h.constructor !== Ut; h = d.next())
      vr(l, o.struct, o.offset), o = { struct: h, offset: 0 };
  }
  o !== null && (vr(l, o.struct, o.offset), o = null), Of(l);
  const a = r.map((d) => xf(d)), c = eh(a);
  return ko(s, c), s.toUint8Array();
}, XN = (n, e, t = fo, r = _i) => {
  const i = n1(e), o = new r(), s = new Mf(o), l = new t(yo(n)), a = new Tf(l, !1);
  for (; a.curr; ) {
    const d = a.curr, u = d.id.client, h = i.get(u) || 0;
    if (a.curr.constructor === Ut) {
      a.next();
      continue;
    }
    if (d.id.clock + d.length > h)
      for (vr(s, d, fn(h - d.id.clock, 0)), a.next(); a.curr && a.curr.id.client === u; )
        vr(s, a.curr, 0), a.next();
    else
      for (; a.curr && a.curr.id.client === u && a.curr.id.clock + a.curr.length <= h; )
        a.next();
  }
  Of(s);
  const c = xf(l);
  return ko(o, c), o.toUint8Array();
}, u1 = (n) => {
  n.written > 0 && (n.clientStructs.push({ written: n.written, restEncoder: cn(n.encoder.restEncoder) }), n.encoder.restEncoder = Us(), n.written = 0);
}, vr = (n, e, t) => {
  n.written > 0 && n.currClient !== e.id.client && u1(n), n.written === 0 && (n.currClient = e.id.client, n.encoder.writeClient(e.id.client), Z(n.encoder.restEncoder, e.id.clock + t)), e.write(n.encoder, t), n.written++;
}, Of = (n) => {
  u1(n);
  const e = n.encoder.restEncoder;
  Z(e, n.clientStructs.length);
  for (let t = 0; t < n.clientStructs.length; t++) {
    const r = n.clientStructs[t];
    Z(e, r.written), Dc(e, r.restEncoder);
  }
}, ZN = (n, e, t, r) => {
  const i = new t(yo(n)), o = new Tf(i, !1), s = new r(), l = new Mf(s);
  for (let c = o.curr; c !== null; c = o.next())
    vr(l, e(c), 0);
  Of(l);
  const a = xf(i);
  return ko(s, a), s.toUint8Array();
}, QN = (n) => ZN(n, ZF, fo, qs), T0 = "You must not compute changes after the event-handler fired.";
class Tc {
  /**
   * @param {T} target The changed type.
   * @param {Transaction} transaction
   */
  constructor(e, t) {
    this.target = e, this.currentTarget = e, this.transaction = t, 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 = e$(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(e) {
    return wo(this.transaction.deleteSet, e.id);
  }
  /**
   * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}
   */
  get keys() {
    if (this._keys === null) {
      if (this.transaction.doc._transactionCleanups.length === 0)
        throw $r(T0);
      const e = /* @__PURE__ */ new Map(), t = this.target;
      /** @type Set<string|null> */
      this.transaction.changed.get(t).forEach((i) => {
        if (i !== null) {
          const o = (
            /** @type {Item} */
            t._map.get(i)
          );
          let s, l;
          if (this.adds(o)) {
            let a = o.left;
            for (; a !== null && this.adds(a); )
              a = a.left;
            if (this.deletes(o))
              if (a !== null && this.deletes(a))
                s = "delete", l = Vd(a.content.getContent());
              else
                return;
            else
              a !== null && this.deletes(a) ? (s = "update", l = Vd(a.content.getContent())) : (s = "add", l = void 0);
          } else if (this.deletes(o))
            s = "delete", l = Vd(
              /** @type {Item} */
              o.content.getContent()
            );
          else
            return;
          e.set(i, { action: s, oldValue: l });
        }
      }), this._keys = e;
    }
    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(e) {
    return e.id.clock >= (this.transaction.beforeState.get(e.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 e = this._changes;
    if (e === null) {
      if (this.transaction.doc._transactionCleanups.length === 0)
        throw $r(T0);
      const t = this.target, r = yi(), i = yi(), o = [];
      if (e = {
        added: r,
        deleted: i,
        delta: o,
        keys: this.keys
      }, /** @type Set<string|null> */
      this.transaction.changed.get(t).has(null)) {
        let l = null;
        const a = () => {
          l && o.push(l);
        };
        for (let c = t._start; c !== null; c = c.right)
          c.deleted ? this.deletes(c) && !this.adds(c) && ((l === null || l.delete === void 0) && (a(), l = { delete: 0 }), l.delete += c.length, i.add(c)) : this.adds(c) ? ((l === null || l.insert === void 0) && (a(), l = { insert: [] }), l.insert = l.insert.concat(c.content.getContent()), r.add(c)) : ((l === null || l.retain === void 0) && (a(), l = { retain: 0 }), l.retain += c.length);
        l !== null && l.retain === void 0 && a();
      }
      this._changes = e;
    }
    return (
      /** @type {any} */
      e
    );
  }
}
const e$ = (n, e) => {
  const t = [];
  for (; e._item !== null && e !== n; ) {
    if (e._item.parentSub !== null)
      t.unshift(e._item.parentSub);
    else {
      let r = 0, i = (
        /** @type {AbstractType<any>} */
        e._item.parent._start
      );
      for (; i !== e._item && i !== null; )
        !i.deleted && i.countable && (r += i.length), i = i.right;
      t.unshift(r);
    }
    e = /** @type {AbstractType<any>} */
    e._item.parent;
  }
  return t;
}, it = () => {
  Ww("Invalid access: Add Yjs type to a document before reading data.");
}, h1 = 80;
let Ff = 0;
class t$ {
  /**
   * @param {Item} p
   * @param {number} index
   */
  constructor(e, t) {
    e.marker = !0, this.p = e, this.index = t, this.timestamp = Ff++;
  }
}
const n$ = (n) => {
  n.timestamp = Ff++;
}, f1 = (n, e, t) => {
  n.p.marker = !1, n.p = e, e.marker = !0, n.index = t, n.timestamp = Ff++;
}, r$ = (n, e, t) => {
  if (n.length >= h1) {
    const r = n.reduce((i, o) => i.timestamp < o.timestamp ? i : o);
    return f1(r, e, t), r;
  } else {
    const r = new t$(e, t);
    return n.push(r), r;
  }
}, Mc = (n, e) => {
  if (n._start === null || e === 0 || n._searchMarker === null)
    return null;
  const t = n._searchMarker.length === 0 ? null : n._searchMarker.reduce((o, s) => ea(e - o.index) < ea(e - s.index) ? o : s);
  let r = n._start, i = 0;
  for (t !== null && (r = t.p, i = t.index, n$(t)); r.right !== null && i < e; ) {
    if (!r.deleted && r.countable) {
      if (e < i + r.length)
        break;
      i += r.length;
    }
    r = r.right;
  }
  for (; r.left !== null && i > e; )
    r = r.left, !r.deleted && r.countable && (i -= r.length);
  for (; r.left !== null && r.left.id.client === r.id.client && r.left.id.clock + r.left.length === r.id.clock; )
    r = r.left, !r.deleted && r.countable && (i -= r.length);
  return t !== null && ea(t.index - i) < /** @type {YText|YArray<any>} */
  r.parent.length / h1 ? (f1(t, r, i), t) : r$(n._searchMarker, r, i);
}, Ts = (n, e, t) => {
  for (let r = n.length - 1; r >= 0; r--) {
    const i = n[r];
    if (t > 0) {
      let o = i.p;
      for (o.marker = !1; o && (o.deleted || !o.countable); )
        o = o.left, o && !o.deleted && o.countable && (i.index -= o.length);
      if (o === null || o.marker === !0) {
        n.splice(r, 1);
        continue;
      }
      i.p = o, o.marker = !0;
    }
    (e < i.index || t > 0 && e === i.index) && (i.index = fn(e, i.index + t));
  }
}, Oc = (n, e, t) => {
  const r = n, i = e.changedParentTypes;
  for (; Bn(i, n, () => []).push(t), n._item !== null; )
    n = /** @type {AbstractType<any>} */
    n._item.parent;
  i1(r._eH, t, e);
};
class ze {
  constructor() {
    this._item = null, this._map = /* @__PURE__ */ new Map(), this._start = null, this.doc = null, this._length = 0, this._eH = w0(), this._dEH = w0(), 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(e, t) {
    this.doc = e, this._item = t;
  }
  /**
   * @return {AbstractType<EventType>}
   */
  _copy() {
    throw un();
  }
  /**
   * 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 un();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder
   */
  _write(e) {
  }
  /**
   * The first non-deleted item
   */
  get _first() {
    let e = this._start;
    for (; e !== null && e.deleted; )
      e = e.right;
    return e;
  }
  /**
   * 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(e, t) {
    !e.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(e) {
    k0(this._eH, e);
  }
  /**
   * Observe all events that are created by this type and its children.
   *
   * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
   */
  observeDeep(e) {
    k0(this._dEH, e);
  }
  /**
   * Unregister an observer function.
   *
   * @param {function(EventType,Transaction):void} f Observer function
   */
  unobserve(e) {
    v0(this._eH, e);
  }
  /**
   * Unregister an observer function.
   *
   * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
   */
  unobserveDeep(e) {
    v0(this._dEH, e);
  }
  /**
   * @abstract
   * @return {any}
   */
  toJSON() {
  }
}
const p1 = (n, e, t) => {
  n.doc ?? it(), e < 0 && (e = n._length + e), t < 0 && (t = n._length + t);
  let r = t - e;
  const i = [];
  let o = n._start;
  for (; o !== null && r > 0; ) {
    if (o.countable && !o.deleted) {
      const s = o.content.getContent();
      if (s.length <= e)
        e -= s.length;
      else {
        for (let l = e; l < s.length && r > 0; l++)
          i.push(s[l]), r--;
        e = 0;
      }
    }
    o = o.right;
  }
  return i;
}, m1 = (n) => {
  n.doc ?? it();
  const e = [];
  let t = n._start;
  for (; t !== null; ) {
    if (t.countable && !t.deleted) {
      const r = t.content.getContent();
      for (let i = 0; i < r.length; i++)
        e.push(r[i]);
    }
    t = t.right;
  }
  return e;
}, g1 = (n, e) => {
  const t = [];
  let r = n._start;
  for (; r !== null; ) {
    if (r.countable && Jr(r, e)) {
      const i = r.content.getContent();
      for (let o = 0; o < i.length; o++)
        t.push(i[o]);
    }
    r = r.right;
  }
  return t;
}, Ms = (n, e) => {
  let t = 0, r = n._start;
  for (n.doc ?? it(); r !== null; ) {
    if (r.countable && !r.deleted) {
      const i = r.content.getContent();
      for (let o = 0; o < i.length; o++)
        e(i[o], t++, n);
    }
    r = r.right;
  }
}, b1 = (n, e) => {
  const t = [];
  return Ms(n, (r, i) => {
    t.push(e(r, i, n));
  }), t;
}, i$ = (n) => {
  let e = n._start, t = null, r = 0;
  return {
    [Symbol.iterator]() {
      return this;
    },
    next: () => {
      if (t === null) {
        for (; e !== null && e.deleted; )
          e = e.right;
        if (e === null)
          return {
            done: !0,
            value: void 0
          };
        t = e.content.getContent(), r = 0, e = e.right;
      }
      const i = t[r++];
      return t.length <= r && (t = null), {
        done: !1,
        value: i
      };
    }
  };
}, y1 = (n, e) => {
  n.doc ?? it();
  const t = Mc(n, e);
  let r = n._start;
  for (t !== null && (r = t.p, e -= t.index); r !== null; r = r.right)
    if (!r.deleted && r.countable) {
      if (e < r.length)
        return r.content.getContent()[e];
      e -= r.length;
    }
}, nc = (n, e, t, r) => {
  let i = t;
  const o = n.doc, s = o.clientID, l = o.store, a = t === null ? e._start : t.right;
  let c = [];
  const d = () => {
    c.length > 0 && (i = new ie(j(s, De(l, s)), i, i && i.lastId, a, a && a.id, e, null, new ki(c)), i.integrate(n, 0), c = []);
  };
  r.forEach((u) => {
    if (u === null)
      c.push(u);
    else
      switch (u.constructor) {
        case Number:
        case Object:
        case Boolean:
        case Array:
        case String:
          c.push(u);
          break;
        default:
          switch (d(), u.constructor) {
            case Uint8Array:
            case ArrayBuffer:
              i = new ie(j(s, De(l, s)), i, i && i.lastId, a, a && a.id, e, null, new Ws(new Uint8Array(
                /** @type {Uint8Array} */
                u
              ))), i.integrate(n, 0);
              break;
            case Hr:
              i = new ie(j(s, De(l, s)), i, i && i.lastId, a, a && a.id, e, null, new Gs(
                /** @type {Doc} */
                u
              )), i.integrate(n, 0);
              break;
            default:
              if (u instanceof ze)
                i = new ie(j(s, De(l, s)), i, i && i.lastId, a, a && a.id, e, null, new gn(u)), i.integrate(n, 0);
              else
                throw new Error("Unexpected content type in insert operation");
          }
      }
  }), d();
}, _1 = () => $r("Length exceeded!"), w1 = (n, e, t, r) => {
  if (t > e._length)
    throw _1();
  if (t === 0)
    return e._searchMarker && Ts(e._searchMarker, t, r.length), nc(n, e, null, r);
  const i = t, o = Mc(e, t);
  let s = e._start;
  for (o !== null && (s = o.p, t -= o.index, t === 0 && (s = s.prev, t += s && s.countable && !s.deleted ? s.length : 0)); s !== null; s = s.right)
    if (!s.deleted && s.countable) {
      if (t <= s.length) {
        t < s.length && _t(n, j(s.id.client, s.id.clock + t));
        break;
      }
      t -= s.length;
    }
  return e._searchMarker && Ts(e._searchMarker, i, r.length), nc(n, e, s, r);
}, o$ = (n, e, t) => {
  let i = (e._searchMarker || []).reduce((o, s) => s.index > o.index ? s : o, { index: 0, p: e._start }).p;
  if (i)
    for (; i.right; )
      i = i.right;
  return nc(n, e, i, t);
}, k1 = (n, e, t, r) => {
  if (r === 0)
    return;
  const i = t, o = r, s = Mc(e, t);
  let l = e._start;
  for (s !== null && (l = s.p, t -= s.index); l !== null && t > 0; l = l.right)
    !l.deleted && l.countable && (t < l.length && _t(n, j(l.id.client, l.id.clock + t)), t -= l.length);
  for (; r > 0 && l !== null; )
    l.deleted || (r < l.length && _t(n, j(l.id.client, l.id.clock + r)), l.delete(n), r -= l.length), l = l.right;
  if (r > 0)
    throw _1();
  e._searchMarker && Ts(
    e._searchMarker,
    i,
    -o + r
    /* in case we remove the above exception */
  );
}, rc = (n, e, t) => {
  const r = e._map.get(t);
  r !== void 0 && r.delete(n);
}, Nf = (n, e, t, r) => {
  const i = e._map.get(t) || null, o = n.doc, s = o.clientID;
  let l;
  if (r == null)
    l = new ki([r]);
  else
    switch (r.constructor) {
      case Number:
      case Object:
      case Boolean:
      case Array:
      case String:
      case Date:
      case BigInt:
        l = new ki([r]);
        break;
      case Uint8Array:
        l = new Ws(
          /** @type {Uint8Array} */
          r
        );
        break;
      case Hr:
        l = new Gs(
          /** @type {Doc} */
          r
        );
        break;
      default:
        if (r instanceof ze)
          l = new gn(r);
        else
          throw new Error("Unexpected content type");
    }
  new ie(j(s, De(o.store, s)), i, i && i.lastId, null, null, e, t, l).integrate(n, 0);
}, $f = (n, e) => {
  n.doc ?? it();
  const t = n._map.get(e);
  return t !== void 0 && !t.deleted ? t.content.getContent()[t.length - 1] : void 0;
}, v1 = (n) => {
  const e = {};
  return n.doc ?? it(), n._map.forEach((t, r) => {
    t.deleted || (e[r] = t.content.getContent()[t.length - 1]);
  }), e;
}, C1 = (n, e) => {
  n.doc ?? it();
  const t = n._map.get(e);
  return t !== void 0 && !t.deleted;
}, s$ = (n, e) => {
  const t = {};
  return n._map.forEach((r, i) => {
    let o = r;
    for (; o !== null && (!e.sv.has(o.id.client) || o.id.clock >= (e.sv.get(o.id.client) || 0)); )
      o = o.left;
    o !== null && Jr(o, e) && (t[i] = o.content.getContent()[o.length - 1]);
  }), t;
}, $l = (n) => (n.doc ?? it(), CN(
  n._map.entries(),
  /** @param {any} entry */
  (e) => !e[1].deleted
));
class l$ extends Tc {
}
class to extends ze {
  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(e) {
    const t = new to();
    return t.push(e), t;
  }
  /**
   * 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(e, t) {
    super._integrate(e, t), this.insert(
      0,
      /** @type {Array<any>} */
      this._prelimContent
    ), this._prelimContent = null;
  }
  /**
   * @return {YArray<T>}
   */
  _copy() {
    return new to();
  }
  /**
   * 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 e = new to();
    return e.insert(0, this.toArray().map(
      (t) => t instanceof ze ? (
        /** @type {typeof el} */
        t.clone()
      ) : t
    )), e;
  }
  get length() {
    return this.doc ?? it(), 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(e, t) {
    super._callObserver(e, t), Oc(this, e, new l$(this, e));
  }
  /**
   * 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(e, t) {
    this.doc !== null ? de(this.doc, (r) => {
      w1(
        r,
        this,
        e,
        /** @type {any} */
        t
      );
    }) : this._prelimContent.splice(e, 0, ...t);
  }
  /**
   * Appends content to this YArray.
   *
   * @param {Array<T>} content Array of content to append.
   *
   * @todo Use the following implementation in all types.
   */
  push(e) {
    this.doc !== null ? de(this.doc, (t) => {
      o$(
        t,
        this,
        /** @type {any} */
        e
      );
    }) : this._prelimContent.push(...e);
  }
  /**
   * Prepends content to this YArray.
   *
   * @param {Array<T>} content Array of content to prepend.
   */
  unshift(e) {
    this.insert(0, e);
  }
  /**
   * 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(e, t = 1) {
    this.doc !== null ? de(this.doc, (r) => {
      k1(r, this, e, t);
    }) : this._prelimContent.splice(e, t);
  }
  /**
   * Returns the i-th element from a YArray.
   *
   * @param {number} index The index of the element to return from the YArray
   * @return {T}
   */
  get(e) {
    return y1(this, e);
  }
  /**
   * Transforms this YArray to a JavaScript Array.
   *
   * @return {Array<T>}
   */
  toArray() {
    return m1(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(e = 0, t = this.length) {
    return p1(this, e, t);
  }
  /**
   * Transforms this Shared Type to a JSON object.
   *
   * @return {Array<any>}
   */
  toJSON() {
    return this.map((e) => e instanceof ze ? e.toJSON() : e);
  }
  /**
   * 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(e) {
    return b1(
      this,
      /** @type {any} */
      e
    );
  }
  /**
   * 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(e) {
    Ms(this, e);
  }
  /**
   * @return {IterableIterator<T>}
   */
  [Symbol.iterator]() {
    return i$(this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(e) {
    e.writeTypeRef(F$);
  }
}
const a$ = (n) => new to();
class c$ extends Tc {
  /**
   * @param {YMap<T>} ymap The YArray that changed.
   * @param {Transaction} transaction
   * @param {Set<any>} subs The keys that changed.
   */
  constructor(e, t, r) {
    super(e, t), this.keysChanged = r;
  }
}
class po extends ze {
  /**
   *
   * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap
   */
  constructor(e) {
    super(), this._prelimContent = null, e === void 0 ? this._prelimContent = /* @__PURE__ */ new Map() : this._prelimContent = new Map(e);
  }
  /**
   * 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(e, t) {
    super._integrate(e, t), this._prelimContent.forEach((r, i) => {
      this.set(i, r);
    }), this._prelimContent = null;
  }
  /**
   * @return {YMap<MapType>}
   */
  _copy() {
    return new po();
  }
  /**
   * 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 e = new po();
    return this.forEach((t, r) => {
      e.set(r, t instanceof ze ? (
        /** @type {typeof value} */
        t.clone()
      ) : t);
    }), e;
  }
  /**
   * Creates YMapEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(e, t) {
    Oc(this, e, new c$(this, e, t));
  }
  /**
   * Transforms this Shared Type to a JSON object.
   *
   * @return {Object<string,any>}
   */
  toJSON() {
    this.doc ?? it();
    const e = {};
    return this._map.forEach((t, r) => {
      if (!t.deleted) {
        const i = t.content.getContent()[t.length - 1];
        e[r] = i instanceof ze ? i.toJSON() : i;
      }
    }), e;
  }
  /**
   * Returns the size of the YMap (count of key/value pairs)
   *
   * @return {number}
   */
  get size() {
    return [...$l(this)].length;
  }
  /**
   * Returns the keys for each element in the YMap Type.
   *
   * @return {IterableIterator<string>}
   */
  keys() {
    return Gd(
      $l(this),
      /** @param {any} v */
      (e) => e[0]
    );
  }
  /**
   * Returns the values for each element in the YMap Type.
   *
   * @return {IterableIterator<MapType>}
   */
  values() {
    return Gd(
      $l(this),
      /** @param {any} v */
      (e) => e[1].content.getContent()[e[1].length - 1]
    );
  }
  /**
   * Returns an Iterator of [key, value] pairs
   *
   * @return {IterableIterator<[string, MapType]>}
   */
  entries() {
    return Gd(
      $l(this),
      /** @param {any} v */
      (e) => (
        /** @type {any} */
        [e[0], e[1].content.getContent()[e[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(e) {
    this.doc ?? it(), this._map.forEach((t, r) => {
      t.deleted || e(t.content.getContent()[t.length - 1], r, 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(e) {
    this.doc !== null ? de(this.doc, (t) => {
      rc(t, this, e);
    }) : this._prelimContent.delete(e);
  }
  /**
   * 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(e, t) {
    return this.doc !== null ? de(this.doc, (r) => {
      Nf(
        r,
        this,
        e,
        /** @type {any} */
        t
      );
    }) : this._prelimContent.set(e, t), t;
  }
  /**
   * Returns a specified element from this YMap.
   *
   * @param {string} key
   * @return {MapType|undefined}
   */
  get(e) {
    return (
      /** @type {any} */
      $f(this, e)
    );
  }
  /**
   * Returns a boolean indicating whether the specified key exists or not.
   *
   * @param {string} key The key to test.
   * @return {boolean}
   */
  has(e) {
    return C1(this, e);
  }
  /**
   * Removes all elements from this YMap.
   */
  clear() {
    this.doc !== null ? de(this.doc, (e) => {
      this.forEach(function(t, r, i) {
        rc(e, i, r);
      });
    }) : this._prelimContent.clear();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(e) {
    e.writeTypeRef(N$);
  }
}
const d$ = (n) => new po(), Dr = (n, e) => n === e || typeof n == "object" && typeof e == "object" && n && e && YF(n, e);
class rh {
  /**
   * @param {Item|null} left
   * @param {Item|null} right
   * @param {number} index
   * @param {Map<string,any>} currentAttributes
   */
  constructor(e, t, r, i) {
    this.left = e, this.right = t, this.index = r, this.currentAttributes = i;
  }
  /**
   * Only call this if you know that this.right is defined
   */
  forward() {
    switch (this.right === null && Ot(), this.right.content.constructor) {
      case Ne:
        this.right.deleted || vo(
          this.currentAttributes,
          /** @type {ContentFormat} */
          this.right.content
        );
        break;
      default:
        this.right.deleted || (this.index += this.right.length);
        break;
    }
    this.left = this.right, this.right = this.right.right;
  }
}
const M0 = (n, e, t) => {
  for (; e.right !== null && t > 0; ) {
    switch (e.right.content.constructor) {
      case Ne:
        e.right.deleted || vo(
          e.currentAttributes,
          /** @type {ContentFormat} */
          e.right.content
        );
        break;
      default:
        e.right.deleted || (t < e.right.length && _t(n, j(e.right.id.client, e.right.id.clock + t)), e.index += e.right.length, t -= e.right.length);
        break;
    }
    e.left = e.right, e.right = e.right.right;
  }
  return e;
}, Il = (n, e, t, r) => {
  const i = /* @__PURE__ */ new Map(), o = r ? Mc(e, t) : null;
  if (o) {
    const s = new rh(o.p.left, o.p, o.index, i);
    return M0(n, s, t - o.index);
  } else {
    const s = new rh(null, e._start, 0, i);
    return M0(n, s, t);
  }
}, S1 = (n, e, t, r) => {
  for (; t.right !== null && (t.right.deleted === !0 || t.right.content.constructor === Ne && Dr(
    r.get(
      /** @type {ContentFormat} */
      t.right.content.key
    ),
    /** @type {ContentFormat} */
    t.right.content.value
  )); )
    t.right.deleted || r.delete(
      /** @type {ContentFormat} */
      t.right.content.key
    ), t.forward();
  const i = n.doc, o = i.clientID;
  r.forEach((s, l) => {
    const a = t.left, c = t.right, d = new ie(j(o, De(i.store, o)), a, a && a.lastId, c, c && c.id, e, null, new Ne(l, s));
    d.integrate(n, 0), t.right = d, t.forward();
  });
}, vo = (n, e) => {
  const { key: t, value: r } = e;
  r === null ? n.delete(t) : n.set(t, r);
}, E1 = (n, e) => {
  for (; n.right !== null; ) {
    if (!(n.right.deleted || n.right.content.constructor === Ne && Dr(
      e[
        /** @type {ContentFormat} */
        n.right.content.key
      ] ?? null,
      /** @type {ContentFormat} */
      n.right.content.value
    ))) break;
    n.forward();
  }
}, x1 = (n, e, t, r) => {
  const i = n.doc, o = i.clientID, s = /* @__PURE__ */ new Map();
  for (const l in r) {
    const a = r[l], c = t.currentAttributes.get(l) ?? null;
    if (!Dr(c, a)) {
      s.set(l, c);
      const { left: d, right: u } = t;
      t.right = new ie(j(o, De(i.store, o)), d, d && d.lastId, u, u && u.id, e, null, new Ne(l, a)), t.right.integrate(n, 0), t.forward();
    }
  }
  return s;
}, Yd = (n, e, t, r, i) => {
  t.currentAttributes.forEach((h, f) => {
    i[f] === void 0 && (i[f] = null);
  });
  const o = n.doc, s = o.clientID;
  E1(t, i);
  const l = x1(n, e, t, i), a = r.constructor === String ? new pn(
    /** @type {string} */
    r
  ) : r instanceof ze ? new gn(r) : new xi(r);
  let { left: c, right: d, index: u } = t;
  e._searchMarker && Ts(e._searchMarker, t.index, a.getLength()), d = new ie(j(s, De(o.store, s)), c, c && c.lastId, d, d && d.id, e, null, a), d.integrate(n, 0), t.right = d, t.index = u, t.forward(), S1(n, e, t, l);
}, O0 = (n, e, t, r, i) => {
  const o = n.doc, s = o.clientID;
  E1(t, i);
  const l = x1(n, e, t, i);
  e: for (; t.right !== null && (r > 0 || l.size > 0 && (t.right.deleted || t.right.content.constructor === Ne)); ) {
    if (!t.right.deleted)
      switch (t.right.content.constructor) {
        case Ne: {
          const { key: a, value: c } = (
            /** @type {ContentFormat} */
            t.right.content
          ), d = i[a];
          if (d !== void 0) {
            if (Dr(d, c))
              l.delete(a);
            else {
              if (r === 0)
                break e;
              l.set(a, c);
            }
            t.right.delete(n);
          } else
            t.currentAttributes.set(a, c);
          break;
        }
        default:
          r < t.right.length && _t(n, j(t.right.id.client, t.right.id.clock + r)), r -= t.right.length;
          break;
      }
    t.forward();
  }
  if (r > 0) {
    let a = "";
    for (; r > 0; r--)
      a += `
`;
    t.right = new ie(j(s, De(o.store, s)), t.left, t.left && t.left.lastId, t.right, t.right && t.right.id, e, null, new pn(a)), t.right.integrate(n, 0), t.forward();
  }
  S1(n, e, t, l);
}, D1 = (n, e, t, r, i) => {
  let o = e;
  const s = Kt();
  for (; o && (!o.countable || o.deleted); ) {
    if (!o.deleted && o.content.constructor === Ne) {
      const c = (
        /** @type {ContentFormat} */
        o.content
      );
      s.set(c.key, c);
    }
    o = o.right;
  }
  let l = 0, a = !1;
  for (; e !== o; ) {
    if (t === e && (a = !0), !e.deleted) {
      const c = e.content;
      switch (c.constructor) {
        case Ne: {
          const { key: d, value: u } = (
            /** @type {ContentFormat} */
            c
          ), h = r.get(d) ?? null;
          (s.get(d) !== c || h === u) && (e.delete(n), l++, !a && (i.get(d) ?? null) === u && h !== u && (h === null ? i.delete(d) : i.set(d, h))), !a && !e.deleted && vo(
            i,
            /** @type {ContentFormat} */
            c
          );
          break;
        }
      }
    }
    e = /** @type {Item} */
    e.right;
  }
  return l;
}, u$ = (n, e) => {
  for (; e && e.right && (e.right.deleted || !e.right.countable); )
    e = e.right;
  const t = /* @__PURE__ */ new Set();
  for (; e && (e.deleted || !e.countable); ) {
    if (!e.deleted && e.content.constructor === Ne) {
      const r = (
        /** @type {ContentFormat} */
        e.content.key
      );
      t.has(r) ? e.delete(n) : t.add(r);
    }
    e = e.left;
  }
}, h$ = (n) => {
  let e = 0;
  return de(
    /** @type {Doc} */
    n.doc,
    (t) => {
      let r = (
        /** @type {Item} */
        n._start
      ), i = n._start, o = Kt();
      const s = Ku(o);
      for (; i; ) {
        if (i.deleted === !1)
          switch (i.content.constructor) {
            case Ne:
              vo(
                s,
                /** @type {ContentFormat} */
                i.content
              );
              break;
            default:
              e += D1(t, r, i, o, s), o = Ku(s), r = i;
              break;
          }
        i = i.right;
      }
    }
  ), e;
}, f$ = (n) => {
  const e = /* @__PURE__ */ new Set(), t = n.doc;
  for (const [r, i] of n.afterState.entries()) {
    const o = n.beforeState.get(r) || 0;
    i !== o && a1(
      n,
      /** @type {Array<Item|GC>} */
      t.store.clients.get(r),
      o,
      i,
      (s) => {
        !s.deleted && /** @type {Item} */
        s.content.constructor === Ne && s.constructor !== Vt && e.add(
          /** @type {any} */
          s.parent
        );
      }
    );
  }
  de(t, (r) => {
    Ir(n, n.deleteSet, (i) => {
      if (i instanceof Vt || !/** @type {YText} */
      i.parent._hasFormatting || e.has(
        /** @type {YText} */
        i.parent
      ))
        return;
      const o = (
        /** @type {YText} */
        i.parent
      );
      i.content.constructor === Ne ? e.add(o) : u$(r, i);
    });
    for (const i of e)
      h$(i);
  });
}, F0 = (n, e, t) => {
  const r = t, i = Ku(e.currentAttributes), o = e.right;
  for (; t > 0 && e.right !== null; ) {
    if (e.right.deleted === !1)
      switch (e.right.content.constructor) {
        case gn:
        case xi:
        case pn:
          t < e.right.length && _t(n, j(e.right.id.client, e.right.id.clock + t)), t -= e.right.length, e.right.delete(n);
          break;
      }
    e.forward();
  }
  o && D1(n, o, e.right, i, e.currentAttributes);
  const s = (
    /** @type {AbstractType<any>} */
    /** @type {Item} */
    (e.left || e.right).parent
  );
  return s._searchMarker && Ts(s._searchMarker, e.index, -r + t), e;
};
class p$ extends Tc {
  /**
   * @param {YText} ytext
   * @param {Transaction} transaction
   * @param {Set<any>} subs The keys that changed
   */
  constructor(e, t, r) {
    super(e, t), this.childListChanged = !1, this.keysChanged = /* @__PURE__ */ new Set(), r.forEach((i) => {
      i === null ? this.childListChanged = !0 : this.keysChanged.add(i);
    });
  }
  /**
   * @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 e = {
        keys: this.keys,
        delta: this.delta,
        added: /* @__PURE__ */ new Set(),
        deleted: /* @__PURE__ */ new Set()
      };
      this._changes = e;
    }
    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 e = (
        /** @type {Doc} */
        this.target.doc
      ), t = [];
      de(e, (r) => {
        const i = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map();
        let s = this.target._start, l = null;
        const a = {};
        let c = "", d = 0, u = 0;
        const h = () => {
          if (l !== null) {
            let f = null;
            switch (l) {
              case "delete":
                u > 0 && (f = { delete: u }), u = 0;
                break;
              case "insert":
                (typeof c == "object" || c.length > 0) && (f = { insert: c }, i.size > 0 && (f.attributes = {}, i.forEach((p, m) => {
                  p !== null && (f.attributes[m] = p);
                }))), c = "";
                break;
              case "retain":
                d > 0 && (f = { retain: d }, KF(a) || (f.attributes = WF({}, a))), d = 0;
                break;
            }
            f && t.push(f), l = null;
          }
        };
        for (; s !== null; ) {
          switch (s.content.constructor) {
            case gn:
            case xi:
              this.adds(s) ? this.deletes(s) || (h(), l = "insert", c = s.content.getContent()[0], h()) : this.deletes(s) ? (l !== "delete" && (h(), l = "delete"), u += 1) : s.deleted || (l !== "retain" && (h(), l = "retain"), d += 1);
              break;
            case pn:
              this.adds(s) ? this.deletes(s) || (l !== "insert" && (h(), l = "insert"), c += /** @type {ContentString} */
              s.content.str) : this.deletes(s) ? (l !== "delete" && (h(), l = "delete"), u += s.length) : s.deleted || (l !== "retain" && (h(), l = "retain"), d += s.length);
              break;
            case Ne: {
              const { key: f, value: p } = (
                /** @type {ContentFormat} */
                s.content
              );
              if (this.adds(s)) {
                if (!this.deletes(s)) {
                  const m = i.get(f) ?? null;
                  Dr(m, p) ? p !== null && s.delete(r) : (l === "retain" && h(), Dr(p, o.get(f) ?? null) ? delete a[f] : a[f] = p);
                }
              } else if (this.deletes(s)) {
                o.set(f, p);
                const m = i.get(f) ?? null;
                Dr(m, p) || (l === "retain" && h(), a[f] = m);
              } else if (!s.deleted) {
                o.set(f, p);
                const m = a[f];
                m !== void 0 && (Dr(m, p) ? m !== null && s.delete(r) : (l === "retain" && h(), p === null ? delete a[f] : a[f] = p));
              }
              s.deleted || (l === "insert" && h(), vo(
                i,
                /** @type {ContentFormat} */
                s.content
              ));
              break;
            }
          }
          s = s.right;
        }
        for (h(); t.length > 0; ) {
          const f = t[t.length - 1];
          if (f.retain !== void 0 && f.attributes === void 0)
            t.pop();
          else
            break;
        }
      }), this._delta = t;
    }
    return (
      /** @type {any} */
      this._delta
    );
  }
}
class Lr extends ze {
  /**
   * @param {String} [string] The initial value of the YText.
   */
  constructor(e) {
    super(), this._pending = e !== void 0 ? [() => this.insert(0, e)] : [], this._searchMarker = [], this._hasFormatting = !1;
  }
  /**
   * Number of characters of this text type.
   *
   * @type {number}
   */
  get length() {
    return this.doc ?? it(), this._length;
  }
  /**
   * @param {Doc} y
   * @param {Item} item
   */
  _integrate(e, t) {
    super._integrate(e, t);
    try {
      this._pending.forEach((r) => r());
    } catch (r) {
      console.error(r);
    }
    this._pending = null;
  }
  _copy() {
    return new Lr();
  }
  /**
   * 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 e = new Lr();
    return e.applyDelta(this.toDelta()), e;
  }
  /**
   * Creates YTextEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(e, t) {
    super._callObserver(e, t);
    const r = new p$(this, e, t);
    Oc(this, e, r), !e.local && this._hasFormatting && (e._needFormattingCleanup = !0);
  }
  /**
   * Returns the unformatted string representation of this YText type.
   *
   * @public
   */
  toString() {
    this.doc ?? it();
    let e = "", t = this._start;
    for (; t !== null; )
      !t.deleted && t.countable && t.content.constructor === pn && (e += /** @type {ContentString} */
      t.content.str), t = t.right;
    return e;
  }
  /**
   * 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(e, { sanitize: t = !0 } = {}) {
    this.doc !== null ? de(this.doc, (r) => {
      const i = new rh(null, this._start, 0, /* @__PURE__ */ new Map());
      for (let o = 0; o < e.length; o++) {
        const s = e[o];
        if (s.insert !== void 0) {
          const l = !t && typeof s.insert == "string" && o === e.length - 1 && i.right === null && s.insert.slice(-1) === `
` ? s.insert.slice(0, -1) : s.insert;
          (typeof l != "string" || l.length > 0) && Yd(r, this, i, l, s.attributes || {});
        } else s.retain !== void 0 ? O0(r, this, i, s.retain, s.attributes || {}) : s.delete !== void 0 && F0(r, i, s.delete);
      }
    }) : this._pending.push(() => this.applyDelta(e));
  }
  /**
   * 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(e, t, r) {
    this.doc ?? it();
    const i = [], o = /* @__PURE__ */ new Map(), s = (
      /** @type {Doc} */
      this.doc
    );
    let l = "", a = this._start;
    function c() {
      if (l.length > 0) {
        const u = {};
        let h = !1;
        o.forEach((p, m) => {
          h = !0, u[m] = p;
        });
        const f = { insert: l };
        h && (f.attributes = u), i.push(f), l = "";
      }
    }
    const d = () => {
      for (; a !== null; ) {
        if (Jr(a, e) || t !== void 0 && Jr(a, t))
          switch (a.content.constructor) {
            case pn: {
              const u = o.get("ychange");
              e !== void 0 && !Jr(a, e) ? (u === void 0 || u.user !== a.id.client || u.type !== "removed") && (c(), o.set("ychange", r ? r("removed", a.id) : { type: "removed" })) : t !== void 0 && !Jr(a, t) ? (u === void 0 || u.user !== a.id.client || u.type !== "added") && (c(), o.set("ychange", r ? r("added", a.id) : { type: "added" })) : u !== void 0 && (c(), o.delete("ychange")), l += /** @type {ContentString} */
              a.content.str;
              break;
            }
            case gn:
            case xi: {
              c();
              const u = {
                insert: a.content.getContent()[0]
              };
              if (o.size > 0) {
                const h = (
                  /** @type {Object<string,any>} */
                  {}
                );
                u.attributes = h, o.forEach((f, p) => {
                  h[p] = f;
                });
              }
              i.push(u);
              break;
            }
            case Ne:
              Jr(a, e) && (c(), vo(
                o,
                /** @type {ContentFormat} */
                a.content
              ));
              break;
          }
        a = a.right;
      }
      c();
    };
    return e || t ? de(s, (u) => {
      e && th(u, e), t && th(u, t), d();
    }, "cleanup") : d(), i;
  }
  /**
   * 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(e, t, r) {
    if (t.length <= 0)
      return;
    const i = this.doc;
    i !== null ? de(i, (o) => {
      const s = Il(o, this, e, !r);
      r || (r = {}, s.currentAttributes.forEach((l, a) => {
        r[a] = l;
      })), Yd(o, this, s, t, r);
    }) : this._pending.push(() => this.insert(e, t, r));
  }
  /**
   * 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(e, t, r) {
    const i = this.doc;
    i !== null ? de(i, (o) => {
      const s = Il(o, this, e, !r);
      Yd(o, this, s, t, r || {});
    }) : this._pending.push(() => this.insertEmbed(e, t, r || {}));
  }
  /**
   * 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(e, t) {
    if (t === 0)
      return;
    const r = this.doc;
    r !== null ? de(r, (i) => {
      F0(i, Il(i, this, e, !0), t);
    }) : this._pending.push(() => this.delete(e, t));
  }
  /**
   * 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(e, t, r) {
    if (t === 0)
      return;
    const i = this.doc;
    i !== null ? de(i, (o) => {
      const s = Il(o, this, e, !1);
      s.right !== null && O0(o, this, s, t, r);
    }) : this._pending.push(() => this.format(e, t, r));
  }
  /**
   * 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(e) {
    this.doc !== null ? de(this.doc, (t) => {
      rc(t, this, e);
    }) : this._pending.push(() => this.removeAttribute(e));
  }
  /**
   * 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(e, t) {
    this.doc !== null ? de(this.doc, (r) => {
      Nf(r, this, e, t);
    }) : this._pending.push(() => this.setAttribute(e, t));
  }
  /**
   * 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(e) {
    return (
      /** @type {any} */
      $f(this, e)
    );
  }
  /**
   * 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 v1(this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(e) {
    e.writeTypeRef($$);
  }
}
const m$ = (n) => new Lr();
class Xd {
  /**
   * @param {YXmlFragment | YXmlElement} root
   * @param {function(AbstractType<any>):boolean} [f]
   */
  constructor(e, t = () => !0) {
    this._filter = t, this._root = e, this._currentNode = /** @type {Item} */
    e._start, this._firstCall = !0, e.doc ?? it();
  }
  [Symbol.iterator]() {
    return this;
  }
  /**
   * Get the next node.
   *
   * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node.
   *
   * @public
   */
  next() {
    let e = this._currentNode, t = e && e.content && /** @type {any} */
    e.content.type;
    if (e !== null && (!this._firstCall || e.deleted || !this._filter(t)))
      do
        if (t = /** @type {any} */
        e.content.type, !e.deleted && (t.constructor === at || t.constructor === wi) && t._start !== null)
          e = t._start;
        else
          for (; e !== null; ) {
            const r = e.next;
            if (r !== null) {
              e = r;
              break;
            } else e.parent === this._root ? e = null : e = /** @type {AbstractType<any>} */
            e.parent._item;
          }
      while (e !== null && (e.deleted || !this._filter(
        /** @type {ContentType} */
        e.content.type
      )));
    return this._firstCall = !1, e === null ? { value: void 0, done: !0 } : (this._currentNode = e, { value: (
      /** @type {any} */
      e.content.type
    ), done: !1 });
  }
}
class wi extends ze {
  constructor() {
    super(), this._prelimContent = [];
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get firstChild() {
    const e = this._first;
    return e ? e.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(e, t) {
    super._integrate(e, t), this.insert(
      0,
      /** @type {Array<any>} */
      this._prelimContent
    ), this._prelimContent = null;
  }
  _copy() {
    return new wi();
  }
  /**
   * 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 e = new wi();
    return e.insert(0, this.toArray().map((t) => t instanceof ze ? t.clone() : t)), e;
  }
  get length() {
    return this.doc ?? it(), 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(e) {
    return new Xd(this, e);
  }
  /**
   * 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(e) {
    e = e.toUpperCase();
    const r = new Xd(this, (i) => i.nodeName && i.nodeName.toUpperCase() === e).next();
    return r.done ? null : r.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(e) {
    return e = e.toUpperCase(), Nr(new Xd(this, (t) => t.nodeName && t.nodeName.toUpperCase() === e));
  }
  /**
   * Creates YXmlEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(e, t) {
    Oc(this, e, new y$(this, t, e));
  }
  /**
   * Get the string representation of all the children of this YXmlFragment.
   *
   * @return {string} The string representation of all children.
   */
  toString() {
    return b1(this, (e) => e.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(e = document, t = {}, r) {
    const i = e.createDocumentFragment();
    return r !== void 0 && r._createAssociation(i, this), Ms(this, (o) => {
      i.insertBefore(o.toDOM(e, t, r), null);
    }), i;
  }
  /**
   * 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(e, t) {
    this.doc !== null ? de(this.doc, (r) => {
      w1(r, this, e, t);
    }) : this._prelimContent.splice(e, 0, ...t);
  }
  /**
   * 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(e, t) {
    if (this.doc !== null)
      de(this.doc, (r) => {
        const i = e && e instanceof ze ? e._item : e;
        nc(r, this, i, t);
      });
    else {
      const r = (
        /** @type {Array<any>} */
        this._prelimContent
      ), i = e === null ? 0 : r.findIndex((o) => o === e) + 1;
      if (i === 0 && e !== null)
        throw $r("Reference item not found");
      r.splice(i, 0, ...t);
    }
  }
  /**
   * 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(e, t = 1) {
    this.doc !== null ? de(this.doc, (r) => {
      k1(r, this, e, t);
    }) : this._prelimContent.splice(e, t);
  }
  /**
   * Transforms this YArray to a JavaScript Array.
   *
   * @return {Array<YXmlElement|YXmlText|YXmlHook>}
   */
  toArray() {
    return m1(this);
  }
  /**
   * Appends content to this YArray.
   *
   * @param {Array<YXmlElement|YXmlText>} content Array of content to append.
   */
  push(e) {
    this.insert(this.length, e);
  }
  /**
   * Prepends content to this YArray.
   *
   * @param {Array<YXmlElement|YXmlText>} content Array of content to prepend.
   */
  unshift(e) {
    this.insert(0, e);
  }
  /**
   * 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(e) {
    return y1(this, e);
  }
  /**
   * 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(e = 0, t = this.length) {
    return p1(this, e, t);
  }
  /**
   * 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(e) {
    Ms(this, e);
  }
  /**
   * 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(e) {
    e.writeTypeRef(L$);
  }
}
const g$ = (n) => new wi();
class at extends wi {
  constructor(e = "UNDEFINED") {
    super(), this.nodeName = e, this._prelimAttrs = /* @__PURE__ */ new Map();
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get nextSibling() {
    const e = this._item ? this._item.next : null;
    return e ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      e.content.type
    ) : null;
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get prevSibling() {
    const e = this._item ? this._item.prev : null;
    return e ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      e.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(e, t) {
    super._integrate(e, t), /** @type {Map<string, any>} */
    this._prelimAttrs.forEach((r, i) => {
      this.setAttribute(i, r);
    }), this._prelimAttrs = null;
  }
  /**
   * Creates an Item with the same effect as this Item (without position effect)
   *
   * @return {YXmlElement}
   */
  _copy() {
    return new at(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 e = new at(this.nodeName), t = this.getAttributes();
    return GF(t, (r, i) => {
      typeof r == "string" && e.setAttribute(i, r);
    }), e.insert(0, this.toArray().map((r) => r instanceof ze ? r.clone() : r)), e;
  }
  /**
   * 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 e = this.getAttributes(), t = [], r = [];
    for (const l in e)
      r.push(l);
    r.sort();
    const i = r.length;
    for (let l = 0; l < i; l++) {
      const a = r[l];
      t.push(a + '="' + e[a] + '"');
    }
    const o = this.nodeName.toLocaleLowerCase(), s = t.length > 0 ? " " + t.join(" ") : "";
    return `<${o}${s}>${super.toString()}</${o}>`;
  }
  /**
   * Removes an attribute from this YXmlElement.
   *
   * @param {string} attributeName The attribute name that is to be removed.
   *
   * @public
   */
  removeAttribute(e) {
    this.doc !== null ? de(this.doc, (t) => {
      rc(t, this, e);
    }) : this._prelimAttrs.delete(e);
  }
  /**
   * 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(e, t) {
    this.doc !== null ? de(this.doc, (r) => {
      Nf(r, this, e, t);
    }) : this._prelimAttrs.set(e, t);
  }
  /**
   * 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(e) {
    return (
      /** @type {any} */
      $f(this, e)
    );
  }
  /**
   * Returns whether an attribute exists
   *
   * @param {string} attributeName The attribute name to check for existence.
   * @return {boolean} whether the attribute exists.
   *
   * @public
   */
  hasAttribute(e) {
    return (
      /** @type {any} */
      C1(this, e)
    );
  }
  /**
   * 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(e) {
    return (
      /** @type {any} */
      e ? s$(this, e) : v1(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(e = document, t = {}, r) {
    const i = e.createElement(this.nodeName), o = this.getAttributes();
    for (const s in o) {
      const l = o[s];
      typeof l == "string" && i.setAttribute(s, l);
    }
    return Ms(this, (s) => {
      i.appendChild(s.toDOM(e, t, r));
    }), r !== void 0 && r._createAssociation(i, this), i;
  }
  /**
   * 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(e) {
    e.writeTypeRef(I$), e.writeKey(this.nodeName);
  }
}
const b$ = (n) => new at(n.readKey());
class y$ extends Tc {
  /**
   * @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(e, t, r) {
    super(e, r), this.childListChanged = !1, this.attributesChanged = /* @__PURE__ */ new Set(), t.forEach((i) => {
      i === null ? this.childListChanged = !0 : this.attributesChanged.add(i);
    });
  }
}
class ic extends po {
  /**
   * @param {string} hookName nodeName of the Dom Node.
   */
  constructor(e) {
    super(), this.hookName = e;
  }
  /**
   * Creates an Item with the same effect as this Item (without position effect)
   */
  _copy() {
    return new ic(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 e = new ic(this.hookName);
    return this.forEach((t, r) => {
      e.set(r, t);
    }), e;
  }
  /**
   * 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(e = document, t = {}, r) {
    const i = t[this.hookName];
    let o;
    return i !== void 0 ? o = i.createDom(this) : o = document.createElement(this.hookName), o.setAttribute("data-yjs-hook", this.hookName), r !== void 0 && r._createAssociation(o, this), o;
  }
  /**
   * 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(e) {
    e.writeTypeRef(R$), e.writeKey(this.hookName);
  }
}
const _$ = (n) => new ic(n.readKey());
class At extends Lr {
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get nextSibling() {
    const e = this._item ? this._item.next : null;
    return e ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      e.content.type
    ) : null;
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get prevSibling() {
    const e = this._item ? this._item.prev : null;
    return e ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      e.content.type
    ) : null;
  }
  _copy() {
    return new At();
  }
  /**
   * 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 e = new At();
    return e.applyDelta(this.toDelta()), e;
  }
  /**
   * 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(e = document, t, r) {
    const i = e.createTextNode(this.toString());
    return r !== void 0 && r._createAssociation(i, this), i;
  }
  toString() {
    return this.toDelta().map((e) => {
      const t = [];
      for (const i in e.attributes) {
        const o = [];
        for (const s in e.attributes[i])
          o.push({ key: s, value: e.attributes[i][s] });
        o.sort((s, l) => s.key < l.key ? -1 : 1), t.push({ nodeName: i, attrs: o });
      }
      t.sort((i, o) => i.nodeName < o.nodeName ? -1 : 1);
      let r = "";
      for (let i = 0; i < t.length; i++) {
        const o = t[i];
        r += `<${o.nodeName}`;
        for (let s = 0; s < o.attrs.length; s++) {
          const l = o.attrs[s];
          r += ` ${l.key}="${l.value}"`;
        }
        r += ">";
      }
      r += e.insert;
      for (let i = t.length - 1; i >= 0; i--)
        r += `</${t[i].nodeName}>`;
      return r;
    }).join("");
  }
  /**
   * @return {string}
   */
  toJSON() {
    return this.toString();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(e) {
    e.writeTypeRef(B$);
  }
}
const w$ = (n) => new At();
class If {
  /**
   * @param {ID} id
   * @param {number} length
   */
  constructor(e, t) {
    this.id = e, this.length = t;
  }
  /**
   * @type {boolean}
   */
  get deleted() {
    throw un();
  }
  /**
   * 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(e) {
    return !1;
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   * @param {number} offset
   * @param {number} encodingRef
   */
  write(e, t, r) {
    throw un();
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(e, t) {
    throw un();
  }
}
const k$ = 0;
class Vt extends If {
  get deleted() {
    return !0;
  }
  delete() {
  }
  /**
   * @param {GC} right
   * @return {boolean}
   */
  mergeWith(e) {
    return this.constructor !== e.constructor ? !1 : (this.length += e.length, !0);
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(e, t) {
    t > 0 && (this.id.clock += t, this.length -= t), l1(e.doc.store, this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeInfo(k$), e.writeLen(this.length - t);
  }
  /**
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(e, t) {
    return null;
  }
}
class Ws {
  /**
   * @param {Uint8Array} content
   */
  constructor(e) {
    this.content = e;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.content];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !0;
  }
  /**
   * @return {ContentBinary}
   */
  copy() {
    return new Ws(this.content);
  }
  /**
   * @param {number} offset
   * @return {ContentBinary}
   */
  splice(e) {
    throw un();
  }
  /**
   * @param {ContentBinary} right
   * @return {boolean}
   */
  mergeWith(e) {
    return !1;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeBuf(this.content);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 3;
  }
}
const v$ = (n) => new Ws(n.readBuf());
class Os {
  /**
   * @param {number} len
   */
  constructor(e) {
    this.len = e;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.len;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !1;
  }
  /**
   * @return {ContentDeleted}
   */
  copy() {
    return new Os(this.len);
  }
  /**
   * @param {number} offset
   * @return {ContentDeleted}
   */
  splice(e) {
    const t = new Os(this.len - e);
    return this.len = e, t;
  }
  /**
   * @param {ContentDeleted} right
   * @return {boolean}
   */
  mergeWith(e) {
    return this.len += e.len, !0;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
    Es(e.deleteSet, t.id.client, t.id.clock, this.len), t.markDeleted();
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeLen(this.len - t);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 1;
  }
}
const C$ = (n) => new Os(n.readLen()), A1 = (n, e) => new Hr({ guid: n, ...e, shouldLoad: e.shouldLoad || e.autoLoad || !1 });
class Gs {
  /**
   * @param {Doc} doc
   */
  constructor(e) {
    e._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 = e;
    const t = {};
    this.opts = t, e.gc || (t.gc = !1), e.autoLoad && (t.autoLoad = !0), e.meta !== null && (t.meta = e.meta);
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.doc];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !0;
  }
  /**
   * @return {ContentDoc}
   */
  copy() {
    return new Gs(A1(this.doc.guid, this.opts));
  }
  /**
   * @param {number} offset
   * @return {ContentDoc}
   */
  splice(e) {
    throw un();
  }
  /**
   * @param {ContentDoc} right
   * @return {boolean}
   */
  mergeWith(e) {
    return !1;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
    this.doc._item = t, e.subdocsAdded.add(this.doc), this.doc.shouldLoad && e.subdocsLoaded.add(this.doc);
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
    e.subdocsAdded.has(this.doc) ? e.subdocsAdded.delete(this.doc) : e.subdocsRemoved.add(this.doc);
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeString(this.doc.guid), e.writeAny(this.opts);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 9;
  }
}
const S$ = (n) => new Gs(A1(n.readString(), n.readAny()));
class xi {
  /**
   * @param {Object} embed
   */
  constructor(e) {
    this.embed = e;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.embed];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !0;
  }
  /**
   * @return {ContentEmbed}
   */
  copy() {
    return new xi(this.embed);
  }
  /**
   * @param {number} offset
   * @return {ContentEmbed}
   */
  splice(e) {
    throw un();
  }
  /**
   * @param {ContentEmbed} right
   * @return {boolean}
   */
  mergeWith(e) {
    return !1;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeJSON(this.embed);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 5;
  }
}
const E$ = (n) => new xi(n.readJSON());
class Ne {
  /**
   * @param {string} key
   * @param {Object} value
   */
  constructor(e, t) {
    this.key = e, this.value = t;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !1;
  }
  /**
   * @return {ContentFormat}
   */
  copy() {
    return new Ne(this.key, this.value);
  }
  /**
   * @param {number} _offset
   * @return {ContentFormat}
   */
  splice(e) {
    throw un();
  }
  /**
   * @param {ContentFormat} _right
   * @return {boolean}
   */
  mergeWith(e) {
    return !1;
  }
  /**
   * @param {Transaction} _transaction
   * @param {Item} item
   */
  integrate(e, t) {
    const r = (
      /** @type {YText} */
      t.parent
    );
    r._searchMarker = null, r._hasFormatting = !0;
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeKey(this.key), e.writeJSON(this.value);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 6;
  }
}
const x$ = (n) => new Ne(n.readKey(), n.readJSON());
class oc {
  /**
   * @param {Array<any>} arr
   */
  constructor(e) {
    this.arr = e;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.arr.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.arr;
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !0;
  }
  /**
   * @return {ContentJSON}
   */
  copy() {
    return new oc(this.arr);
  }
  /**
   * @param {number} offset
   * @return {ContentJSON}
   */
  splice(e) {
    const t = new oc(this.arr.slice(e));
    return this.arr = this.arr.slice(0, e), t;
  }
  /**
   * @param {ContentJSON} right
   * @return {boolean}
   */
  mergeWith(e) {
    return this.arr = this.arr.concat(e.arr), !0;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    const r = this.arr.length;
    e.writeLen(r - t);
    for (let i = t; i < r; i++) {
      const o = this.arr[i];
      e.writeString(o === void 0 ? "undefined" : JSON.stringify(o));
    }
  }
  /**
   * @return {number}
   */
  getRef() {
    return 2;
  }
}
const D$ = (n) => {
  const e = n.readLen(), t = [];
  for (let r = 0; r < e; r++) {
    const i = n.readString();
    i === "undefined" ? t.push(void 0) : t.push(JSON.parse(i));
  }
  return new oc(t);
}, A$ = Qa("node_env") === "development";
class ki {
  /**
   * @param {Array<any>} arr
   */
  constructor(e) {
    this.arr = e, A$ && Pw(e);
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.arr.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.arr;
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !0;
  }
  /**
   * @return {ContentAny}
   */
  copy() {
    return new ki(this.arr);
  }
  /**
   * @param {number} offset
   * @return {ContentAny}
   */
  splice(e) {
    const t = new ki(this.arr.slice(e));
    return this.arr = this.arr.slice(0, e), t;
  }
  /**
   * @param {ContentAny} right
   * @return {boolean}
   */
  mergeWith(e) {
    return this.arr = this.arr.concat(e.arr), !0;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    const r = this.arr.length;
    e.writeLen(r - t);
    for (let i = t; i < r; i++) {
      const o = this.arr[i];
      e.writeAny(o);
    }
  }
  /**
   * @return {number}
   */
  getRef() {
    return 8;
  }
}
const T$ = (n) => {
  const e = n.readLen(), t = [];
  for (let r = 0; r < e; r++)
    t.push(n.readAny());
  return new ki(t);
};
class pn {
  /**
   * @param {string} str
   */
  constructor(e) {
    this.str = e;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.str.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.str.split("");
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !0;
  }
  /**
   * @return {ContentString}
   */
  copy() {
    return new pn(this.str);
  }
  /**
   * @param {number} offset
   * @return {ContentString}
   */
  splice(e) {
    const t = new pn(this.str.slice(e));
    this.str = this.str.slice(0, e);
    const r = this.str.charCodeAt(e - 1);
    return r >= 55296 && r <= 56319 && (this.str = this.str.slice(0, e - 1) + "�", t.str = "�" + t.str.slice(1)), t;
  }
  /**
   * @param {ContentString} right
   * @return {boolean}
   */
  mergeWith(e) {
    return this.str += e.str, !0;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeString(t === 0 ? this.str : this.str.slice(t));
  }
  /**
   * @return {number}
   */
  getRef() {
    return 4;
  }
}
const M$ = (n) => new pn(n.readString()), O$ = [
  a$,
  d$,
  m$,
  b$,
  g$,
  _$,
  w$
], F$ = 0, N$ = 1, $$ = 2, I$ = 3, L$ = 4, R$ = 5, B$ = 6;
class gn {
  /**
   * @param {AbstractType<any>} type
   */
  constructor(e) {
    this.type = e;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.type];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return !0;
  }
  /**
   * @return {ContentType}
   */
  copy() {
    return new gn(this.type._copy());
  }
  /**
   * @param {number} offset
   * @return {ContentType}
   */
  splice(e) {
    throw un();
  }
  /**
   * @param {ContentType} right
   * @return {boolean}
   */
  mergeWith(e) {
    return !1;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(e, t) {
    this.type._integrate(e.doc, t);
  }
  /**
   * @param {Transaction} transaction
   */
  delete(e) {
    let t = this.type._start;
    for (; t !== null; )
      t.deleted ? t.id.clock < (e.beforeState.get(t.id.client) || 0) && e._mergeStructs.push(t) : t.delete(e), t = t.right;
    this.type._map.forEach((r) => {
      r.deleted ? r.id.clock < (e.beforeState.get(r.id.client) || 0) && e._mergeStructs.push(r) : r.delete(e);
    }), e.changed.delete(this.type);
  }
  /**
   * @param {StructStore} store
   */
  gc(e) {
    let t = this.type._start;
    for (; t !== null; )
      t.gc(e, !0), t = t.right;
    this.type._start = null, this.type._map.forEach(
      /** @param {Item | null} item */
      (r) => {
        for (; r !== null; )
          r.gc(e, !0), r = r.left;
      }
    ), this.type._map = /* @__PURE__ */ new Map();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    this.type._write(e);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 7;
  }
}
const P$ = (n) => new gn(O$[n.readTypeRef()](n)), ih = (n, e) => {
  let t = e, r = 0, i;
  do
    r > 0 && (t = j(t.client, t.clock + r)), i = eo(n, t), r = t.clock - i.id.clock, t = i.redone;
  while (t !== null && i instanceof ie);
  return {
    item: i,
    diff: r
  };
}, Lf = (n, e) => {
  for (; n !== null && n.keep !== e; )
    n.keep = e, n = /** @type {AbstractType<any>} */
    n.parent._item;
}, sc = (n, e, t) => {
  const { client: r, clock: i } = e.id, o = new ie(
    j(r, i + t),
    e,
    j(r, i + t - 1),
    e.right,
    e.rightOrigin,
    e.parent,
    e.parentSub,
    e.content.splice(t)
  );
  return e.deleted && o.markDeleted(), e.keep && (o.keep = !0), e.redone !== null && (o.redone = j(e.redone.client, e.redone.clock + t)), e.right = o, o.right !== null && (o.right.left = o), n._mergeStructs.push(o), o.parentSub !== null && o.right === null && o.parent._map.set(o.parentSub, o), e.length = t, o;
}, N0 = (n, e) => oF(
  n,
  /** @param {StackItem} s */
  (t) => wo(t.deletions, e)
), T1 = (n, e, t, r, i, o) => {
  const s = n.doc, l = s.store, a = s.clientID, c = e.redone;
  if (c !== null)
    return _t(n, c);
  let d = (
    /** @type {AbstractType<any>} */
    e.parent._item
  ), u = null, h;
  if (d !== null && d.deleted === !0) {
    if (d.redone === null && (!t.has(d) || T1(n, d, t, r, i, o) === null))
      return null;
    for (; d.redone !== null; )
      d = _t(n, d.redone);
  }
  const f = d === null ? (
    /** @type {AbstractType<any>} */
    e.parent
  ) : (
    /** @type {ContentType} */
    d.content.type
  );
  if (e.parentSub === null) {
    for (u = e.left, h = e; u !== null; ) {
      let y = u;
      for (; y !== null && /** @type {AbstractType<any>} */
      y.parent._item !== d; )
        y = y.redone === null ? null : _t(n, y.redone);
      if (y !== null && /** @type {AbstractType<any>} */
      y.parent._item === d) {
        u = y;
        break;
      }
      u = u.left;
    }
    for (; h !== null; ) {
      let y = h;
      for (; y !== null && /** @type {AbstractType<any>} */
      y.parent._item !== d; )
        y = y.redone === null ? null : _t(n, y.redone);
      if (y !== null && /** @type {AbstractType<any>} */
      y.parent._item === d) {
        h = y;
        break;
      }
      h = h.right;
    }
  } else if (h = null, e.right && !i) {
    for (u = e; u !== null && u.right !== null && (u.right.redone || wo(r, u.right.id) || N0(o.undoStack, u.right.id) || N0(o.redoStack, u.right.id)); )
      for (u = u.right; u.redone; ) u = _t(n, u.redone);
    if (u && u.right !== null)
      return null;
  } else
    u = f._map.get(e.parentSub) || null;
  const p = De(l, a), m = j(a, p), g = new ie(
    m,
    u,
    u && u.lastId,
    h,
    h && h.id,
    f,
    e.parentSub,
    e.content.copy()
  );
  return e.redone = m, Lf(g, !0), g.integrate(n, 0), g;
};
class ie extends If {
  /**
   * @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(e, t, r, i, o, s, l, a) {
    super(e, a.getLength()), this.origin = r, this.left = t, this.right = i, this.rightOrigin = o, this.parent = s, this.parentSub = l, this.redone = null, this.content = a, this.info = this.content.isCountable() ? l0 : 0;
  }
  /**
   * This is used to mark the item as an indexed fast-search marker
   *
   * @type {boolean}
   */
  set marker(e) {
    (this.info & qd) > 0 !== e && (this.info ^= qd);
  }
  get marker() {
    return (this.info & qd) > 0;
  }
  /**
   * If true, do not garbage collect this Item.
   */
  get keep() {
    return (this.info & s0) > 0;
  }
  set keep(e) {
    this.keep !== e && (this.info ^= s0);
  }
  get countable() {
    return (this.info & l0) > 0;
  }
  /**
   * Whether this item was deleted or not.
   * @type {Boolean}
   */
  get deleted() {
    return (this.info & Ud) > 0;
  }
  set deleted(e) {
    this.deleted !== e && (this.info ^= Ud);
  }
  markDeleted() {
    this.info |= Ud;
  }
  /**
   * 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(e, t) {
    if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= De(t, this.origin.client))
      return this.origin.client;
    if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= De(t, this.rightOrigin.client))
      return this.rightOrigin.client;
    if (this.parent && this.parent.constructor === Qi && this.id.client !== this.parent.client && this.parent.clock >= De(t, this.parent.client))
      return this.parent.client;
    if (this.origin && (this.left = S0(e, t, this.origin), this.origin = this.left.lastId), this.rightOrigin && (this.right = _t(e, this.rightOrigin), this.rightOrigin = this.right.id), this.left && this.left.constructor === Vt || this.right && this.right.constructor === Vt)
      this.parent = null;
    else if (!this.parent)
      this.left && this.left.constructor === ie ? (this.parent = this.left.parent, this.parentSub = this.left.parentSub) : this.right && this.right.constructor === ie && (this.parent = this.right.parent, this.parentSub = this.right.parentSub);
    else if (this.parent.constructor === Qi) {
      const r = eo(t, this.parent);
      r.constructor === Vt ? this.parent = null : this.parent = /** @type {ContentType} */
      r.content.type;
    }
    return null;
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(e, t) {
    if (t > 0 && (this.id.clock += t, this.left = S0(e, e.doc.store, j(this.id.client, this.id.clock - 1)), this.origin = this.left.lastId, this.content = this.content.splice(t), this.length -= t), this.parent) {
      if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) {
        let r = this.left, i;
        if (r !== null)
          i = r.right;
        else if (this.parentSub !== null)
          for (i = /** @type {AbstractType<any>} */
          this.parent._map.get(this.parentSub) || null; i !== null && i.left !== null; )
            i = i.left;
        else
          i = /** @type {AbstractType<any>} */
          this.parent._start;
        const o = /* @__PURE__ */ new Set(), s = /* @__PURE__ */ new Set();
        for (; i !== null && i !== this.right; ) {
          if (s.add(i), o.add(i), ji(this.origin, i.origin)) {
            if (i.id.client < this.id.client)
              r = i, o.clear();
            else if (ji(this.rightOrigin, i.rightOrigin))
              break;
          } else if (i.origin !== null && s.has(eo(e.doc.store, i.origin)))
            o.has(eo(e.doc.store, i.origin)) || (r = i, o.clear());
          else
            break;
          i = i.right;
        }
        this.left = r;
      }
      if (this.left !== null) {
        const r = this.left.right;
        this.right = r, this.left.right = this;
      } else {
        let r;
        if (this.parentSub !== null)
          for (r = /** @type {AbstractType<any>} */
          this.parent._map.get(this.parentSub) || null; r !== null && r.left !== null; )
            r = r.left;
        else
          r = /** @type {AbstractType<any>} */
          this.parent._start, this.parent._start = this;
        this.right = r;
      }
      this.right !== null ? this.right.left = this : this.parentSub !== null && (this.parent._map.set(this.parentSub, this), this.left !== null && this.left.delete(e)), this.parentSub === null && this.countable && !this.deleted && (this.parent._length += this.length), l1(e.doc.store, this), this.content.integrate(e, this), x0(
        e,
        /** @type {AbstractType<any>} */
        this.parent,
        this.parentSub
      ), /** @type {AbstractType<any>} */
      (this.parent._item !== null && /** @type {AbstractType<any>} */
      this.parent._item.deleted || this.parentSub !== null && this.right !== null) && this.delete(e);
    } else
      new Vt(this.id, this.length).integrate(e, 0);
  }
  /**
   * Returns the next non-deleted item
   */
  get next() {
    let e = this.right;
    for (; e !== null && e.deleted; )
      e = e.right;
    return e;
  }
  /**
   * Returns the previous non-deleted item
   */
  get prev() {
    let e = this.left;
    for (; e !== null && e.deleted; )
      e = e.left;
    return e;
  }
  /**
   * Computes the last content address of this Item.
   */
  get lastId() {
    return this.length === 1 ? this.id : j(this.id.client, this.id.clock + this.length - 1);
  }
  /**
   * Try to merge two items
   *
   * @param {Item} right
   * @return {boolean}
   */
  mergeWith(e) {
    if (this.constructor === e.constructor && ji(e.origin, this.lastId) && this.right === e && ji(this.rightOrigin, e.rightOrigin) && this.id.client === e.id.client && this.id.clock + this.length === e.id.clock && this.deleted === e.deleted && this.redone === null && e.redone === null && this.content.constructor === e.content.constructor && this.content.mergeWith(e.content)) {
      const t = (
        /** @type {AbstractType<any>} */
        this.parent._searchMarker
      );
      return t && t.forEach((r) => {
        r.p === e && (r.p = this, !this.deleted && this.countable && (r.index -= this.length));
      }), e.keep && (this.keep = !0), this.right = e.right, this.right !== null && (this.right.left = this), this.length += e.length, !0;
    }
    return !1;
  }
  /**
   * Mark this Item as deleted.
   *
   * @param {Transaction} transaction
   */
  delete(e) {
    if (!this.deleted) {
      const t = (
        /** @type {AbstractType<any>} */
        this.parent
      );
      this.countable && this.parentSub === null && (t._length -= this.length), this.markDeleted(), Es(e.deleteSet, this.id.client, this.id.clock, this.length), x0(e, t, this.parentSub), this.content.delete(e);
    }
  }
  /**
   * @param {StructStore} store
   * @param {boolean} parentGCd
   */
  gc(e, t) {
    if (!this.deleted)
      throw Ot();
    this.content.gc(e), t ? UN(e, this, new Vt(this.id, this.length)) : this.content = new Os(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(e, t) {
    const r = t > 0 ? j(this.id.client, this.id.clock + t - 1) : this.origin, i = this.rightOrigin, o = this.parentSub, s = this.content.getRef() & xc | (r === null ? 0 : ct) | // origin is defined
    (i === null ? 0 : rr) | // right origin is defined
    (o === null ? 0 : vs);
    if (e.writeInfo(s), r !== null && e.writeLeftID(r), i !== null && e.writeRightID(i), r === null && i === null) {
      const l = (
        /** @type {AbstractType<any>} */
        this.parent
      );
      if (l._item !== void 0) {
        const a = l._item;
        if (a === null) {
          const c = xs(l);
          e.writeParentInfo(!0), e.writeString(c);
        } else
          e.writeParentInfo(!1), e.writeLeftID(a.id);
      } else l.constructor === String ? (e.writeParentInfo(!0), e.writeString(l)) : l.constructor === Qi ? (e.writeParentInfo(!1), e.writeLeftID(l)) : Ot();
      o !== null && e.writeString(o);
    }
    this.content.write(e, t);
  }
}
const M1 = (n, e) => z$[e & xc](n), z$ = [
  () => {
    Ot();
  },
  // GC is not ItemContent
  C$,
  // 1
  D$,
  // 2
  v$,
  // 3
  M$,
  // 4
  E$,
  // 5
  x$,
  // 6
  P$,
  // 7
  T$,
  // 8
  S$,
  // 9
  () => {
    Ot();
  }
  // 10 - Skip is not ItemContent
], H$ = 10;
class Ut extends If {
  get deleted() {
    return !0;
  }
  delete() {
  }
  /**
   * @param {Skip} right
   * @return {boolean}
   */
  mergeWith(e) {
    return this.constructor !== e.constructor ? !1 : (this.length += e.length, !0);
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(e, t) {
    Ot();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(e, t) {
    e.writeInfo(H$), Z(e.restEncoder, this.length - t);
  }
  /**
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(e, t) {
    return null;
  }
}
const O1 = (
  /** @type {any} */
  typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : {}
), F1 = "__ $YJS$ __";
O1[F1] === !0 && console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");
O1[F1] = !0;
const V$ = () => {
  let n = !0;
  return (e, t) => {
    if (n) {
      n = !1;
      try {
        e();
      } finally {
        n = !0;
      }
    } else t !== void 0 && t();
  };
}, U$ = /[\uD800-\uDBFF]/, q$ = /[\uDC00-\uDFFF]/, j$ = (n, e) => {
  let t = 0, r = 0;
  for (; t < n.length && t < e.length && n[t] === e[t]; )
    t++;
  for (t > 0 && U$.test(n[t - 1]) && t--; r + t < n.length && r + t < e.length && n[n.length - r - 1] === e[e.length - r - 1]; )
    r++;
  return r > 0 && q$.test(n[n.length - r]) && r--, {
    index: t,
    remove: n.length - t - r,
    insert: e.slice(t, e.length - r)
  };
}, W$ = j$, ne = new te("y-sync"), Wt = new te("y-undo"), Vo = new te("yjs-cursor"), Fn = (n, e) => n >>> e | n << 32 - e, G$ = (n) => Fn(n, 2) ^ Fn(n, 13) ^ Fn(n, 22), K$ = (n) => Fn(n, 6) ^ Fn(n, 11) ^ Fn(n, 25), J$ = (n) => Fn(n, 7) ^ Fn(n, 18) ^ n >>> 3, Y$ = (n) => Fn(n, 17) ^ Fn(n, 19) ^ n >>> 10, X$ = 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
]), Z$ = new Uint32Array([
  1779033703,
  3144134277,
  1013904242,
  2773480762,
  1359893119,
  2600822924,
  528734635,
  1541459225
]);
class Q$ {
  constructor() {
    const e = new ArrayBuffer(320);
    this._H = new Uint32Array(e, 0, 8), this._H.set(Z$), this._W = new Uint32Array(e, 64, 64);
  }
  _updateHash() {
    const e = this._H, t = this._W;
    for (let u = 16; u < 64; u++)
      t[u] = Y$(t[u - 2]) + t[u - 7] + J$(t[u - 15]) + t[u - 16];
    let r = e[0], i = e[1], o = e[2], s = e[3], l = e[4], a = e[5], c = e[6], d = e[7];
    for (let u = 0, h, f; u < 64; u++)
      h = d + K$(l) + (l & a ^ ~l & c) + X$[u] + t[u] >>> 0, f = G$(r) + (r & i ^ r & o ^ i & o) >>> 0, d = c, c = a, a = l, l = s + h >>> 0, s = o, o = i, i = r, r = h + f >>> 0;
    e[0] += r, e[1] += i, e[2] += o, e[3] += s, e[4] += l, e[5] += a, e[6] += c, e[7] += d;
  }
  /**
   * Returns a 32-byte hash.
   *
   * @param {Uint8Array} data
   */
  digest(e) {
    let t = 0;
    for (; t + 56 <= e.length; ) {
      let s = 0;
      for (; s < 16 && t + 3 < e.length; s++)
        this._W[s] = e[t++] << 24 | e[t++] << 16 | e[t++] << 8 | e[t++];
      if (t % 64 !== 0) {
        for (this._W.fill(0, s, 16); t < e.length; )
          this._W[s] |= e[t] << (3 - t % 4) * 8, t++;
        this._W[s] |= ct << (3 - t % 4) * 8;
      }
      this._updateHash();
    }
    const r = t % 64 !== 0;
    this._W.fill(0, 0, 16);
    let i = 0;
    for (; t < e.length; i++)
      for (let s = 3; s >= 0 && t < e.length; s--)
        this._W[i] |= e[t++] << s * 8;
    r || (this._W[i - (t % 4 === 0 ? 0 : 1)] |= ct << (3 - t % 4) * 8), this._W[14] = e.byteLength / sF, this._W[15] = e.byteLength * 8, this._updateHash();
    const o = new Uint8Array(32);
    for (let s = 0; s < this._H.length; s++)
      for (let l = 0; l < 4; l++)
        o[s * 4 + l] = this._H[s] >>> (3 - l) * 8;
    return o;
  }
}
const eI = (n) => new Q$().digest(n), tI = (n) => {
  for (let t = 6; t < n.length; t++)
    n[t % 6] = n[t % 6] ^ n[t];
  return n.slice(0, 6);
}, nI = (n) => sN(tI(eI(aN(n)))), lc = (n, e) => e === void 0 ? !n.deleted : e.sv.has(n.id.client) && /** @type {number} */
e.sv.get(n.id.client) > n.id.clock && !wo(e.ds, n.id), rI = [{ light: "#ecd44433", dark: "#ecd444" }], iI = (n, e, t) => {
  if (!n.has(t)) {
    if (n.size < e.length) {
      const r = yi();
      n.forEach((i) => r.add(i)), e = e.filter((i) => !r.has(i));
    }
    n.set(t, PF(e));
  }
  return (
    /** @type {ColorDef} */
    n.get(t)
  );
}, oI = (n, {
  colors: e = rI,
  colorMapping: t = /* @__PURE__ */ new Map(),
  permanentUserData: r = null,
  onFirstRender: i = () => {
  },
  mapping: o
} = {}) => {
  let s = !1;
  const l = new lI(n, o), a = new G({
    props: {
      editable: (c) => {
        const d = ne.getState(c);
        return d.snapshot == null && d.prevSnapshot == null;
      }
    },
    key: ne,
    state: {
      /**
       * @returns {any}
       */
      init: (c, d) => ({
        type: n,
        doc: n.doc,
        binding: l,
        snapshot: null,
        prevSnapshot: null,
        isChangeOrigin: !1,
        isUndoRedoOperation: !1,
        addToHistory: !0,
        colors: e,
        colorMapping: t,
        permanentUserData: r
      }),
      apply: (c, d) => {
        const u = c.getMeta(ne);
        if (u !== void 0) {
          d = Object.assign({}, d);
          for (const h in u)
            d[h] = u[h];
        }
        return d.addToHistory = c.getMeta("addToHistory") !== !1, d.isChangeOrigin = u !== void 0 && !!u.isChangeOrigin, d.isUndoRedoOperation = u !== void 0 && !!u.isChangeOrigin && !!u.isUndoRedoOperation, l.prosemirrorView !== null && u !== void 0 && (u.snapshot != null || u.prevSnapshot != null) && vf(0, () => {
          l.prosemirrorView != null && (u.restore == null ? l._renderSnapshot(
            u.snapshot,
            u.prevSnapshot,
            d
          ) : (l._renderSnapshot(
            u.snapshot,
            u.snapshot,
            d
          ), delete d.restore, delete d.snapshot, delete d.prevSnapshot, l.mux(() => {
            l._prosemirrorChanged(
              l.prosemirrorView.state.doc
            );
          })));
        }), d;
      }
    },
    view: (c) => (l.initView(c), o == null && l._forceRerender(), i(), {
      update: () => {
        const d = a.getState(c.state);
        if (d.snapshot == null && d.prevSnapshot == null && // 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
        (s || c.state.doc.content.findDiffStart(
          c.state.doc.type.createAndFill().content
        ) !== null)) {
          if (s = !0, d.addToHistory === !1 && !d.isChangeOrigin) {
            const u = Wt.getState(c.state), h = u && u.undoManager;
            h && h.stopCapturing();
          }
          l.mux(() => {
            d.doc.transact((u) => {
              u.meta.set("addToHistory", d.addToHistory), l._prosemirrorChanged(c.state.doc);
            }, ne);
          });
        }
      },
      destroy: () => {
        l.destroy();
      }
    })
  });
  return a;
}, sI = (n, e, t) => {
  if (e !== null && e.anchor !== null && e.head !== null)
    if (e.type === "all")
      n.setSelection(new wt(n.doc));
    else if (e.type === "node") {
      const r = ci(
        t.doc,
        t.type,
        e.anchor,
        t.mapping
      );
      n.setSelection(P.create(n.doc, r));
    } else {
      const r = ci(
        t.doc,
        t.type,
        e.anchor,
        t.mapping
      ), i = ci(
        t.doc,
        t.type,
        e.head,
        t.mapping
      );
      if (r !== null && i !== null) {
        const o = L.between(n.doc.resolve(r), n.doc.resolve(i));
        n.setSelection(o);
      }
    }
}, ac = (n, e) => ({
  type: (
    /** @type {any} */
    e.selection.jsonID
  ),
  anchor: Ns(
    e.selection.anchor,
    n.type,
    n.mapping
  ),
  head: Ns(
    e.selection.head,
    n.type,
    n.mapping
  )
});
class lI {
  /**
   * @param {Y.XmlFragment} yXmlFragment The bind source
   * @param {ProsemirrorMapping} mapping
   */
  constructor(e, t = /* @__PURE__ */ new Map()) {
    this.type = e, this.prosemirrorView = null, this.mux = V$(), this.mapping = t, this.isOMark = /* @__PURE__ */ new Map(), this._observeFunction = this._typeChanged.bind(this), this.doc = e.doc, this.beforeTransactionSelection = null, this.beforeAllTransactions = () => {
      this.beforeTransactionSelection === null && this.prosemirrorView != null && (this.beforeTransactionSelection = ac(
        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", !1);
  }
  _isLocalCursorInView() {
    return this.prosemirrorView.hasFocus() ? (zw && this._domSelectionInView === null && (vf(0, () => {
      this._domSelectionInView = null;
    }), this._domSelectionInView = this._isDomSelectionInView()), this._domSelectionInView) : !1;
  }
  _isDomSelectionInView() {
    const e = this.prosemirrorView._root.getSelection();
    if (e == null || e.anchorNode == null) return !1;
    const t = this.prosemirrorView._root.createRange();
    t.setStart(e.anchorNode, e.anchorOffset), t.setEnd(e.focusNode, e.focusOffset), t.getClientRects().length === 0 && t.startContainer && t.collapsed && t.selectNodeContents(t.startContainer);
    const i = t.getBoundingClientRect(), o = dN.documentElement;
    return i.bottom >= 0 && i.right >= 0 && i.left <= (window.innerWidth || o.clientWidth || 0) && i.top <= (window.innerHeight || o.clientHeight || 0);
  }
  /**
   * @param {Y.Snapshot} snapshot
   * @param {Y.Snapshot} prevSnapshot
   */
  renderSnapshot(e, t) {
    t || (t = o1(Jw(), /* @__PURE__ */ new Map())), this.prosemirrorView.dispatch(
      this._tr.setMeta(ne, { snapshot: e, prevSnapshot: t })
    );
  }
  unrenderSnapshot() {
    this.mapping.clear(), this.mux(() => {
      const e = this.type.toArray().map(
        (r) => ia(
          /** @type {Y.XmlElement} */
          r,
          this.prosemirrorView.state.schema,
          this
        )
      ).filter((r) => r !== null), t = this._tr.replace(
        0,
        this.prosemirrorView.state.doc.content.size,
        new O(A.from(e), 0, 0)
      );
      t.setMeta(ne, { snapshot: null, prevSnapshot: null }), this.prosemirrorView.dispatch(t);
    });
  }
  _forceRerender() {
    this.mapping.clear(), this.mux(() => {
      const e = this.beforeTransactionSelection !== null ? null : this.prosemirrorView.state.selection, t = this.type.toArray().map(
        (i) => ia(
          /** @type {Y.XmlElement} */
          i,
          this.prosemirrorView.state.schema,
          this
        )
      ).filter((i) => i !== null), r = this._tr.replace(
        0,
        this.prosemirrorView.state.doc.content.size,
        new O(A.from(t), 0, 0)
      );
      if (e) {
        const i = nr(fn(e.anchor, 0), r.doc.content.size), o = nr(fn(e.head, 0), r.doc.content.size);
        r.setSelection(L.create(r.doc, i, o));
      }
      this.prosemirrorView.dispatch(
        r.setMeta(ne, { isChangeOrigin: !0, binding: this })
      );
    });
  }
  /**
   * @param {Y.Snapshot|Uint8Array} snapshot
   * @param {Y.Snapshot|Uint8Array} prevSnapshot
   * @param {Object} pluginState
   */
  _renderSnapshot(e, t, r) {
    let i = this.doc, o = this.type;
    if (e || (e = Jd(this.doc)), e instanceof Uint8Array || t instanceof Uint8Array)
      if ((!(e instanceof Uint8Array) || !(t instanceof Uint8Array)) && Ot(), i = new Hr({ gc: !1 }), ec(i, t), t = Jd(i), ec(i, e), e = Jd(i), o._item === null) {
        const s = Array.from(this.doc.share.keys()).find(
          (l) => this.doc.share.get(l) === this.type
        );
        o = i.getXmlFragment(s);
      } else {
        const s = i.store.clients.get(o._item.id.client) ?? [], l = Zt(
          s,
          o._item.id.clock
        );
        o = /** @type {Y.XmlFragment} */
        /** @type {Y.ContentType} */
        /** @type {Y.Item} */
        s[l].content.type;
      }
    this.mapping.clear(), this.mux(() => {
      i.transact((s) => {
        const l = r.permanentUserData;
        l && l.dss.forEach((u) => {
          Ir(s, u, (h) => {
          });
        });
        const a = (u, h) => {
          const f = u === "added" ? l.getUserByClientId(h.client) : l.getUserByDeletedId(h);
          return {
            user: f,
            type: u,
            color: iI(
              r.colorMapping,
              r.colors,
              f
            )
          };
        }, c = g1(
          o,
          new Af(t.ds, e.sv)
        ).map((u) => !u._item.deleted || lc(u._item, e) || lc(u._item, t) ? ia(
          u,
          this.prosemirrorView.state.schema,
          { mapping: /* @__PURE__ */ new Map(), isOMark: /* @__PURE__ */ new Map() },
          e,
          t,
          a
        ) : null).filter((u) => u !== null), d = this._tr.replace(
          0,
          this.prosemirrorView.state.doc.content.size,
          new O(A.from(c), 0, 0)
        );
        this.prosemirrorView.dispatch(
          d.setMeta(ne, { isChangeOrigin: !0 })
        );
      }, ne);
    });
  }
  /**
   * @param {Array<Y.YEvent<any>>} events
   * @param {Y.Transaction} transaction
   */
  _typeChanged(e, t) {
    if (this.prosemirrorView == null) return;
    const r = ne.getState(this.prosemirrorView.state);
    if (e.length === 0 || r.snapshot != null || r.prevSnapshot != null) {
      this.renderSnapshot(r.snapshot, r.prevSnapshot);
      return;
    }
    this.mux(() => {
      const i = (l, a) => this.mapping.delete(a);
      Ir(
        t,
        t.deleteSet,
        (l) => {
          if (l.constructor === ie) {
            const a = (
              /** @type {Y.ContentType} */
              /** @type {Y.Item} */
              l.content.type
            );
            a && this.mapping.delete(a);
          }
        }
      ), t.changed.forEach(i), t.changedParentTypes.forEach(i);
      const o = this.type.toArray().map(
        (l) => N1(
          /** @type {Y.XmlElement | Y.XmlHook} */
          l,
          this.prosemirrorView.state.schema,
          this
        )
      ).filter((l) => l !== null);
      let s = this._tr.replace(
        0,
        this.prosemirrorView.state.doc.content.size,
        new O(A.from(o), 0, 0)
      );
      sI(s, this.beforeTransactionSelection, this), s = s.setMeta(ne, { isChangeOrigin: !0, isUndoRedoOperation: t.origin instanceof d1 }), this.beforeTransactionSelection !== null && this._isLocalCursorInView() && s.scrollIntoView(), this.prosemirrorView.dispatch(s);
    });
  }
  /**
   * @param {import('prosemirror-model').Node} doc
   */
  _prosemirrorChanged(e) {
    this.doc.transact(() => {
      sh(this.doc, this.type, e, this), this.beforeTransactionSelection = ac(
        this,
        this.prosemirrorView.state
      );
    }, ne);
  }
  /**
   * View is ready to listen to changes. Register observers.
   * @param {any} prosemirrorView
   */
  initView(e) {
    this.prosemirrorView != null && this.destroy(), this.prosemirrorView = e, this.doc.on("beforeAllTransactions", this.beforeAllTransactions), this.doc.on("afterAllTransactions", this.afterAllTransactions), this.type.observeDeep(this._observeFunction);
  }
  destroy() {
    this.prosemirrorView != null && (this.prosemirrorView = null, this.type.unobserveDeep(this._observeFunction), this.doc.off("beforeAllTransactions", this.beforeAllTransactions), this.doc.off("afterAllTransactions", this.afterAllTransactions));
  }
}
const N1 = (n, e, t, r, i, o) => {
  const s = (
    /** @type {PModel.Node} */
    t.mapping.get(n)
  );
  if (s === void 0) {
    if (n instanceof at)
      return ia(
        n,
        e,
        t,
        r,
        i,
        o
      );
    throw un();
  }
  return s;
}, ia = (n, e, t, r, i, o) => {
  const s = [], l = (a) => {
    var c, d;
    if (a instanceof at) {
      const u = N1(
        a,
        e,
        t,
        r,
        i,
        o
      );
      u !== null && s.push(u);
    } else {
      const u = (
        /** @type {Y.ContentType} */
        (d = (c = a._item.right) == null ? void 0 : c.content) == null ? void 0 : d.type
      );
      u instanceof Lr && !u._item.deleted && u._item.id.client === u.doc.clientID && (a.applyDelta([
        { retain: a.length },
        ...u.toDelta()
      ]), u.doc.transact((f) => {
        u._item.delete(f);
      }));
      const h = aI(
        a,
        e,
        t,
        r,
        i,
        o
      );
      h !== null && h.forEach((f) => {
        f !== null && s.push(f);
      });
    }
  };
  r === void 0 || i === void 0 ? n.toArray().forEach(l) : g1(n, new Af(i.ds, r.sv)).forEach(l);
  try {
    const a = n.getAttributes(r);
    r !== void 0 && (lc(
      /** @type {Y.Item} */
      n._item,
      r
    ) ? lc(
      /** @type {Y.Item} */
      n._item,
      i
    ) || (a.ychange = o ? o(
      "added",
      /** @type {Y.Item} */
      n._item.id
    ) : { type: "added" }) : a.ychange = o ? o(
      "removed",
      /** @type {Y.Item} */
      n._item.id
    ) : { type: "removed" });
    const c = e.node(n.nodeName, a, s);
    return t.mapping.set(n, c), c;
  } catch {
    return n.doc.transact((c) => {
      n._item.delete(c);
    }, ne), t.mapping.delete(n), null;
  }
}, aI = (n, e, t, r, i, o) => {
  const s = [], l = n.toDelta(r, i, o);
  try {
    for (let a = 0; a < l.length; a++) {
      const c = l[a];
      s.push(e.text(c.insert, pI(c.attributes, e)));
    }
  } catch {
    return n.doc.transact((c) => {
      n._item.delete(c);
    }, ne), null;
  }
  return s;
}, cI = (n, e) => {
  const t = new At(), r = n.map((i) => ({
    // @ts-ignore
    insert: i.text,
    attributes: L1(i.marks, e)
  }));
  return t.applyDelta(r), e.mapping.set(t, n), t;
}, dI = (n, e) => {
  const t = new at(n.type.name);
  for (const r in n.attrs) {
    const i = n.attrs[r];
    i !== null && r !== "ychange" && t.setAttribute(r, i);
  }
  return t.insert(
    0,
    Fc(n).map(
      (r) => oh(r, e)
    )
  ), e.mapping.set(t, n), t;
}, oh = (n, e) => n instanceof Array ? cI(n, e) : dI(n, e), $0 = (n) => typeof n == "object" && n !== null, Rf = (n, e) => {
  const t = Object.keys(n).filter((i) => n[i] !== null);
  let r = t.length === (e == null ? 0 : Object.keys(e).filter((i) => e[i] !== null).length);
  for (let i = 0; i < t.length && r; i++) {
    const o = t[i], s = n[o], l = e[o];
    r = o === "ychange" || s === l || $0(s) && $0(l) && Rf(s, l);
  }
  return r;
}, Fc = (n) => {
  const e = n.content.content, t = [];
  for (let r = 0; r < e.length; r++) {
    const i = e[r];
    if (i.isText) {
      const o = [];
      for (let s = e[r]; r < e.length && s.isText; s = e[++r])
        o.push(s);
      r--, t.push(o);
    } else
      t.push(i);
  }
  return t;
}, $1 = (n, e) => {
  const t = n.toDelta();
  return t.length === e.length && t.every(
    /** @type {(d:any,i:number) => boolean} */
    (r, i) => r.insert === /** @type {any} */
    e[i].text && Rw(r.attributes || {}).length === e[i].marks.length && Bw(r.attributes, (o, s) => {
      var c;
      const l = I1(s), a = e[i].marks;
      return Rf(o, (c = a.find(
        /** @param {any} mark */
        (d) => d.type.name === l
      )) == null ? void 0 : c.attrs);
    })
  );
}, Fs = (n, e) => {
  if (n instanceof at && !(e instanceof Array) && lh(n, e)) {
    const t = Fc(e);
    return n._length === t.length && Rf(n.getAttributes(), e.attrs) && n.toArray().every(
      (r, i) => Fs(r, t[i])
    );
  }
  return n instanceof At && e instanceof Array && $1(n, e);
}, cc = (n, e) => n === e || n instanceof Array && e instanceof Array && n.length === e.length && n.every(
  (t, r) => e[r] === t
), I0 = (n, e, t) => {
  const r = n.toArray(), i = Fc(e), o = i.length, s = r.length, l = nr(s, o);
  let a = 0, c = 0, d = !1;
  for (; a < l; a++) {
    const u = r[a], h = i[a];
    if (cc(t.mapping.get(u), h))
      d = !0;
    else if (!Fs(u, h))
      break;
  }
  for (; a + c < l; c++) {
    const u = r[s - c - 1], h = i[o - c - 1];
    if (cc(t.mapping.get(u), h))
      d = !0;
    else if (!Fs(u, h))
      break;
  }
  return {
    equalityFactor: a + c,
    foundMappedChild: d
  };
}, uI = (n) => {
  let e = "", t = n._start;
  const r = {};
  for (; t !== null; )
    t.deleted || (t.countable && t.content instanceof pn ? e += t.content.str : t.content instanceof Ne && (r[t.content.key] = null)), t = t.right;
  return {
    str: e,
    nAttrs: r
  };
}, hI = (n, e, t) => {
  t.mapping.set(n, e);
  const { nAttrs: r, str: i } = uI(n), o = e.map((c) => ({
    insert: (
      /** @type {any} */
      c.text
    ),
    attributes: Object.assign({}, r, L1(c.marks, t))
  })), { insert: s, remove: l, index: a } = W$(
    i,
    o.map((c) => c.insert).join("")
  );
  n.delete(a, l), n.insert(a, s), n.applyDelta(
    o.map((c) => ({ retain: c.insert.length, attributes: c.attributes }))
  );
}, fI = /(.*)(--[a-zA-Z0-9+/=]{8})$/, I1 = (n) => {
  var e;
  return ((e = fI.exec(n)) == null ? void 0 : e[1]) ?? n;
}, pI = (n, e) => {
  const t = [];
  for (const r in n)
    t.push(e.mark(I1(r), n[r]));
  return t;
}, L1 = (n, e) => {
  const t = {};
  return n.forEach((r) => {
    if (r.type.name !== "ychange") {
      const i = Bn(e.isOMark, r.type, () => !r.type.excludes(r.type));
      t[i ? `${r.type.name}--${nI(r.toJSON())}` : r.type.name] = r.attrs;
    }
  }), t;
}, sh = (n, e, t, r) => {
  if (e instanceof at && e.nodeName !== t.type.name)
    throw new Error("node name mismatch!");
  if (r.mapping.set(e, t), e instanceof at) {
    const u = e.getAttributes(), h = t.attrs;
    for (const f in h)
      h[f] !== null ? u[f] !== h[f] && f !== "ychange" && e.setAttribute(f, h[f]) : e.removeAttribute(f);
    for (const f in u)
      h[f] === void 0 && e.removeAttribute(f);
  }
  const i = Fc(t), o = i.length, s = e.toArray(), l = s.length, a = nr(o, l);
  let c = 0, d = 0;
  for (; c < a; c++) {
    const u = s[c], h = i[c];
    if (!cc(r.mapping.get(u), h))
      if (Fs(u, h))
        r.mapping.set(u, h);
      else
        break;
  }
  for (; d + c < a; d++) {
    const u = s[l - d - 1], h = i[o - d - 1];
    if (!cc(r.mapping.get(u), h))
      if (Fs(u, h))
        r.mapping.set(u, h);
      else
        break;
  }
  n.transact(() => {
    for (; l - c - d > 0 && o - c - d > 0; ) {
      const h = s[c], f = i[c], p = s[l - d - 1], m = i[o - d - 1];
      if (h instanceof At && f instanceof Array)
        $1(h, f) || hI(h, f, r), c += 1;
      else {
        let g = h instanceof at && lh(h, f), y = p instanceof at && lh(p, m);
        if (g && y) {
          const _ = I0(
            /** @type {Y.XmlElement} */
            h,
            /** @type {PModel.Node} */
            f,
            r
          ), b = I0(
            /** @type {Y.XmlElement} */
            p,
            /** @type {PModel.Node} */
            m,
            r
          );
          _.foundMappedChild && !b.foundMappedChild ? y = !1 : !_.foundMappedChild && b.foundMappedChild || _.equalityFactor < b.equalityFactor ? g = !1 : y = !1;
        }
        g ? (sh(
          n,
          /** @type {Y.XmlFragment} */
          h,
          /** @type {PModel.Node} */
          f,
          r
        ), c += 1) : y ? (sh(
          n,
          /** @type {Y.XmlFragment} */
          p,
          /** @type {PModel.Node} */
          m,
          r
        ), d += 1) : (r.mapping.delete(e.get(c)), e.delete(c, 1), e.insert(c, [
          oh(f, r)
        ]), c += 1);
      }
    }
    const u = l - c - d;
    if (l === 1 && o === 0 && s[0] instanceof At ? (r.mapping.delete(s[0]), s[0].delete(0, s[0].length)) : u > 0 && (e.slice(c, c + u).forEach((h) => r.mapping.delete(h)), e.delete(c, u)), c + d < o) {
      const h = [];
      for (let f = c; f < o - d; f++)
        h.push(oh(i[f], r));
      e.insert(c, h);
    }
  }, ne);
}, lh = (n, e) => !(e instanceof Array) && n.nodeName === e.type.name;
let as = null;
const mI = () => {
  const n = (
    /** @type {Map<EditorView, Map<any, any>>} */
    as
  );
  as = null, n.forEach((e, t) => {
    const r = t.state.tr, i = ne.getState(t.state);
    i && i.binding && !i.binding.isDestroyed && (e.forEach((o, s) => {
      r.setMeta(s, o);
    }), t.dispatch(r));
  });
}, gI = (n, e, t) => {
  as || (as = /* @__PURE__ */ new Map(), vf(0, mI)), Bn(as, n, Kt).set(e, t);
}, Ns = (n, e, t) => {
  if (n === 0)
    return Kd(e, 0, e.length === 0 ? -1 : 0);
  let r = e._first === null ? null : (
    /** @type {Y.ContentType} */
    e._first.content.type
  );
  for (; r !== null && e !== r; ) {
    if (r instanceof At) {
      if (r._length >= n)
        return Kd(r, n, e.length === 0 ? -1 : 0);
      if (n -= r._length, r._item !== null && r._item.next !== null)
        r = /** @type {Y.ContentType} */
        r._item.next.content.type;
      else {
        do
          r = r._item === null ? null : r._item.parent, n--;
        while (r !== e && r !== null && r._item !== null && r._item.next === null);
        r !== null && r !== e && (r = r._item === null ? null : (
          /** @type {Y.ContentType} */
          /** @type Y.Item */
          r._item.next.content.type
        ));
      }
    } else {
      const i = (
        /** @type {any} */
        (t.get(r) || { nodeSize: 0 }).nodeSize
      );
      if (r._first !== null && n < i)
        r = /** @type {Y.ContentType} */
        r._first.content.type, n--;
      else {
        if (n === 1 && r._length === 0 && i > 1)
          return new As(r._item === null ? null : r._item.id, r._item === null ? xs(r) : null, null);
        if (n -= i, r._item !== null && r._item.next !== null)
          r = /** @type {Y.ContentType} */
          r._item.next.content.type;
        else {
          if (n === 0)
            return r = r._item === null ? r : r._item.parent, new As(r._item === null ? null : r._item.id, r._item === null ? xs(r) : null, null);
          do
            r = /** @type {Y.Item} */
            r._item.parent, n--;
          while (r !== e && /** @type {Y.Item} */
          r._item.next === null);
          r !== e && (r = /** @type {Y.ContentType} */
          /** @type {Y.Item} */
          /** @type {Y.Item} */
          r._item.next.content.type);
        }
      }
    }
    if (r === null)
      throw Ot();
    if (n === 0 && r.constructor !== At && r !== e)
      return bI(r._item.parent, r._item);
  }
  return Kd(e, e._length, e.length === 0 ? -1 : 0);
}, bI = (n, e) => {
  let t = null, r = null;
  return n._item === null ? r = xs(n) : t = j(n._item.id.client, n._item.id.clock), new As(t, r, e.id);
}, ci = (n, e, t, r) => {
  const i = HN(t, n);
  if (i === null || i.type !== e && !Ds(e, i.type._item))
    return null;
  let o = i.type, s = 0;
  if (o.constructor === At)
    s = i.index;
  else if (o._item === null || !o._item.deleted) {
    let l = o._first, a = 0;
    for (; a < o._length && a < i.index && l !== null; ) {
      if (!l.deleted) {
        const c = (
          /** @type {Y.ContentType} */
          l.content.type
        );
        a++, c instanceof At ? s += c._length : s += /** @type {any} */
        r.get(c).nodeSize;
      }
      l = /** @type {Y.Item} */
      l.right;
    }
    s += 1;
  }
  for (; o !== e && o._item !== null; ) {
    const l = o._item.parent;
    if (l._item === null || !l._item.deleted) {
      s += 1;
      let a = (
        /** @type {Y.AbstractType} */
        l._first
      );
      for (; a !== null; ) {
        const c = (
          /** @type {Y.ContentType} */
          a.content.type
        );
        if (c === o)
          break;
        a.deleted || (c instanceof At ? s += c._length : s += /** @type {any} */
        r.get(c).nodeSize), a = a.right;
      }
    }
    o = /** @type {Y.AbstractType} */
    l;
  }
  return s - 1;
}, yI = (n, e, t) => n !== e, _I = (n) => {
  const e = document.createElement("span");
  e.classList.add("ProseMirror-yjs-cursor"), e.setAttribute("style", `border-color: ${n.color}`);
  const t = document.createElement("div");
  t.setAttribute("style", `background-color: ${n.color}`), t.insertBefore(document.createTextNode(n.name), null);
  const r = document.createTextNode("⁠"), i = document.createTextNode("⁠");
  return e.insertBefore(r, null), e.insertBefore(t, null), e.insertBefore(i, null), e;
}, R1 = (n) => ({
  style: `background-color: ${n.color}70`,
  class: "ProseMirror-yjs-selection"
}), wI = /^#[0-9a-fA-F]{6}$/, L0 = (n, e, t, r, i) => {
  const o = ne.getState(n), s = o.doc, l = [];
  return o.snapshot != null || o.prevSnapshot != null || o.binding.mapping.size === 0 ? Q.create(n.doc, []) : (e.getStates().forEach((a, c) => {
    if (t(s.clientID, c, a) && a.cursor != null) {
      const d = a.user || {};
      d.color == null ? d.color = "#ffa500" : wI.test(d.color) || console.warn("A user uses an unsupported color format", d), d.name == null && (d.name = `User: ${c}`);
      let u = ci(
        s,
        o.type,
        ls(a.cursor.anchor),
        o.binding.mapping
      ), h = ci(
        s,
        o.type,
        ls(a.cursor.head),
        o.binding.mapping
      );
      if (u !== null && h !== null) {
        const f = fn(n.doc.content.size - 1, 0);
        u = nr(u, f), h = nr(h, f), l.push(
          se.widget(h, () => r(d, c), {
            key: c + "",
            side: 10
          })
        );
        const p = nr(u, h), m = fn(u, h);
        l.push(
          se.inline(p, m, i(d, c), {
            inclusiveEnd: !0,
            inclusiveStart: !1
          })
        );
      }
    }
  }), Q.create(n.doc, l));
}, kI = (n, {
  awarenessStateFilter: e = yI,
  cursorBuilder: t = _I,
  selectionBuilder: r = R1,
  getSelection: i = (s) => s.selection
} = {}, o = "cursor") => new G({
  key: Vo,
  state: {
    init(s, l) {
      return L0(
        l,
        n,
        e,
        t,
        r
      );
    },
    apply(s, l, a, c) {
      const d = ne.getState(c), u = s.getMeta(Vo);
      return d && d.isChangeOrigin || u && u.awarenessUpdated ? L0(
        c,
        n,
        e,
        t,
        r
      ) : l.map(s.mapping, s.doc);
    }
  },
  props: {
    decorations: (s) => Vo.getState(s)
  },
  view: (s) => {
    const l = () => {
      s.docView && gI(s, Vo, { awarenessUpdated: !0 });
    }, a = () => {
      const c = ne.getState(s.state), d = n.getLocalState() || {};
      if (s.hasFocus()) {
        const u = i(s.state), h = Ns(
          u.anchor,
          c.type,
          c.binding.mapping
        ), f = Ns(
          u.head,
          c.type,
          c.binding.mapping
        );
        (d.cursor == null || !C0(
          ls(d.cursor.anchor),
          h
        ) || !C0(
          ls(d.cursor.head),
          f
        )) && n.setLocalStateField(o, {
          anchor: h,
          head: f
        });
      } else d.cursor != null && ci(
        c.doc,
        c.type,
        ls(d.cursor.anchor),
        c.binding.mapping
      ) !== null && n.setLocalStateField(o, null);
    };
    return n.on("change", l), s.dom.addEventListener("focusin", a), s.dom.addEventListener("focusout", a), {
      update: a,
      destroy: () => {
        s.dom.removeEventListener("focusin", a), s.dom.removeEventListener("focusout", a), n.off("change", l), n.setLocalStateField(o, null);
      }
    };
  }
}), vI = (n) => {
  var e, t;
  return ((t = (e = Wt.getState(n)) == null ? void 0 : e.undoManager) == null ? void 0 : t.undo()) != null;
}, CI = (n) => {
  var e, t;
  return ((t = (e = Wt.getState(n)) == null ? void 0 : e.undoManager) == null ? void 0 : t.redo()) != null;
}, SI = (n, e) => {
  var t, r;
  return e == null ? (r = (t = Wt.getState(n)) == null ? void 0 : t.undoManager) == null ? void 0 : r.canUndo() : vI(n);
}, EI = (n, e) => {
  var t, r;
  return e == null ? (r = (t = Wt.getState(n)) == null ? void 0 : t.undoManager) == null ? void 0 : r.canRedo() : CI(n);
}, xI = /* @__PURE__ */ new Set(["paragraph"]), DI = (n, e) => !(n instanceof ie) || !(n.content instanceof gn) || !(n.content.type instanceof Lr || n.content.type instanceof at && e.has(n.content.type.nodeName)) || n.content.type._length === 0, AI = ({ protectedNodes: n = xI, trackedOrigins: e = [], undoManager: t = null } = {}) => new G({
  key: Wt,
  state: {
    init: (r, i) => {
      const o = ne.getState(i), s = t || new d1(o.type, {
        trackedOrigins: new Set([ne].concat(e)),
        deleteFilter: (l) => DI(l, n),
        captureTransaction: (l) => l.meta.get("addToHistory") !== !1
      });
      return {
        undoManager: s,
        prevSel: null,
        hasUndoOps: s.undoStack.length > 0,
        hasRedoOps: s.redoStack.length > 0
      };
    },
    apply: (r, i, o, s) => {
      const l = ne.getState(s).binding, a = i.undoManager, c = a.undoStack.length > 0, d = a.redoStack.length > 0;
      return l ? {
        undoManager: a,
        prevSel: ac(l, o),
        hasUndoOps: c,
        hasRedoOps: d
      } : c !== i.hasUndoOps || d !== i.hasRedoOps ? Object.assign({}, i, {
        hasUndoOps: a.undoStack.length > 0,
        hasRedoOps: a.redoStack.length > 0
      }) : i;
    }
  },
  view: (r) => {
    const i = ne.getState(r.state), o = Wt.getState(r.state).undoManager;
    return o.on("stack-item-added", ({ stackItem: s }) => {
      const l = i.binding;
      l && s.meta.set(l, Wt.getState(r.state).prevSel);
    }), o.on("stack-item-popped", ({ stackItem: s }) => {
      const l = i.binding;
      l && (l.beforeTransactionSelection = s.meta.get(l) || l.beforeTransactionSelection);
    }), {
      destroy: () => {
        o.destroy();
      }
    };
  }
});
function TI(n = {}) {
  return new G({
    view(e) {
      return new MI(e, n);
    }
  });
}
class MI {
  constructor(e, t) {
    var r;
    this.editorView = e, this.cursorPos = null, this.element = null, this.timeout = -1, this.width = (r = t.width) !== null && r !== void 0 ? r : 1, this.color = t.color === !1 ? void 0 : t.color || "black", this.class = t.class, this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((i) => {
      let o = (s) => {
        this[i](s);
      };
      return e.dom.addEventListener(i, o), { name: i, handler: o };
    });
  }
  destroy() {
    this.handlers.forEach(({ name: e, handler: t }) => this.editorView.dom.removeEventListener(e, t));
  }
  update(e, t) {
    this.cursorPos != null && t.doc != e.state.doc && (this.cursorPos > e.state.doc.content.size ? this.setCursor(null) : this.updateOverlay());
  }
  setCursor(e) {
    e != this.cursorPos && (this.cursorPos = e, e == null ? (this.element.parentNode.removeChild(this.element), this.element = null) : this.updateOverlay());
  }
  updateOverlay() {
    let e = this.editorView.state.doc.resolve(this.cursorPos), t = !e.parent.inlineContent, r, i = this.editorView.dom, o = i.getBoundingClientRect(), s = o.width / i.offsetWidth, l = o.height / i.offsetHeight;
    if (t) {
      let u = e.nodeBefore, h = e.nodeAfter;
      if (u || h) {
        let f = this.editorView.nodeDOM(this.cursorPos - (u ? u.nodeSize : 0));
        if (f) {
          let p = f.getBoundingClientRect(), m = u ? p.bottom : p.top;
          u && h && (m = (m + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2);
          let g = this.width / 2 * l;
          r = { left: p.left, right: p.right, top: m - g, bottom: m + g };
        }
      }
    }
    if (!r) {
      let u = this.editorView.coordsAtPos(this.cursorPos), h = this.width / 2 * s;
      r = { left: u.left - h, right: u.left + h, top: u.top, bottom: u.bottom };
    }
    let a = this.editorView.dom.offsetParent;
    this.element || (this.element = a.appendChild(document.createElement("div")), this.class && (this.element.className = this.class), this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;", this.color && (this.element.style.backgroundColor = this.color)), this.element.classList.toggle("prosemirror-dropcursor-block", t), this.element.classList.toggle("prosemirror-dropcursor-inline", !t);
    let c, d;
    if (!a || a == document.body && getComputedStyle(a).position == "static")
      c = -pageXOffset, d = -pageYOffset;
    else {
      let u = a.getBoundingClientRect(), h = u.width / a.offsetWidth, f = u.height / a.offsetHeight;
      c = u.left - a.scrollLeft * h, d = u.top - a.scrollTop * f;
    }
    this.element.style.left = (r.left - c) / s + "px", this.element.style.top = (r.top - d) / l + "px", this.element.style.width = (r.right - r.left) / s + "px", this.element.style.height = (r.bottom - r.top) / l + "px";
  }
  scheduleRemoval(e) {
    clearTimeout(this.timeout), this.timeout = setTimeout(() => this.setCursor(null), e);
  }
  dragover(e) {
    if (!this.editorView.editable)
      return;
    let t = this.editorView.posAtCoords({ left: e.clientX, top: e.clientY }), r = t && t.inside >= 0 && this.editorView.state.doc.nodeAt(t.inside), i = r && r.type.spec.disableDropCursor, o = typeof i == "function" ? i(this.editorView, t, e) : i;
    if (t && !o) {
      let s = t.pos;
      if (this.editorView.dragging && this.editorView.dragging.slice) {
        let l = Py(this.editorView.state.doc, s, this.editorView.dragging.slice);
        l != null && (s = l);
      }
      this.setCursor(s), this.scheduleRemoval(5e3);
    }
  }
  dragend() {
    this.scheduleRemoval(20);
  }
  drop() {
    this.scheduleRemoval(20);
  }
  dragleave(e) {
    this.editorView.dom.contains(e.relatedTarget) || this.setCursor(null);
  }
}
const OI = {
  slash_menu: {
    heading: {
      title: "Heading 1",
      subtext: "Top-level heading",
      aliases: ["h", "heading1", "h1"],
      group: "Headings"
    },
    heading_2: {
      title: "Heading 2",
      subtext: "Key section heading",
      aliases: ["h2", "heading2", "subheading"],
      group: "Headings"
    },
    heading_3: {
      title: "Heading 3",
      subtext: "Subsection and group heading",
      aliases: ["h3", "heading3", "subheading"],
      group: "Headings"
    },
    heading_4: {
      title: "Heading 4",
      subtext: "Minor subsection heading",
      aliases: ["h4", "heading4", "subheading4"],
      group: "Subheadings"
    },
    heading_5: {
      title: "Heading 5",
      subtext: "Small subsection heading",
      aliases: ["h5", "heading5", "subheading5"],
      group: "Subheadings"
    },
    heading_6: {
      title: "Heading 6",
      subtext: "Lowest-level heading",
      aliases: ["h6", "heading6", "subheading6"],
      group: "Subheadings"
    },
    toggle_heading: {
      title: "Toggle Heading 1",
      subtext: "Toggleable top-level heading",
      aliases: ["h", "heading1", "h1", "collapsable"],
      group: "Subheadings"
    },
    toggle_heading_2: {
      title: "Toggle Heading 2",
      subtext: "Toggleable key section heading",
      aliases: ["h2", "heading2", "subheading", "collapsable"],
      group: "Subheadings"
    },
    toggle_heading_3: {
      title: "Toggle Heading 3",
      subtext: "Toggleable subsection and group heading",
      aliases: ["h3", "heading3", "subheading", "collapsable"],
      group: "Subheadings"
    },
    quote: {
      title: "Quote",
      subtext: "Quote or excerpt",
      aliases: ["quotation", "blockquote", "bq"],
      group: "Basic blocks"
    },
    toggle_list: {
      title: "Toggle List",
      subtext: "List with hideable sub-items",
      aliases: ["li", "list", "toggleList", "toggle list", "collapsable list"],
      group: "Basic blocks"
    },
    numbered_list: {
      title: "Numbered List",
      subtext: "List with ordered items",
      aliases: ["ol", "li", "list", "numberedlist", "numbered list"],
      group: "Basic blocks"
    },
    bullet_list: {
      title: "Bullet List",
      subtext: "List with unordered items",
      aliases: ["ul", "li", "list", "bulletlist", "bullet list"],
      group: "Basic blocks"
    },
    check_list: {
      title: "Check List",
      subtext: "List with checkboxes",
      aliases: [
        "ul",
        "li",
        "list",
        "checklist",
        "check list",
        "checked list",
        "checkbox"
      ],
      group: "Basic blocks"
    },
    paragraph: {
      title: "Paragraph",
      subtext: "The body of your document",
      aliases: ["p", "paragraph"],
      group: "Basic blocks"
    },
    code_block: {
      title: "Code Block",
      subtext: "Code block with syntax highlighting",
      aliases: ["code", "pre"],
      group: "Basic blocks"
    },
    page_break: {
      title: "Page Break",
      subtext: "Page separator",
      aliases: ["page", "break", "separator"],
      group: "Basic blocks"
    },
    table: {
      title: "Table",
      subtext: "Table with editable cells",
      aliases: ["table"],
      group: "Advanced"
    },
    image: {
      title: "Image",
      subtext: "Resizable image with caption",
      aliases: [
        "image",
        "imageUpload",
        "upload",
        "img",
        "picture",
        "media",
        "url"
      ],
      group: "Media"
    },
    video: {
      title: "Video",
      subtext: "Resizable video with caption",
      aliases: [
        "video",
        "videoUpload",
        "upload",
        "mp4",
        "film",
        "media",
        "url"
      ],
      group: "Media"
    },
    audio: {
      title: "Audio",
      subtext: "Embedded audio with caption",
      aliases: [
        "audio",
        "audioUpload",
        "upload",
        "mp3",
        "sound",
        "media",
        "url"
      ],
      group: "Media"
    },
    file: {
      title: "File",
      subtext: "Embedded file",
      aliases: ["file", "upload", "embed", "media", "url"],
      group: "Media"
    },
    emoji: {
      title: "Emoji",
      subtext: "Search for and insert an emoji",
      aliases: ["emoji", "emote", "emotion", "face"],
      group: "Others"
    }
  },
  placeholders: {
    default: "Enter text or type '/' for commands",
    heading: "Heading",
    toggleListItem: "Toggle",
    bulletListItem: "List",
    numberedListItem: "List",
    checkListItem: "List",
    emptyDocument: void 0,
    new_comment: "Write a comment...",
    edit_comment: "Edit comment...",
    comment_reply: "Add comment..."
  },
  file_blocks: {
    image: {
      add_button_text: "Add image"
    },
    video: {
      add_button_text: "Add video"
    },
    audio: {
      add_button_text: "Add audio"
    },
    file: {
      add_button_text: "Add file"
    }
  },
  // from react package:
  side_menu: {
    add_block_label: "Add block",
    drag_handle_label: "Open block menu"
  },
  drag_handle: {
    delete_menuitem: "Delete",
    colors_menuitem: "Colors",
    header_row_menuitem: "Header row",
    header_column_menuitem: "Header column"
  },
  table_handle: {
    delete_column_menuitem: "Delete column",
    delete_row_menuitem: "Delete row",
    add_left_menuitem: "Add column left",
    add_right_menuitem: "Add column right",
    add_above_menuitem: "Add row above",
    add_below_menuitem: "Add row below",
    split_cell_menuitem: "Split cell",
    merge_cells_menuitem: "Merge cells",
    background_color_menuitem: "Background color"
  },
  suggestion_menu: {
    no_items_title: "No items found"
  },
  color_picker: {
    text_title: "Text",
    background_title: "Background",
    colors: {
      default: "Default",
      gray: "Gray",
      brown: "Brown",
      red: "Red",
      orange: "Orange",
      yellow: "Yellow",
      green: "Green",
      blue: "Blue",
      purple: "Purple",
      pink: "Pink"
    }
  },
  formatting_toolbar: {
    bold: {
      tooltip: "Bold",
      secondary_tooltip: "Mod+B"
    },
    italic: {
      tooltip: "Italic",
      secondary_tooltip: "Mod+I"
    },
    underline: {
      tooltip: "Underline",
      secondary_tooltip: "Mod+U"
    },
    strike: {
      tooltip: "Strike",
      secondary_tooltip: "Mod+Shift+S"
    },
    code: {
      tooltip: "Code",
      secondary_tooltip: ""
    },
    colors: {
      tooltip: "Colors"
    },
    link: {
      tooltip: "Create link",
      secondary_tooltip: "Mod+K"
    },
    file_caption: {
      tooltip: "Edit caption",
      input_placeholder: "Edit caption"
    },
    file_replace: {
      tooltip: {
        image: "Replace image",
        video: "Replace video",
        audio: "Replace audio",
        file: "Replace file"
      }
    },
    file_rename: {
      tooltip: {
        image: "Rename image",
        video: "Rename video",
        audio: "Rename audio",
        file: "Rename file"
      },
      input_placeholder: {
        image: "Rename image",
        video: "Rename video",
        audio: "Rename audio",
        file: "Rename file"
      }
    },
    file_download: {
      tooltip: {
        image: "Download image",
        video: "Download video",
        audio: "Download audio",
        file: "Download file"
      }
    },
    file_delete: {
      tooltip: {
        image: "Delete image",
        video: "Delete video",
        audio: "Delete audio",
        file: "Delete file"
      }
    },
    file_preview_toggle: {
      tooltip: "Toggle preview"
    },
    nest: {
      tooltip: "Nest block",
      secondary_tooltip: "Tab"
    },
    unnest: {
      tooltip: "Unnest block",
      secondary_tooltip: "Shift+Tab"
    },
    align_left: {
      tooltip: "Align text left"
    },
    align_center: {
      tooltip: "Align text center"
    },
    align_right: {
      tooltip: "Align text right"
    },
    align_justify: {
      tooltip: "Justify text"
    },
    table_cell_merge: {
      tooltip: "Merge cells"
    },
    comment: {
      tooltip: "Add comment"
    }
  },
  file_panel: {
    upload: {
      title: "Upload",
      file_placeholder: {
        image: "Upload image",
        video: "Upload video",
        audio: "Upload audio",
        file: "Upload file"
      },
      upload_error: "Error: Upload failed"
    },
    embed: {
      title: "Embed",
      embed_button: {
        image: "Embed image",
        video: "Embed video",
        audio: "Embed audio",
        file: "Embed file"
      },
      url_placeholder: "Enter URL"
    }
  },
  link_toolbar: {
    delete: {
      tooltip: "Remove link"
    },
    edit: {
      text: "Edit link",
      tooltip: "Edit"
    },
    open: {
      tooltip: "Open in new tab"
    },
    form: {
      title_placeholder: "Edit title",
      url_placeholder: "Edit URL"
    }
  },
  comments: {
    edited: "edited",
    save_button_text: "Save",
    cancel_button_text: "Cancel",
    actions: {
      add_reaction: "Add reaction",
      resolve: "Resolve",
      edit_comment: "Edit comment",
      delete_comment: "Delete comment",
      more_actions: "More actions"
    },
    reactions: {
      reacted_by: "Reacted by"
    },
    sidebar: {
      marked_as_resolved: "Marked as resolved",
      more_replies: (n) => `${n} more replies`
    }
  },
  generic: {
    ctrl_shortcut: "Ctrl"
  }
};
var FI = Object.defineProperty, NI = (n, e, t) => e in n ? FI(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t, E = (n, e, t) => NI(n, typeof e != "symbol" ? e + "" : e, t);
function $I(n, e = JSON.stringify) {
  const t = {};
  return n.filter((r) => {
    const i = e(r);
    return Object.prototype.hasOwnProperty.call(t, i) ? !1 : t[i] = !0;
  });
}
function II(n) {
  const e = n.filter(
    (t, r) => n.indexOf(t) !== r
  );
  return $I(e);
}
const Nc = he.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: !1,
      generateID: () => {
        if (typeof window < "u" && window.__TEST_OPTIONS) {
          const n = window.__TEST_OPTIONS;
          return n.mockID === void 0 ? n.mockID = 0 : n.mockID++, n.mockID.toString();
        }
        return lw();
      },
      filterTransaction: null
    };
  },
  addGlobalAttributes() {
    return [
      {
        types: this.options.types,
        attributes: {
          [this.options.attributeName]: {
            default: null,
            parseHTML: (n) => n.getAttribute(`data-${this.options.attributeName}`),
            renderHTML: (n) => {
              const e = {
                [`data-${this.options.attributeName}`]: n[this.options.attributeName]
              };
              return this.options.setIdAttribute ? {
                ...e,
                id: n[this.options.attributeName]
              } : e;
            }
          }
        }
      }
    ];
  },
  // 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 n = null, e = !1;
    return [
      new G({
        key: new te("uniqueID"),
        appendTransaction: (t, r, i) => {
          const o = t.some((f) => f.docChanged) && !r.doc.eq(i.doc), s = this.options.filterTransaction && t.some((f) => {
            let p, m;
            return !(!((m = (p = this.options).filterTransaction) === null || m === void 0) && m.call(p, f));
          });
          if (!o || s)
            return;
          const { tr: l } = i, { types: a, attributeName: c, generateID: d } = this.options, u = Zh(
            r.doc,
            t
          ), { mapping: h } = u;
          if (Z_(u).forEach(({ newRange: f }) => {
            const p = Y_(
              i.doc,
              f,
              (y) => a.includes(y.type.name)
            ), m = p.map(({ node: y }) => y.attrs[c]).filter((y) => y !== null), g = II(m);
            p.forEach(({ node: y, pos: _ }) => {
              let b;
              const k = (b = l.doc.nodeAt(_)) === null || b === void 0 ? void 0 : b.attrs[c];
              if (k === null) {
                const w = r.doc.type.createAndFill().content;
                if (r.doc.content.findDiffStart(w) === null) {
                  const x = JSON.parse(
                    JSON.stringify(i.doc.toJSON())
                  );
                  if (x.content[0].content[0].attrs.id = "initialBlockId", JSON.stringify(x.content) === JSON.stringify(w.toJSON())) {
                    l.setNodeMarkup(_, void 0, {
                      ...y.attrs,
                      [c]: "initialBlockId"
                    });
                    return;
                  }
                }
                l.setNodeMarkup(_, void 0, {
                  ...y.attrs,
                  [c]: d()
                });
                return;
              }
              const { deleted: C } = h.invert().mapResult(_);
              C && g.includes(k) && l.setNodeMarkup(_, void 0, {
                ...y.attrs,
                [c]: d()
              });
            });
          }), !!l.steps.length)
            return l;
        },
        // we register a global drag handler to track the current drag source element
        view(t) {
          const r = (i) => {
            let o;
            n = !((o = t.dom.parentElement) === null || o === void 0) && o.contains(i.target) ? t.dom.parentElement : null;
          };
          return window.addEventListener("dragstart", r), {
            destroy() {
              window.removeEventListener("dragstart", r);
            }
          };
        },
        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: (t, r) => {
              let i;
              return n !== t.dom.parentElement || ((i = r.dataTransfer) === null || i === void 0 ? void 0 : i.effectAllowed) === "copy" ? e = !0 : e = !1, n = null, !1;
            },
            // always create new ids on pasted content
            paste: () => (e = !0, !1)
          },
          // we’ll remove ids for every pasted node
          // so we can create a new one within `appendTransaction`
          transformPasted: (t) => {
            if (!e)
              return t;
            const { types: r, attributeName: i } = this.options, o = (s) => {
              const l = [];
              return s.forEach((a) => {
                if (a.isText) {
                  l.push(a);
                  return;
                }
                if (!r.includes(a.type.name)) {
                  l.push(a.copy(o(a.content)));
                  return;
                }
                const c = a.type.create(
                  {
                    ...a.attrs,
                    [i]: null
                  },
                  o(a.content),
                  a.marks
                );
                l.push(c);
              }), A.from(l);
            };
            return e = !1, new O(
              o(t.content),
              t.openStart,
              t.openEnd
            );
          }
        }
      })
    ];
  }
});
function R0(n) {
  return n.type === "link";
}
function B1(n) {
  return typeof n != "string" && n.type === "link";
}
function mo(n) {
  return typeof n != "string" && n.type === "text";
}
function ah(n) {
  var e, t, r, i, o;
  return Bf(n) ? { ...n } : $s(n) ? {
    type: "tableCell",
    content: [].concat(n.content),
    props: {
      backgroundColor: ((e = n.props) == null ? void 0 : e.backgroundColor) ?? "default",
      textColor: ((t = n.props) == null ? void 0 : t.textColor) ?? "default",
      textAlignment: ((r = n.props) == null ? void 0 : r.textAlignment) ?? "left",
      colspan: ((i = n.props) == null ? void 0 : i.colspan) ?? 1,
      rowspan: ((o = n.props) == null ? void 0 : o.rowspan) ?? 1
    }
  } : {
    type: "tableCell",
    content: [].concat(n),
    props: {
      backgroundColor: "default",
      textColor: "default",
      textAlignment: "left",
      colspan: 1,
      rowspan: 1
    }
  };
}
function $s(n) {
  return n != null && typeof n != "string" && !Array.isArray(n) && n.type === "tableCell";
}
function Bf(n) {
  return $s(n) && n.props !== void 0 && n.content !== void 0;
}
function Is(n) {
  return Bf(n) ? n.props.colspan ?? 1 : 1;
}
function ch(n) {
  return Bf(n) ? n.props.rowspan ?? 1 : 1;
}
class In extends Error {
  constructor(e) {
    super(`Unreachable case: ${e}`);
  }
}
function Rr(...n) {
  return [
    // Converts to & from set to remove duplicates.
    ...new Set(
      n.filter((e) => e).join(" ").split(" ")
    )
  ].join(" ");
}
function Ft(n, e, t, r) {
  const i = document.createElement("div");
  i.className = Rr(
    "bn-block-content",
    t.class
  ), i.setAttribute("data-content-type", n);
  for (const [s, l] of Object.entries(t))
    s !== "class" && i.setAttribute(s, l);
  const o = document.createElement(e);
  o.className = Rr(
    "bn-inline-content",
    r.class
  );
  for (const [s, l] of Object.entries(
    r
  ))
    s !== "class" && o.setAttribute(s, l);
  return i.appendChild(o), {
    dom: i,
    contentDOM: o
  };
}
const B0 = (n, e) => {
  let t = Di(n, e.pmSchema);
  t.type.name === "blockContainer" && (t = t.firstChild);
  const r = e.pmSchema.nodes[t.type.name].spec.toDOM;
  if (r === void 0)
    throw new Error(
      "This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`."
    );
  const i = r(t);
  if (typeof i != "object" || !("dom" in i))
    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 i;
};
function LI(n) {
  const e = n.querySelectorAll("p");
  if (e.length > 1) {
    const t = e[0];
    for (let r = 1; r < e.length; r++) {
      const i = e[r];
      t.innerHTML += "<br>" + i.innerHTML, i.remove();
    }
  }
}
const Fe = {
  backgroundColor: {
    default: "default"
  },
  textColor: {
    default: "default"
  },
  textAlignment: {
    default: "left",
    values: ["left", "center", "right", "justify"]
  }
}, P1 = ["backgroundColor", "textColor"];
function dh(n) {
  return "data-" + n.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
function $c(n) {
  const e = {};
  return Object.entries(n).filter(([t, r]) => !P1.includes(t)).forEach(([t, r]) => {
    e[t] = {
      default: r.default,
      keepOnSplit: !0,
      // 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: (i) => {
        const o = i.getAttribute(dh(t));
        if (o === null)
          return null;
        if (r.default === void 0 && r.type === "boolean" || r.default !== void 0 && typeof r.default == "boolean")
          return o === "true" ? !0 : o === "false" ? !1 : null;
        if (r.default === void 0 && r.type === "number" || r.default !== void 0 && typeof r.default == "number") {
          const s = parseFloat(o);
          return !Number.isNaN(s) && Number.isFinite(s) ? s : null;
        }
        return o;
      },
      renderHTML: (i) => i[t] !== r.default ? {
        [dh(t)]: i[t]
      } : {}
    };
  }), e;
}
function Pf(n, e, t, r) {
  if (typeof n == "boolean")
    throw new Error(
      "Cannot find node position as getPos is a boolean, not a function."
    );
  const i = n(), o = t.state.doc.resolve(i).node().attrs.id;
  if (!o)
    throw new Error("Block doesn't have id");
  const s = e.getBlock(o);
  if (s.type !== r)
    throw new Error("Block type does not match");
  return s;
}
function Ll(n, e, t, r, i = !1, o) {
  const s = document.createElement("div");
  if (o !== void 0)
    for (const [l, a] of Object.entries(o))
      l !== "class" && s.setAttribute(l, a);
  s.className = Rr(
    "bn-block-content",
    (o == null ? void 0 : o.class) || ""
  ), s.setAttribute("data-content-type", e);
  for (const [l, a] of Object.entries(t)) {
    const c = r[l].default;
    !P1.includes(l) && a !== c && s.setAttribute(dh(l), a);
  }
  return i && s.setAttribute("data-file-block", ""), s.appendChild(n.dom), n.contentDOM !== void 0 && (n.contentDOM.className = Rr(
    "bn-inline-content",
    n.contentDOM.className
  )), {
    ...n,
    dom: s
  };
}
function bn(n) {
  return Mt.create(n);
}
function z1(n, e) {
  return {
    config: n,
    implementation: e
  };
}
function ar(n, e, t) {
  return z1(
    {
      type: n.name,
      content: n.config.content === "inline*" ? "inline" : n.config.content === "tableRow+" ? "table" : "none",
      propSchema: e
    },
    {
      node: n,
      requiredExtensions: t,
      toInternalHTML: B0,
      toExternalHTML: B0
      // parse: () => undefined, // parse rules are in node already
    }
  );
}
function H1(n) {
  return Object.fromEntries(
    Object.entries(n).map(([e, t]) => [e, t.config])
  );
}
function RI(n, e) {
  n.stopEvent = (t) => (t.type === "mousedown" && setTimeout(() => {
    e.view.dom.blur();
  }, 10), !0);
}
function BI(n, e) {
  const t = [
    {
      tag: "[data-content-type=" + n.type + "]",
      contentElement: ".bn-inline-content"
    }
  ];
  return e && t.push({
    tag: "*",
    getAttrs(r) {
      if (typeof r == "string")
        return !1;
      const i = e == null ? void 0 : e(r);
      return i === void 0 ? !1 : i;
    }
  }), t;
}
function Ks(n, e) {
  const t = bn({
    name: n.type,
    content: n.content === "inline" ? "inline*" : "",
    group: "blockContent",
    selectable: n.isSelectable ?? !0,
    isolating: !0,
    addAttributes() {
      return $c(n.propSchema);
    },
    parseHTML() {
      return BI(n, e.parse);
    },
    renderHTML({ HTMLAttributes: r }) {
      const i = document.createElement("div");
      return Ll(
        {
          dom: i,
          contentDOM: n.content === "inline" ? i : void 0
        },
        n.type,
        {},
        n.propSchema,
        n.isFileBlock,
        r
      );
    },
    addNodeView() {
      return ({ getPos: r }) => {
        var i;
        const o = this.options.editor, s = Pf(
          r,
          o,
          this.editor,
          n.type
        ), l = ((i = this.options.domAttributes) == null ? void 0 : i.blockContent) || {}, a = e.render(s, o), c = Ll(
          a,
          s.type,
          s.props,
          n.propSchema,
          n.isFileBlock,
          l
        );
        return n.isSelectable === !1 && RI(c, this.editor), c;
      };
    }
  });
  if (t.name !== n.type)
    throw new Error(
      "Node name does not match block type. This is a bug in BlockNote."
    );
  return z1(n, {
    node: t,
    toInternalHTML: (r, i) => {
      var o;
      const s = ((o = t.options.domAttributes) == null ? void 0 : o.blockContent) || {}, l = e.render(r, i);
      return Ll(
        l,
        r.type,
        r.props,
        n.propSchema,
        n.isFileBlock,
        s
      );
    },
    // TODO: this should not have wrapInBlockStructure and generally be a lot simpler
    // post-processing in externalHTMLExporter should not be necessary
    toExternalHTML: (r, i) => {
      var o, s;
      const l = ((o = t.options.domAttributes) == null ? void 0 : o.blockContent) || {};
      let a = (s = e.toExternalHTML) == null ? void 0 : s.call(
        e,
        r,
        i
      );
      return a === void 0 && (a = e.render(r, i)), Ll(
        a,
        r.type,
        r.props,
        n.propSchema,
        l
      );
    }
  });
}
function or(n, e) {
  const t = n.resolve(e);
  if (t.nodeAfter && t.nodeAfter.type.isInGroup("bnBlock"))
    return {
      posBeforeNode: t.pos,
      node: t.nodeAfter
    };
  let r = t.depth, i = t.node(r);
  for (; r > 0; ) {
    if (i.type.isInGroup("bnBlock"))
      return {
        posBeforeNode: t.before(r),
        node: i
      };
    r--, i = t.node(r);
  }
  const o = [];
  n.descendants((l, a) => {
    l.type.isInGroup("bnBlock") && o.push(a);
  }), console.warn(`Position ${e} is not within a blockContainer node.`);
  const s = n.resolve(
    o.find((l) => l >= e) || o[o.length - 1]
  );
  return {
    posBeforeNode: s.pos,
    node: s.nodeAfter
  };
}
function zf(n, e) {
  if (!n.type.isInGroup("bnBlock"))
    throw new Error(
      `Attempted to get bnBlock node at position but found node of different type ${n.type.name}`
    );
  const t = n, r = e, i = r + t.nodeSize, o = {
    node: t,
    beforePos: r,
    afterPos: i
  };
  if (t.type.name === "blockContainer") {
    let s, l;
    if (t.forEach((a, c) => {
      if (a.type.spec.group === "blockContent") {
        const d = a, u = r + c + 1, h = u + a.nodeSize;
        s = {
          node: d,
          beforePos: u,
          afterPos: h
        };
      } else if (a.type.name === "blockGroup") {
        const d = a, u = r + c + 1, h = u + a.nodeSize;
        l = {
          node: d,
          beforePos: u,
          afterPos: h
        };
      }
    }), !s)
      throw new Error(
        `blockContainer node does not contain a blockContent node in its children: ${t}`
      );
    return {
      isBlockContainer: !0,
      bnBlock: o,
      blockContent: s,
      childContainer: l,
      blockNoteType: s.node.type.name
    };
  } else {
    if (!o.node.type.isInGroup("childContainer"))
      throw new Error(
        `bnBlock node is not in the childContainer group: ${o.node}`
      );
    return {
      isBlockContainer: !1,
      bnBlock: o,
      childContainer: o,
      blockNoteType: o.node.type.name
    };
  }
}
function Br(n) {
  return zf(n.node, n.posBeforeNode);
}
function Js(n) {
  if (!n.nodeAfter)
    throw new Error(
      `Attempted to get blockContainer node at position ${n.pos} but a node at this position does not exist`
    );
  return zf(n.nodeAfter, n.pos);
}
function ge(n) {
  const e = or(n.doc, n.selection.anchor);
  return Br(e);
}
function Ic(n) {
  const e = or(n.doc, n.selection.anchor);
  return Br(e);
}
function Ue(n) {
  return "doc" in n ? n.doc.type.schema : n.type.schema;
}
function V1(n) {
  return n.cached.blockNoteEditor;
}
function Ys(n) {
  return V1(n).schema;
}
function Hf(n) {
  return Ys(n).blockSchema;
}
function Vf(n) {
  return Ys(n).inlineContentSchema;
}
function Co(n) {
  return Ys(n).styleSchema;
}
function Uf(n) {
  return V1(n).blockCache;
}
function U1(n, e, t) {
  var r, i;
  const o = {
    type: "tableContent",
    columnWidths: [],
    headerRows: void 0,
    headerCols: void 0,
    rows: []
  }, s = [];
  n.content.forEach((l, a, c) => {
    const d = {
      cells: []
    };
    c === 0 && l.content.forEach((u) => {
      let h = u.attrs.colwidth;
      h == null && (h = new Array(u.attrs.colspan ?? 1).fill(void 0)), o.columnWidths.push(...h);
    }), d.cells = l.content.content.map((u, h) => (s[c] || (s[c] = []), s[c][h] = u.type.name === "tableHeader", {
      type: "tableCell",
      content: u.content.content.map(
        (f) => Lc(f, e, t)
      ).reduce(
        (f, p) => {
          if (!f.length)
            return p;
          const m = f[f.length - 1], g = p[0];
          return g && mo(m) && mo(g) && JSON.stringify(m.styles) === JSON.stringify(g.styles) ? (m.text += `
` + g.text, f.push(...p.slice(1)), f) : (f.push(...p), f);
        },
        []
      ),
      props: {
        colspan: u.attrs.colspan,
        rowspan: u.attrs.rowspan,
        backgroundColor: u.attrs.backgroundColor,
        textColor: u.attrs.textColor,
        textAlignment: u.attrs.textAlignment
      }
    })), o.rows.push(d);
  });
  for (let l = 0; l < s.length; l++)
    (r = s[l]) != null && r.every((a) => a) && (o.headerRows = (o.headerRows ?? 0) + 1);
  for (let l = 0; l < ((i = s[0]) == null ? void 0 : i.length); l++)
    s != null && s.every((a) => a[l]) && (o.headerCols = (o.headerCols ?? 0) + 1);
  return o;
}
function Lc(n, e, t) {
  const r = [];
  let i;
  return n.content.forEach((o) => {
    if (o.type.name === "hardBreak") {
      if (i)
        if (mo(i))
          i.text += `
`;
        else if (R0(i))
          i.content[i.content.length - 1].text += `
`;
        else
          throw new Error("unexpected");
      else
        i = {
          type: "text",
          text: `
`,
          styles: {}
        };
      return;
    }
    if (o.type.name !== "link" && o.type.name !== "text") {
      if (!e[o.type.name]) {
        console.warn("unrecognized inline content type", o.type.name);
        return;
      }
      i && (r.push(i), i = void 0), r.push(
        PI(o, e, t)
      );
      return;
    }
    const s = {};
    let l;
    for (const a of o.marks)
      if (a.type.name === "link")
        l = a;
      else {
        const c = t[a.type.name];
        if (!c) {
          if (a.type.spec.blocknoteIgnore)
            continue;
          throw new Error(`style ${a.type.name} not found in styleSchema`);
        }
        if (c.propSchema === "boolean")
          s[c.type] = !0;
        else if (c.propSchema === "string")
          s[c.type] = a.attrs.stringValue;
        else
          throw new In(c.propSchema);
      }
    i ? mo(i) ? l ? (r.push(i), i = {
      type: "link",
      href: l.attrs.href,
      content: [
        {
          type: "text",
          text: o.textContent,
          styles: s
        }
      ]
    }) : JSON.stringify(i.styles) === JSON.stringify(s) ? i.text += o.textContent : (r.push(i), i = {
      type: "text",
      text: o.textContent,
      styles: s
    }) : R0(i) && (l ? i.href === l.attrs.href ? JSON.stringify(
      i.content[i.content.length - 1].styles
    ) === JSON.stringify(s) ? i.content[i.content.length - 1].text += o.textContent : i.content.push({
      type: "text",
      text: o.textContent,
      styles: s
    }) : (r.push(i), i = {
      type: "link",
      href: l.attrs.href,
      content: [
        {
          type: "text",
          text: o.textContent,
          styles: s
        }
      ]
    }) : (r.push(i), i = {
      type: "text",
      text: o.textContent,
      styles: s
    })) : l ? i = {
      type: "link",
      href: l.attrs.href,
      content: [
        {
          type: "text",
          text: o.textContent,
          styles: s
        }
      ]
    } : i = {
      type: "text",
      text: o.textContent,
      styles: s
    };
  }), i && r.push(i), r;
}
function PI(n, e, t) {
  if (n.type.name === "text" || n.type.name === "link")
    throw new Error("unexpected");
  const r = {}, i = e[n.type.name];
  for (const [s, l] of Object.entries(n.attrs)) {
    if (!i)
      throw Error("ic node is of an unrecognized type: " + n.type.name);
    const a = i.propSchema;
    s in a && (r[s] = l);
  }
  let o;
  return i.content === "styled" ? o = Lc(
    n,
    e,
    t
  ) : o = void 0, {
    type: n.type.name,
    props: r,
    content: o
  };
}
function Se(n, e, t = Hf(e), r = Vf(e), i = Co(e), o = Uf(e)) {
  var s;
  if (!n.type.isInGroup("bnBlock"))
    throw Error("Node should be a bnBlock, but is instead: " + n.type.name);
  const l = o == null ? void 0 : o.get(n);
  if (l)
    return l;
  const a = zf(n, 0);
  let c = a.bnBlock.node.attrs.id;
  c === null && (c = Nc.options.generateID());
  const d = t[a.blockNoteType];
  if (!d)
    throw Error("Block is of an unrecognized type: " + a.blockNoteType);
  const u = {};
  for (const [g, y] of Object.entries({
    ...n.attrs,
    ...a.isBlockContainer ? a.blockContent.node.attrs : {}
  })) {
    const _ = d.propSchema;
    g in _ && !(_[g].default === void 0 && y === void 0) && (u[g] = y);
  }
  const h = t[a.blockNoteType], f = [];
  (s = a.childContainer) == null || s.node.forEach((g) => {
    f.push(
      Se(
        g,
        e,
        t,
        r,
        i,
        o
      )
    );
  });
  let p;
  if (h.content === "inline") {
    if (!a.isBlockContainer)
      throw new Error("impossible");
    p = Lc(
      a.blockContent.node,
      r,
      i
    );
  } else if (h.content === "table") {
    if (!a.isBlockContainer)
      throw new Error("impossible");
    p = U1(
      a.blockContent.node,
      r,
      i
    );
  } else if (h.content === "none")
    p = void 0;
  else
    throw new In(h.content);
  const m = {
    id: c,
    type: h.type,
    props: u,
    content: p,
    children: f
  };
  return o == null || o.set(n, m), m;
}
function zI(n, e, t = Hf(e), r = Vf(e), i = Co(e), o = Uf(e)) {
  const s = [];
  return n.firstChild.descendants((l) => (s.push(
    Se(
      l,
      e,
      t,
      r,
      i,
      o
    )
  ), !1)), s;
}
function HI(n, e, t = Hf(e), r = Vf(e), i = Co(e), o = Uf(e)) {
  function s(l, a, c) {
    if (l.type.name !== "blockGroup")
      throw new Error("unexpected");
    const d = [];
    let u, h;
    return l.forEach((f, p, m) => {
      if (f.type.name !== "blockContainer")
        throw new Error("unexpected");
      if (f.childCount === 0)
        return;
      if (f.childCount === 0 || f.childCount > 2)
        throw new Error(
          "unexpected, blockContainer.childCount: " + f.childCount
        );
      const g = m === 0, y = m === l.childCount - 1;
      if (f.firstChild.type.name === "blockGroup") {
        if (!g)
          throw new Error("unexpected");
        const C = s(
          f.firstChild,
          Math.max(0, a - 1),
          y ? Math.max(0, c - 1) : 0
        );
        u = C.blockCutAtStart, y && (h = C.blockCutAtEnd), d.push(...C.blocks);
        return;
      }
      const _ = Se(
        f,
        e,
        t,
        r,
        i,
        o
      ), b = f.childCount > 1 ? f.child(1) : void 0;
      let k = [];
      if (b) {
        const C = s(
          b,
          0,
          // TODO: can this be anything other than 0?
          y ? Math.max(0, c - 1) : 0
        );
        k = C.blocks, y && (h = C.blockCutAtEnd);
      }
      y && !b && c > 1 && (h = _.id), g && a > 1 && (u = _.id), d.push({
        ..._,
        children: k
      });
    }), { blocks: d, blockCutAtStart: u, blockCutAtEnd: h };
  }
  if (n.content.childCount === 0)
    return {
      blocks: [],
      blockCutAtStart: void 0,
      blockCutAtEnd: void 0
    };
  if (n.content.childCount !== 1)
    throw new Error(
      "slice must be a single block, did you forget includeParents=true?"
    );
  return s(
    n.content.firstChild,
    Math.max(n.openStart - 1, 0),
    Math.max(n.openEnd - 1, 0)
  );
}
function q1(n) {
  return Object.fromEntries(
    Object.entries(n).map(([e, t]) => [e, t.config])
  );
}
function VI(n, e) {
  return {
    config: n,
    implementation: e
  };
}
function Yr(n, e) {
  return VI(
    {
      type: n.name,
      propSchema: e
    },
    {
      mark: n
    }
  );
}
function j1(n) {
  return Object.fromEntries(
    Object.entries(n).map(([e, t]) => [e, t.config])
  );
}
function Vr(n) {
  const { height: e, width: t } = qf(n), r = new Array(e).fill(!1).map(() => new Array(t).fill(null)), i = (o, s) => {
    for (let l = o; l < e; l++)
      for (let a = s; a < t; a++)
        if (!r[l][a])
          return { row: l, col: a };
    throw new Error(
      "Unable to create occupancy grid for table, no more available cells"
    );
  };
  for (let o = 0; o < n.content.rows.length; o++)
    for (let s = 0; s < n.content.rows[o].cells.length; s++) {
      const l = ah(n.content.rows[o].cells[s]), a = ch(l), c = Is(l), { row: d, col: u } = i(o, s);
      for (let h = d; h < d + a; h++)
        for (let f = u; f < u + c; f++) {
          if (r[h][f])
            throw new Error(
              `Unable to create occupancy grid for table, cell at ${h},${f} is already occupied`
            );
          r[h][f] = {
            row: o,
            col: s,
            rowspan: a,
            colspan: c,
            cell: l
          };
        }
    }
  return r;
}
function Ls(n) {
  const e = /* @__PURE__ */ new Set();
  return n.map((t) => ({
    cells: t.map((r) => e.has(r.row + ":" + r.col) ? !1 : (e.add(r.row + ":" + r.col), r.cell)).filter((r) => r !== !1)
  }));
}
function vi(n, e, t = Vr(e)) {
  for (let r = 0; r < t.length; r++)
    for (let i = 0; i < t[r].length; i++) {
      const o = t[r][i];
      if (o.row === n.row && o.col === n.col)
        return { row: r, col: i, cell: o.cell };
    }
  throw new Error(
    `Unable to resolve relative table cell indices for table, cell at ${n.row},${n.col} is not occupied`
  );
}
function qf(n) {
  const e = n.content.rows.length;
  let t = 0;
  return n.content.rows.forEach((r) => {
    let i = 0;
    r.cells.forEach((o) => {
      i += Is(o);
    }), t = Math.max(t, i);
  }), { height: e, width: t };
}
function W1(n, e, t = Vr(e)) {
  var r;
  const i = (r = t[n.row]) == null ? void 0 : r[n.col];
  if (i)
    return {
      row: i.row,
      col: i.col,
      cell: i.cell
    };
}
function uh(n, e) {
  var t;
  const r = Vr(n);
  if (e < 0 || e >= r.length)
    return [];
  let i = 0;
  for (let s = 0; s < e; s++) {
    const l = (t = r[i]) == null ? void 0 : t[0];
    if (!l)
      return [];
    i += l.rowspan;
  }
  const o = new Array(r[0].length).fill(!1).map((s, l) => W1(
    { row: i, col: l },
    n,
    r
  )).filter(
    (s) => s !== void 0
  );
  return o.filter((s, l) => o.findIndex((a) => a.row === s.row && a.col === s.col) === l);
}
function hh(n, e) {
  var t;
  const r = Vr(n);
  if (e < 0 || e >= r[0].length)
    return [];
  let i = 0;
  for (let s = 0; s < e; s++) {
    const l = (t = r[0]) == null ? void 0 : t[i];
    if (!l)
      return [];
    i += l.colspan;
  }
  const o = new Array(r.length).fill(!1).map((s, l) => W1(
    { row: l, col: i },
    n,
    r
  )).filter(
    (s) => s !== void 0
  );
  return o.filter((s, l) => o.findIndex((a) => a.row === s.row && a.col === s.col) === l);
}
function UI(n, e, t, r = Vr(n)) {
  const { col: i } = vi(
    {
      row: 0,
      col: e
    },
    n,
    r
  ), { col: o } = vi(
    {
      row: 0,
      col: t
    },
    n,
    r
  );
  return r.forEach((s) => {
    const [l] = s.splice(i, 1);
    s.splice(o, 0, l);
  }), Ls(r);
}
function qI(n, e, t, r = Vr(n)) {
  const { row: i } = vi(
    {
      row: e,
      col: 0
    },
    n,
    r
  ), { row: o } = vi(
    {
      row: t,
      col: 0
    },
    n,
    r
  ), [s] = r.splice(i, 1);
  return r.splice(o, 0, s), Ls(r);
}
function fh(n) {
  return n ? $s(n) ? fh(n.content) : typeof n == "string" ? n.length === 0 : Array.isArray(n) ? n.every(
    (e) => typeof e == "string" ? e.length === 0 : mo(e) ? e.text.length === 0 : B1(e) ? typeof e.content == "string" ? e.content.length === 0 : e.content.every((t) => t.text.length === 0) : !1
  ) : !1 : !0;
}
function jI(n, e, t = Vr(n)) {
  if (e === "columns") {
    let o = 0;
    for (let s = t[0].length - 1; s >= 0 && t.every(
      (l) => fh(l[s].cell) && l[s].colspan === 1
    ); s--)
      o++;
    for (let s = t.length - 1; s >= 0; s--) {
      const l = Math.max(
        t[s].length - o,
        1
      );
      t[s] = t[s].slice(0, l);
    }
    return Ls(t);
  }
  let r = 0;
  for (let o = t.length - 1; o >= 0 && t[o].every(
    (s) => fh(s.cell) && s.rowspan === 1
  ); o--)
    r++;
  const i = Math.min(r, t.length - 1);
  return t.splice(t.length - i, i), Ls(t);
}
function WI(n, e, t, r = Vr(n)) {
  const { width: i, height: o } = qf(n);
  if (e === "columns")
    r.forEach((s, l) => {
      if (t >= 0)
        for (let a = 0; a < t; a++)
          s.push({
            row: l,
            col: Math.max(...s.map((c) => c.col)) + 1,
            rowspan: 1,
            colspan: 1,
            cell: ah("")
          });
      else
        s.splice(i + t, -1 * t);
    });
  else if (t > 0)
    for (let s = 0; s < t; s++) {
      const l = new Array(i).fill(null).map((a, c) => ({
        row: o + s,
        col: c,
        rowspan: 1,
        colspan: 1,
        cell: ah("")
      }));
      r.push(l);
    }
  else t < 0 && r.splice(o + t, -1 * t);
  return Ls(r);
}
function G1(n, e, t) {
  const r = uh(n, t);
  if (!r.some((s) => ch(s.cell) > 1))
    return !0;
  let i = t, o = t;
  return r.forEach((s) => {
    const l = ch(s.cell);
    i = Math.max(i, s.row + l - 1), o = Math.min(o, s.row);
  }), e < t ? t === i : t === o;
}
function K1(n, e, t) {
  const r = hh(n, t);
  if (!r.some((s) => Is(s.cell) > 1))
    return !0;
  let i = t, o = t;
  return r.forEach((s) => {
    const l = Is(s.cell);
    i = Math.max(i, s.col + l - 1), o = Math.min(o, s.col);
  }), e < t ? t === i : t === o;
}
function GI(n, e, t) {
  const r = vi(n, t), i = vi(e, t);
  return r.col === i.col;
}
function P0(n, e, t, r) {
  const i = [];
  for (const [o, s] of Object.entries(n.styles || {})) {
    const l = t[o];
    if (!l)
      throw new Error(`style ${o} not found in styleSchema`);
    if (l.propSchema === "boolean")
      s && i.push(e.mark(o));
    else if (l.propSchema === "string")
      s && i.push(e.mark(o, { stringValue: s }));
    else
      throw new In(l.propSchema);
  }
  return !r || !e.nodes[r].spec.code ? n.text.split(/(\n)/g).filter((o) => o.length > 0).map((o) => o === `
` ? e.nodes.hardBreak.createChecked() : e.text(o, i)) : n.text.length > 0 ? [e.text(n.text, i)] : [];
}
function KI(n, e, t) {
  const r = e.marks.link.create({
    href: n.href
  });
  return ph(n.content, e, t).map(
    (i) => {
      if (i.type.name === "text")
        return i.mark([...i.marks, r]);
      if (i.type.name === "hardBreak")
        return i;
      throw new Error("unexpected node type");
    }
  );
}
function ph(n, e, t, r) {
  const i = [];
  if (typeof n == "string")
    return i.push(
      ...P0(
        { text: n, styles: {} },
        e,
        t,
        r
      )
    ), i;
  for (const o of n)
    i.push(
      ...P0(o, e, t, r)
    );
  return i;
}
function mn(n, e, t, r = Co(e)) {
  const i = [];
  for (const o of n)
    typeof o == "string" ? i.push(
      ...ph(o, e, r, t)
    ) : B1(o) ? i.push(...KI(o, e, r)) : mo(o) ? i.push(
      ...ph([o], e, r, t)
    ) : i.push(
      J1(o, e, r)
    );
  return i;
}
function Rc(n, e, t = Co(e)) {
  const r = [], i = new Array(n.headerRows ?? 0).fill(!0), o = new Array(n.headerCols ?? 0).fill(!0), s = n.columnWidths ?? [];
  for (let l = 0; l < n.rows.length; l++) {
    const a = n.rows[l], c = [], d = i[l];
    for (let h = 0; h < a.cells.length; h++) {
      const f = a.cells[h], p = o[h], m = void 0;
      let g = null;
      const y = vi(
        {
          row: l,
          col: h
        },
        { content: n }
      );
      let _ = s[y.col] ? [s[y.col]] : null;
      if (f) if (typeof f == "string")
        g = e.text(f);
      else if ($s(f)) {
        f.content && (g = mn(
          f.content,
          e,
          "tableParagraph",
          t
        ));
        const k = Is(f);
        k > 1 && (_ = new Array(k).fill(!1).map((C, w) => s[y.col + w] ?? void 0));
      } else
        g = mn(
          f,
          e,
          "tableParagraph",
          t
        );
      const b = e.nodes[p || d ? "tableHeader" : "tableCell"].createChecked(
        {
          ...$s(f) ? f.props : {},
          colwidth: _
        },
        e.nodes.tableParagraph.createChecked(m, g)
      );
      c.push(b);
    }
    const u = e.nodes.tableRow.createChecked({}, c);
    r.push(u);
  }
  return r;
}
function J1(n, e, t) {
  let r, i = n.type;
  if (i === void 0 && (i = "paragraph"), !e.nodes[i])
    throw new Error(`node type ${i} not found in schema`);
  if (!n.content)
    r = e.nodes[i].createChecked(n.props);
  else if (typeof n.content == "string") {
    const o = mn(
      [n.content],
      e,
      i,
      t
    );
    r = e.nodes[i].createChecked(n.props, o);
  } else if (Array.isArray(n.content)) {
    const o = mn(
      n.content,
      e,
      i,
      t
    );
    r = e.nodes[i].createChecked(n.props, o);
  } else if (n.content.type === "tableContent") {
    const o = Rc(n.content, e, t);
    r = e.nodes[i].createChecked(n.props, o);
  } else
    throw new In(n.content.type);
  return r;
}
function Di(n, e, t = Co(e)) {
  let r = n.id;
  r === void 0 && (r = Nc.options.generateID());
  const i = [];
  if (n.children)
    for (const o of n.children)
      i.push(Di(o, e, t));
  if (!n.type || // can happen if block.type is not defined (this should create the default node)
  e.nodes[n.type].isInGroup("blockContent")) {
    const o = J1(
      n,
      e,
      t
    ), s = i.length > 0 ? e.nodes.blockGroup.createChecked({}, i) : void 0;
    return e.nodes.blockContainer.createChecked(
      {
        id: r,
        ...n.props
      },
      s ? [o, s] : o
    );
  } else {
    if (e.nodes[n.type].isInGroup("bnBlock"))
      return e.nodes[n.type].createChecked(
        {
          id: r,
          ...n.props
        },
        i
      );
    throw new Error(
      `block type ${n.type} doesn't match blockContent or bnBlock group`
    );
  }
}
function JI(n, e) {
  if (e === 0)
    return;
  const t = n.resolve(e);
  for (let r = t.depth; r > 0; r--) {
    const i = t.node(r);
    if (jf(i))
      return i.attrs.id;
  }
}
function Nt(n, e) {
  let t, r;
  if (e.firstChild.descendants((i, o) => t ? !1 : !jf(i) || i.attrs.id !== n ? !0 : (t = i, r = o + 1, !1)), !(t === void 0 || r === void 0))
    return {
      node: t,
      posBeforeNode: r
    };
}
function jf(n) {
  return n.type.isInGroup("bnBlock");
}
function YI(n, e) {
  return n.id !== e.id || n.type !== e.type || JSON.stringify(n.props) !== JSON.stringify(e.props) || JSON.stringify(n.content) !== JSON.stringify(e.content);
}
function XI(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 z0(n) {
  const e = {}, t = Ue(n);
  return n.descendants((r, i) => {
    if (jf(r)) {
      const o = JI(n, i);
      e[r.attrs.id] = {
        block: Se(r, t),
        parentId: o
      };
    }
    return !0;
  }), e;
}
function Y1(n, e = []) {
  const t = XI(n), r = Zh(n.before, [
    n,
    ...e
  ]), i = z0(
    r.before
  ), o = z0(
    r.doc
  ), s = [];
  return Object.keys(o).filter((l) => !(l in i)).forEach((l) => {
    s.push({
      type: "insert",
      block: o[l].block,
      source: t,
      prevBlock: void 0
    });
  }), Object.keys(i).filter((l) => !(l in o)).forEach((l) => {
    s.push({
      type: "delete",
      block: i[l].block,
      source: t,
      prevBlock: void 0
    });
  }), Object.keys(o).filter((l) => l in i).forEach((l) => {
    var a, c;
    const d = i[l], u = o[l];
    d.parentId !== u.parentId ? s.push({
      type: "move",
      block: u.block,
      prevBlock: d.block,
      source: t,
      prevParent: d.parentId ? (a = i[d.parentId]) == null ? void 0 : a.block : void 0,
      currentParent: u.parentId ? (c = o[u.parentId]) == null ? void 0 : c.block : void 0
    }) : YI(d.block, u.block) && s.push({
      type: "update",
      block: u.block,
      prevBlock: d.block,
      source: t
    });
  }), s;
}
function ZI(n, e, t, r = "before") {
  const i = typeof t == "string" ? t : t.id, o = Ue(n), s = e.map(
    (c) => Di(c, o)
  ), l = Nt(i, n.doc);
  if (!l)
    throw new Error(`Block with ID ${i} not found`);
  let a = l.posBeforeNode;
  return r === "after" && (a += l.node.nodeSize), n.step(
    new Me(a, a, new O(A.from(s), 0, 0))
  ), s.map(
    (c) => Se(c, o)
  );
}
function H0(n, e, t) {
  const r = Ue(n), i = t.map(
    (c) => Di(c, r)
  ), o = new Set(
    e.map(
      (c) => typeof c == "string" ? c : c.id
    )
  ), s = [], l = typeof e[0] == "string" ? e[0] : e[0].id;
  let a = 0;
  if (n.doc.descendants((c, d) => {
    if (o.size === 0)
      return !1;
    if (!c.type.isInGroup("bnBlock") || !o.has(c.attrs.id))
      return !0;
    if (s.push(Se(c, r)), o.delete(c.attrs.id), t.length > 0 && c.attrs.id === l) {
      const p = n.doc.nodeSize;
      n.insert(d, i);
      const m = n.doc.nodeSize;
      a += p - m;
    }
    const u = n.doc.nodeSize, h = n.doc.resolve(d - a);
    h.node().type.name === "blockGroup" && h.node(h.depth - 1).type.name !== "doc" && h.node().childCount === 1 ? n.delete(h.before(), h.after()) : n.delete(d - a, d - a + c.nodeSize);
    const f = n.doc.nodeSize;
    return a += u - f, !1;
  }), o.size > 0) {
    const c = [...o].join(`
`);
    throw Error(
      "Blocks with the following IDs could not be found in the editor: " + c
    );
  }
  return { insertedBlocks: i.map(
    (c) => Se(c, r)
  ), removedBlocks: s };
}
const rt = (n, e) => ({
  tr: t,
  dispatch: r
}) => (r && X1(t, n, e), !0);
function X1(n, e, t, r, i) {
  const o = Js(n.doc.resolve(e)), s = Ue(n), l = s.nodes[o.blockNoteType], a = s.nodes[t.type || o.blockNoteType], c = a.isInGroup("bnBlock") ? a : s.nodes.blockContainer;
  if (o.isBlockContainer && a.isInGroup("blockContent"))
    V0(t, n, o), QI(
      t,
      n,
      l,
      a,
      o
    );
  else if (!o.isBlockContainer && a.isInGroup("bnBlock"))
    V0(t, n, o);
  else {
    const d = Se(o.bnBlock.node, s);
    n.replaceWith(
      o.bnBlock.beforePos,
      o.bnBlock.afterPos,
      Di(
        {
          children: d.children,
          // if no children are passed in, use existing children
          ...t
        },
        s
      )
    );
    return;
  }
  n.setNodeMarkup(o.bnBlock.beforePos, c, {
    ...o.bnBlock.node.attrs,
    ...t.props
  });
}
function QI(n, e, t, r, i, o, s) {
  const l = Ue(e);
  let a = "keep";
  if (n.content)
    if (typeof n.content == "string")
      a = mn(
        [n.content],
        l,
        r.name
      );
    else if (Array.isArray(n.content))
      a = mn(n.content, l, r.name);
    else if (n.content.type === "tableContent")
      a = Rc(n.content, l);
    else
      throw new In(n.content.type);
  else
    t.spec.content === "" || r.spec.content !== t.spec.content && (a = []);
  a === "keep" ? e.setNodeMarkup(i.blockContent.beforePos, r, {
    ...i.blockContent.node.attrs,
    ...n.props
  }) : e.replaceWith(
    i.blockContent.beforePos,
    i.blockContent.afterPos,
    r.createChecked(
      {
        ...i.blockContent.node.attrs,
        ...n.props
      },
      a
    )
  );
}
function V0(n, e, t) {
  const r = Ue(e);
  if (n.children !== void 0 && n.children.length > 0) {
    const i = n.children.map((o) => Di(o, r));
    if (t.childContainer)
      e.step(
        new Me(
          t.childContainer.beforePos + 1,
          t.childContainer.afterPos - 1,
          new O(A.from(i), 0, 0)
        )
      );
    else {
      if (!t.isBlockContainer)
        throw new Error("impossible");
      e.insert(
        t.blockContent.afterPos,
        r.nodes.blockGroup.createChecked({}, i)
      );
    }
  }
}
function eL(n, e, t, r, i) {
  const o = typeof e == "string" ? e : e.id, s = Nt(o, n.doc);
  if (!s)
    throw new Error(`Block with ID ${o} not found`);
  X1(
    n,
    s.posBeforeNode,
    t
  );
  const l = n.doc.resolve(s.posBeforeNode + 1).node(), a = Ue(n);
  return Se(l, a);
}
function Z1(n) {
  const e = Array.from(n.classList).filter(
    (t) => !t.startsWith("bn-")
  ) || [];
  e.length > 0 ? n.className = e.join(" ") : n.removeAttribute("class");
}
function Q1(n, e, t, r) {
  let i;
  if (e)
    if (typeof e == "string")
      i = mn([e], n.pmSchema);
    else if (Array.isArray(e))
      i = mn(e, n.pmSchema);
    else if (e.type === "tableContent")
      i = Rc(e, n.pmSchema);
    else
      throw new In(e.type);
  else throw new Error("blockContent is required");
  const o = t.serializeFragment(A.from(i), r);
  return o.nodeType === 1 && Z1(o), o;
}
function tL(n, e, t, r, i, o, s) {
  var l, a, c, d, u, h, f, p;
  const m = (s == null ? void 0 : s.document) ?? document, g = e.pmSchema.nodes.blockContainer;
  let y = t.props;
  if (!t.props) {
    y = {};
    for (const [x, S] of Object.entries(
      e.schema.blockSchema[t.type].propSchema
    ))
      S.default !== void 0 && (y[x] = S.default);
  }
  const _ = (a = (l = g.spec) == null ? void 0 : l.toDOM) == null ? void 0 : a.call(
    l,
    g.create({
      id: t.id,
      ...y
    })
  ), b = Array.from(_.dom.attributes), k = e.blockImplementations[t.type].implementation.toExternalHTML({ ...t, props: y }, e), C = m.createDocumentFragment();
  if (k.dom.classList.contains("bn-block-content")) {
    const x = [
      ...b,
      ...Array.from(k.dom.attributes)
    ].filter(
      (S) => S.name.startsWith("data") && S.name !== "data-content-type" && S.name !== "data-file-block" && S.name !== "data-node-view-wrapper" && S.name !== "data-node-type" && S.name !== "data-id" && S.name !== "data-index" && S.name !== "data-editable"
    );
    for (const S of x)
      k.dom.firstChild.setAttribute(S.name, S.value);
    Z1(k.dom.firstChild), C.append(...Array.from(k.dom.childNodes));
  } else
    C.append(k.dom);
  if (k.contentDOM && t.content) {
    const x = Q1(
      e,
      t.content,
      // TODO
      r,
      s
    );
    k.contentDOM.appendChild(x);
  }
  let w;
  if (i.has(t.type) ? w = "OL" : o.has(t.type) && (w = "UL"), w) {
    if (((c = n.lastChild) == null ? void 0 : c.nodeName) !== w) {
      const S = m.createElement(w);
      w === "OL" && y != null && y.start && (y == null ? void 0 : y.start) !== 1 && S.setAttribute("start", y.start + ""), n.append(S);
    }
    const x = m.createElement("li");
    x.append(C), n.lastChild.appendChild(x);
  } else
    n.append(C);
  if (t.children && t.children.length > 0) {
    const x = m.createDocumentFragment();
    if (ek(
      x,
      e,
      t.children,
      r,
      i,
      o,
      s
    ), ((d = n.lastChild) == null ? void 0 : d.nodeName) === "UL" || ((u = n.lastChild) == null ? void 0 : u.nodeName) === "OL")
      for (; ((h = x.firstChild) == null ? void 0 : h.nodeName) === "UL" || ((f = x.firstChild) == null ? void 0 : f.nodeName) === "OL"; )
        n.lastChild.lastChild.appendChild(x.firstChild);
    e.pmSchema.nodes[t.type].isInGroup("blockContent") ? n.append(x) : (p = k.contentDOM) == null || p.append(x);
  }
}
const ek = (n, e, t, r, i, o, s) => {
  for (const l of t)
    tL(
      n,
      e,
      l,
      r,
      i,
      o,
      s
    );
}, nL = (n, e, t, r, i, o) => {
  const s = ((o == null ? void 0 : o.document) ?? document).createDocumentFragment();
  return ek(
    s,
    n,
    e,
    t,
    r,
    i,
    o
  ), s;
}, Bc = (n, e) => {
  const t = sr.fromSchema(n);
  return {
    exportBlocks: (r, i) => {
      const o = nL(
        e,
        r,
        t,
        /* @__PURE__ */ new Set(["numberedListItem"]),
        /* @__PURE__ */ new Set(["bulletListItem", "checkListItem"]),
        i
      ), s = document.createElement("div");
      return s.append(o), s.innerHTML;
    },
    exportInlineContent: (r, i) => {
      const o = Q1(
        e,
        r,
        t,
        i
      ), s = document.createElement("div");
      return s.append(o.cloneNode(!0)), s.innerHTML;
    }
  };
};
function rL(n, e, t, r, i) {
  let o;
  if (e)
    if (typeof e == "string")
      o = mn([e], n.pmSchema, r);
    else if (Array.isArray(e))
      o = mn(e, n.pmSchema, r);
    else if (e.type === "tableContent")
      o = Rc(e, n.pmSchema);
    else
      throw new In(e.type);
  else throw new Error("blockContent is required");
  return t.serializeFragment(A.from(o), i);
}
function iL(n, e, t, r, i) {
  var o, s, l, a, c;
  const d = n.pmSchema.nodes.blockContainer;
  let u = e.props;
  if (!e.props) {
    u = {};
    for (const [p, m] of Object.entries(
      n.schema.blockSchema[e.type].propSchema
    ))
      m.default !== void 0 && (u[p] = m.default);
  }
  const h = n.blockImplementations[e.type].implementation.toInternalHTML({ ...e, props: u }, n);
  if (e.type === "numberedListItem" && h.dom.setAttribute("data-index", r.toString()), h.contentDOM && e.content) {
    const p = rL(
      n,
      e.content,
      // TODO
      t,
      e.type,
      i
    );
    h.contentDOM.appendChild(p);
  }
  if (n.pmSchema.nodes[e.type].isInGroup("bnBlock")) {
    if (e.children && e.children.length > 0) {
      const p = tk(
        n,
        e.children,
        t,
        i
      );
      (o = h.contentDOM) == null || o.append(p);
    }
    return h.dom;
  }
  const f = (l = (s = d.spec) == null ? void 0 : s.toDOM) == null ? void 0 : l.call(
    s,
    d.create({
      id: e.id,
      ...u
    })
  );
  return (a = f.contentDOM) == null || a.appendChild(h.dom), e.children && e.children.length > 0 && ((c = f.contentDOM) == null || c.appendChild(
    nk(n, e.children, t, i)
  )), f.dom;
}
function tk(n, e, t, r) {
  const i = ((r == null ? void 0 : r.document) ?? document).createDocumentFragment();
  let o = 0;
  for (const s of e) {
    s.type === "numberedListItem" ? o++ : o = 0;
    const l = iL(
      n,
      s,
      t,
      o,
      r
    );
    i.appendChild(l);
  }
  return i;
}
const nk = (n, e, t, r) => {
  var i;
  const o = n.pmSchema.nodes.blockGroup, s = o.spec.toDOM(o.create({})), l = tk(n, e, t, r);
  return (i = s.contentDOM) == null || i.appendChild(l), s.dom;
}, oL = (n, e) => {
  const t = sr.fromSchema(n);
  return {
    serializeBlocks: (r, i) => nk(e, r, t, i).outerHTML
  };
}, Pc = (n, e) => {
  const t = n.querySelector(
    e
  );
  if (!t)
    return;
  const r = n.querySelector("figcaption"), i = (r == null ? void 0 : r.textContent) ?? void 0;
  return { targetElement: t, caption: i };
}, sL = (n, e, t, r) => {
  const i = document.createElement("div");
  i.className = "bn-add-file-button";
  const o = document.createElement("div");
  o.className = "bn-add-file-button-icon", r ? o.appendChild(r) : o.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>', i.appendChild(o);
  const s = document.createElement("p");
  s.className = "bn-add-file-button-text", s.innerHTML = t || e.dictionary.file_blocks.file.add_button_text, i.appendChild(s);
  const l = (c) => {
    c.preventDefault();
  }, a = () => {
    e.transact(
      (c) => c.setMeta(e.filePanel.plugins[0], {
        block: n
      })
    );
  };
  return i.addEventListener(
    "mousedown",
    l,
    !0
  ), i.addEventListener("click", a, !0), {
    dom: i,
    destroy: () => {
      i.removeEventListener(
        "mousedown",
        l,
        !0
      ), i.removeEventListener(
        "click",
        a,
        !0
      );
    }
  };
}, lL = '<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>', aL = (n) => {
  const e = document.createElement("div");
  e.className = "bn-file-name-with-icon";
  const t = document.createElement("div");
  t.className = "bn-file-icon", t.innerHTML = lL, e.appendChild(t);
  const r = document.createElement("p");
  return r.className = "bn-file-name", r.textContent = n.props.name, e.appendChild(r), {
    dom: e
  };
}, Wf = (n, e, t, r, i) => {
  const o = document.createElement("div");
  if (o.className = "bn-file-block-content-wrapper", n.props.url === "") {
    const l = sL(
      n,
      e,
      r,
      i
    );
    o.appendChild(l.dom);
    const a = e.onUploadStart((c) => {
      if (c === n.id) {
        o.removeChild(l.dom);
        const d = document.createElement("div");
        d.className = "bn-file-loading-preview", d.textContent = "Loading...", o.appendChild(d);
      }
    });
    return {
      dom: o,
      destroy: () => {
        a(), l.destroy();
      }
    };
  }
  const s = { dom: o };
  if (n.props.showPreview === !1 || !t) {
    const l = aL(n);
    o.appendChild(l.dom), s.destroy = () => {
      var a;
      (a = l.destroy) == null || a.call(l);
    };
  } else
    o.appendChild(t.dom);
  if (n.props.caption) {
    const l = document.createElement("p");
    l.className = "bn-file-caption", l.textContent = n.props.caption, o.appendChild(l);
  }
  return s;
}, Gf = (n, e) => {
  const t = document.createElement("figure"), r = document.createElement("figcaption");
  return r.textContent = e, t.appendChild(n), t.appendChild(r), { dom: t };
}, zc = (n, e) => {
  const t = document.createElement("div"), r = document.createElement("p");
  return r.textContent = e, t.appendChild(n), t.appendChild(r), {
    dom: t
  };
}, U0 = (n) => ({ url: n.src || void 0 }), cL = '<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>', dL = {
  backgroundColor: Fe.backgroundColor,
  // File name.
  name: {
    default: ""
  },
  // File url.
  url: {
    default: ""
  },
  // File caption.
  caption: {
    default: ""
  },
  showPreview: {
    default: !0
  }
}, uL = {
  type: "audio",
  propSchema: dL,
  content: "none",
  isFileBlock: !0,
  fileBlockAccept: ["audio/*"]
}, hL = (n, e) => {
  const t = document.createElement("div");
  t.innerHTML = cL;
  const r = document.createElement("audio");
  return r.className = "bn-audio", e.resolveFileUrl ? e.resolveFileUrl(n.props.url).then((i) => {
    r.src = i;
  }) : r.src = n.props.url, r.controls = !0, r.contentEditable = "false", r.draggable = !1, Wf(
    n,
    e,
    { dom: r },
    e.dictionary.file_blocks.audio.add_button_text,
    t.firstElementChild
  );
}, fL = (n) => {
  if (n.tagName === "AUDIO")
    return n.closest("figure") ? void 0 : U0(n);
  if (n.tagName === "FIGURE") {
    const e = Pc(n, "audio");
    if (!e)
      return;
    const { targetElement: t, caption: r } = e;
    return {
      ...U0(t),
      caption: r
    };
  }
}, pL = (n) => {
  if (!n.props.url) {
    const t = document.createElement("p");
    return t.textContent = "Add audio", {
      dom: t
    };
  }
  let e;
  return n.props.showPreview ? (e = document.createElement("audio"), e.src = n.props.url) : (e = document.createElement("a"), e.href = n.props.url, e.textContent = n.props.name || n.props.url), n.props.caption ? n.props.showPreview ? Gf(e, n.props.caption) : zc(e, n.props.caption) : {
    dom: e
  };
}, mL = Ks(uL, {
  render: hL,
  parse: fL,
  toExternalHTML: pL
}), q0 = Symbol.for("blocknote.shikiParser"), Zd = Symbol.for(
  "blocknote.shikiHighlighterPromise"
), gL = {
  language: {
    default: "text"
  }
}, bL = bn({
  name: "codeBlock",
  content: "inline*",
  group: "blockContent",
  marks: "insertion deletion modification",
  code: !0,
  defining: !0,
  addOptions() {
    return {
      defaultLanguage: "text",
      indentLineWithTab: !0,
      supportedLanguages: {}
    };
  },
  addAttributes() {
    const n = this.options;
    return {
      language: {
        default: n.editor.settings.codeBlock.defaultLanguage,
        parseHTML: (e) => {
          let t = e, r = null;
          (t == null ? void 0 : t.tagName) === "DIV" && (t == null ? void 0 : t.dataset.contentType) === "codeBlock" && (t = t.children[0]), (t == null ? void 0 : t.tagName) === "PRE" && (t = t == null ? void 0 : t.children[0]);
          const i = t == null ? void 0 : t.getAttribute("data-language");
          if (i)
            r = i.toLowerCase();
          else {
            const o = [...(t == null ? void 0 : t.className.split(" ")) || []].filter((s) => s.startsWith("language-")).map((s) => s.replace("language-", ""));
            o.length > 0 && (r = o[0].toLowerCase());
          }
          return r ? Qd(n.editor.settings.codeBlock, r) ?? r : null;
        },
        renderHTML: (e) => e.language ? {
          class: `language-${e.language}`,
          "data-language": e.language
        } : {}
      }
    };
  },
  parseHTML() {
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      },
      // Parse from external HTML.
      {
        tag: "pre",
        // contentElement: "code",
        preserveWhitespace: "full"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e, t;
    const r = document.createElement("pre"), { dom: i, contentDOM: o } = Ft(
      this.name,
      "code",
      ((e = this.options.domAttributes) == null ? void 0 : e.blockContent) || {},
      {
        ...((t = this.options.domAttributes) == null ? void 0 : t.inlineContent) || {},
        ...n
      }
    );
    return i.removeChild(o), i.appendChild(r), r.appendChild(o), {
      dom: i,
      contentDOM: o
    };
  },
  addNodeView() {
    const n = this.options;
    return ({ editor: e, node: t, getPos: r, HTMLAttributes: i }) => {
      var o, s;
      const l = document.createElement("pre"), a = document.createElement("select"), c = document.createElement("div"), { dom: d, contentDOM: u } = Ft(
        this.name,
        "code",
        {
          ...((o = this.options.domAttributes) == null ? void 0 : o.blockContent) || {},
          ...i
        },
        ((s = this.options.domAttributes) == null ? void 0 : s.inlineContent) || {}
      ), h = (f) => {
        const p = f.target.value;
        e.commands.command(({ tr: m }) => (m.setNodeAttribute(r(), "language", p), !0));
      };
      return Object.entries(
        n.editor.settings.codeBlock.supportedLanguages
      ).forEach(([f, { name: p }]) => {
        const m = document.createElement("option");
        m.value = f, m.text = p, a.appendChild(m);
      }), c.contentEditable = "false", a.value = t.attrs.language || n.editor.settings.codeBlock.defaultLanguage, d.removeChild(u), d.appendChild(c), d.appendChild(l), l.appendChild(u), c.appendChild(a), a.addEventListener("change", h), {
        dom: d,
        contentDOM: u,
        update: (f) => f.type === this.type,
        destroy: () => {
          a.removeEventListener("change", h);
        }
      };
    };
  },
  addProseMirrorPlugins() {
    const n = this.options, e = globalThis;
    let t, r, i = !1;
    return [KM({
      parser: (o) => {
        if (!n.editor.settings.codeBlock.createHighlighter)
          return process.env.NODE_ENV === "development" && !i && (console.log(
            "For syntax highlighting of code blocks, you must provide a `codeBlock.createHighlighter` function"
          ), i = !0), [];
        if (!t)
          return e[Zd] = e[Zd] || n.editor.settings.codeBlock.createHighlighter(), e[Zd].then(
            (l) => {
              t = l;
            }
          );
        const s = Qd(
          n.editor.settings.codeBlock,
          o.language
        );
        return !s || s === "text" || s === "none" || s === "plaintext" || s === "txt" ? [] : t.getLoadedLanguages().includes(s) ? (r || (r = e[q0] || JM(t), e[q0] = r), r(o)) : t.loadLanguage(s);
      },
      languageExtractor: (o) => o.attrs.language,
      nodeTypes: [this.name]
    })];
  },
  addInputRules() {
    const n = this.options;
    return [
      new Fr({
        find: /^```(.*?)\s$/,
        handler: ({ state: e, range: t, match: r }) => {
          const i = e.doc.resolve(t.from), o = r[1].trim(), s = {
            language: Qd(n.editor.settings.codeBlock, o) ?? o
          };
          if (!i.node(-1).canReplaceWith(
            i.index(-1),
            i.indexAfter(-1),
            this.type
          ))
            return null;
          e.tr.delete(t.from, t.to).setBlockType(t.from, t.from, this.type, s).setSelection(L.create(e.tr.doc, t.from));
        }
      })
    ];
  },
  addKeyboardShortcuts() {
    return {
      Delete: ({ editor: n }) => {
        const { selection: e } = n.state, { $from: t } = e;
        if (n.isActive(this.name) && !t.parent.textContent && vc(e)) {
          const r = t.pos - t.parentOffset - 2;
          return n.chain().setNodeSelection(r).deleteSelection().run(), !0;
        }
        return !1;
      },
      Tab: ({ editor: n }) => this.options.indentLineWithTab && n.isActive(this.name) ? (n.commands.insertContent("  "), !0) : !1,
      Enter: ({ editor: n }) => {
        const { $from: e } = n.state.selection;
        if (!n.isActive(this.name))
          return !1;
        const t = e.parentOffset === e.parent.nodeSize - 2, r = e.parent.textContent.endsWith(`

`);
        return !t || !r ? (n.commands.insertContent(`
`), !0) : n.chain().command(({ tr: i }) => (i.delete(e.pos - 2, e.pos), !0)).exitCode().run();
      },
      "Shift-Enter": ({ editor: n }) => {
        const { $from: e } = n.state.selection;
        return n.isActive(this.name) ? (n.chain().insertContentAt(
          e.pos - e.parentOffset + e.parent.nodeSize,
          {
            type: "paragraph"
          }
        ).run(), !0) : !1;
      }
    };
  }
}), yL = ar(
  bL,
  gL
);
function Qd(n, e) {
  var t;
  return (t = Object.entries(n.supportedLanguages).find(
    ([r, { aliases: i }]) => (i == null ? void 0 : i.includes(e)) || r === e
  )) == null ? void 0 : t[0];
}
const _L = Je.create({
  name: "backgroundColor",
  addAttributes() {
    return {
      stringValue: {
        default: void 0,
        parseHTML: (n) => n.getAttribute("data-background-color"),
        renderHTML: (n) => ({
          "data-background-color": n.stringValue
        })
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "span",
        getAttrs: (n) => typeof n == "string" ? !1 : n.hasAttribute("data-background-color") ? {
          stringValue: n.getAttribute("data-background-color")
        } : !1
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["span", n, 0];
  }
}), wL = Yr(
  _L,
  "string"
), kL = Je.create({
  name: "textColor",
  addAttributes() {
    return {
      stringValue: {
        default: void 0,
        parseHTML: (n) => n.getAttribute("data-text-color"),
        renderHTML: (n) => ({
          "data-text-color": n.stringValue
        })
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "span",
        getAttrs: (n) => typeof n == "string" ? !1 : n.hasAttribute("data-text-color") ? { stringValue: n.getAttribute("data-text-color") } : !1
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["span", n, 0];
  }
}), vL = Yr(kL, "string"), j0 = (n) => ({ url: n.src || void 0 }), CL = {
  backgroundColor: Fe.backgroundColor,
  // File name.
  name: {
    default: ""
  },
  // File url.
  url: {
    default: ""
  },
  // File caption.
  caption: {
    default: ""
  }
}, SL = {
  type: "file",
  propSchema: CL,
  content: "none",
  isFileBlock: !0
}, EL = (n, e) => Wf(n, e), xL = (n) => {
  if (n.tagName === "EMBED")
    return n.closest("figure") ? void 0 : j0(n);
  if (n.tagName === "FIGURE") {
    const e = Pc(n, "embed");
    if (!e)
      return;
    const { targetElement: t, caption: r } = e;
    return {
      ...j0(t),
      caption: r
    };
  }
}, DL = (n) => {
  if (!n.props.url) {
    const t = document.createElement("p");
    return t.textContent = "Add file", {
      dom: t
    };
  }
  const e = document.createElement("a");
  return e.href = n.props.url, e.textContent = n.props.name || n.props.url, n.props.caption ? zc(e, n.props.caption) : {
    dom: e
  };
}, AL = Ks(SL, {
  render: EL,
  parse: xL,
  toExternalHTML: DL
}), TL = {
  set: (n, e) => window.localStorage.setItem(
    `toggle-${n.id}`,
    e ? "true" : "false"
  ),
  get: (n) => window.localStorage.getItem(`toggle-${n.id}`) === "true"
}, rk = (n, e, t, r = TL) => {
  if ("isToggleable" in n.props && !n.props.isToggleable)
    return {
      dom: t
    };
  const i = document.createElement("div"), o = document.createElement("div");
  o.className = "bn-toggle-wrapper";
  const s = document.createElement("button");
  s.className = "bn-toggle-button", s.type = "button", s.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 l = (p) => p.preventDefault();
  s.addEventListener("mousedown", l);
  const a = () => {
    var p;
    o.getAttribute("data-show-children") === "true" ? (o.setAttribute("data-show-children", "false"), r.set(e.getBlock(n), !1), i.contains(c) && i.removeChild(c)) : (o.setAttribute("data-show-children", "true"), r.set(e.getBlock(n), !0), ((p = e.getBlock(n)) == null ? void 0 : p.children.length) === 0 && !i.contains(c) && i.appendChild(c));
  };
  s.addEventListener("click", a), o.appendChild(s), o.appendChild(t);
  const c = document.createElement("button");
  c.className = "bn-toggle-add-block-button", c.type = "button", c.textContent = "Empty toggle. Click to add a block.";
  const d = (p) => p.preventDefault();
  c.addEventListener(
    "mousedown",
    d
  );
  const u = () => {
    e.transact(() => {
      const p = e.updateBlock(n, {
        // Single empty block with default type.
        children: [{}]
      });
      e.setTextCursorPosition(p.children[0].id, "end"), e.focus();
    });
  };
  c.addEventListener("click", u), i.appendChild(o);
  let h = n.children.length;
  const f = e.onChange(() => {
    var p;
    const m = ((p = e.getBlock(n)) == null ? void 0 : p.children.length) ?? 0;
    m > h ? (o.getAttribute("data-show-children") === "false" && (o.setAttribute("data-show-children", "true"), r.set(e.getBlock(n), !0)), i.contains(c) && i.removeChild(c)) : m === 0 && m < h && (o.getAttribute("data-show-children") === "true" && (o.setAttribute("data-show-children", "false"), r.set(e.getBlock(n), !1)), i.contains(c) && i.removeChild(c)), h = m;
  });
  return r.get(n) ? (o.setAttribute("data-show-children", "true"), n.children.length === 0 && i.appendChild(c)) : o.setAttribute("data-show-children", "false"), {
    dom: i,
    // Prevents re-renders when the toggle button is clicked.
    ignoreMutation: (p) => p 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.
    (p.type === "attributes" && p.target === o && p.attributeName === "data-show-children" || p.type === "childList" && (p.addedNodes[0] === c || p.removedNodes[0] === c)),
    destroy: () => {
      s.removeEventListener("mousedown", l), s.removeEventListener("click", a), c.removeEventListener(
        "mousedown",
        d
      ), c.removeEventListener(
        "click",
        u
      ), f == null || f();
    }
  };
}, ML = [1, 2, 3, 4, 5, 6], ik = {
  ...Fe,
  level: { default: 1, values: ML },
  isToggleable: { default: !1 }
}, OL = bn({
  name: "heading",
  content: "inline*",
  group: "blockContent",
  addAttributes() {
    return $c(ik);
  },
  addInputRules() {
    return [
      ...this.options.editor.settings.heading.levels.map((n) => new Fr({
        find: new RegExp(`^(#{${n}})\\s$`),
        handler: ({ state: e, chain: t, range: r }) => {
          const i = ge(e);
          !i.isBlockContainer || i.blockContent.node.type.spec.content !== "inline*" || t().command(
            rt(i.bnBlock.beforePos, {
              type: "heading",
              props: {
                level: n
              }
            })
          ).deleteRange({ from: r.from, to: r.to }).run();
        }
      }))
    ];
  },
  addKeyboardShortcuts() {
    const n = this.options.editor;
    return Object.fromEntries(
      n.settings.heading.levels.map((e) => [
        `Mod-Alt-${e}`,
        () => {
          const t = ge(this.editor.state);
          return !t.isBlockContainer || t.blockContent.node.type.spec.content !== "inline*" ? !0 : this.editor.commands.command(
            rt(t.bnBlock.beforePos, {
              type: "heading",
              props: {
                level: e
              }
            })
          );
        }
      ])
    );
  },
  parseHTML() {
    const n = this.options.editor;
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      },
      ...n.settings.heading.levels.map((e) => ({
        tag: `h${e}`,
        attrs: { level: e },
        node: "heading"
      }))
    ];
  },
  renderHTML({ node: n, HTMLAttributes: e }) {
    var t, r;
    return Ft(
      this.name,
      `h${n.attrs.level}`,
      {
        ...((t = this.options.domAttributes) == null ? void 0 : t.blockContent) || {},
        ...e
      },
      ((r = this.options.domAttributes) == null ? void 0 : r.inlineContent) || {}
    );
  },
  addNodeView() {
    return ({ node: n, HTMLAttributes: e, getPos: t }) => {
      var r, i;
      const { dom: o, contentDOM: s } = Ft(
        this.name,
        `h${n.attrs.level}`,
        {
          ...((r = this.options.domAttributes) == null ? void 0 : r.blockContent) || {},
          ...e
        },
        ((i = this.options.domAttributes) == null ? void 0 : i.inlineContent) || {}
      );
      o.removeChild(s);
      const l = this.options.editor, a = Pf(t, l, this.editor, this.name), c = rk(
        a,
        l,
        s
      );
      return o.appendChild(c.dom), {
        dom: o,
        contentDOM: s,
        ignoreMutation: c.ignoreMutation,
        destroy: c.destroy
      };
    };
  }
}), FL = ar(
  OL,
  ik
), ok = (n, e, t, r, i, o) => {
  const { dom: s, destroy: l } = Wf(
    n,
    e,
    t,
    i,
    o
  ), a = s;
  n.props.url && n.props.showPreview && (n.props.previewWidth ? a.style.width = `${n.props.previewWidth}px` : a.style.width = "fit-content");
  const c = document.createElement("div");
  c.className = "bn-resize-handle", c.style.left = "4px";
  const d = document.createElement("div");
  d.className = "bn-resize-handle", d.style.right = "4px";
  let u, h = n.props.previewWidth;
  const f = (b) => {
    var k, C;
    if (!u) {
      !e.isEditable && r.contains(c) && r.contains(d) && (r.removeChild(c), r.removeChild(d));
      return;
    }
    let w;
    n.props.textAlignment === "center" ? u.handleUsed === "left" ? w = u.initialWidth + (u.initialClientX - b.clientX) * 2 : w = u.initialWidth + (b.clientX - u.initialClientX) * 2 : u.handleUsed === "left" ? w = u.initialWidth + u.initialClientX - b.clientX : w = u.initialWidth + b.clientX - u.initialClientX, h = Math.min(
      Math.max(w, 64),
      ((C = (k = e.domElement) == null ? void 0 : k.firstElementChild) == null ? void 0 : C.clientWidth) || Number.MAX_VALUE
    ), a.style.width = `${h}px`;
  }, p = (b) => {
    (!b.target || !a.contains(b.target) || !e.isEditable) && r.contains(c) && r.contains(d) && (r.removeChild(c), r.removeChild(d)), u && (u = void 0, e.updateBlock(n, {
      props: {
        previewWidth: h
      }
    }));
  }, m = () => {
    e.isEditable && (r.appendChild(c), r.appendChild(d));
  }, g = (b) => {
    b.relatedTarget === c || b.relatedTarget === d || u || e.isEditable && r.contains(c) && r.contains(d) && (r.removeChild(c), r.removeChild(d));
  }, y = (b) => {
    b.preventDefault(), u = {
      handleUsed: "left",
      initialWidth: a.clientWidth,
      initialClientX: b.clientX
    };
  }, _ = (b) => {
    b.preventDefault(), u = {
      handleUsed: "right",
      initialWidth: a.clientWidth,
      initialClientX: b.clientX
    };
  };
  return window.addEventListener("mousemove", f), window.addEventListener("mouseup", p), a.addEventListener("mouseenter", m), a.addEventListener("mouseleave", g), c.addEventListener(
    "mousedown",
    y
  ), d.addEventListener(
    "mousedown",
    _
  ), {
    dom: a,
    destroy: () => {
      l == null || l(), window.removeEventListener("mousemove", f), window.removeEventListener("mouseup", p), a.removeEventListener("mouseenter", m), a.removeEventListener("mouseleave", g), c.removeEventListener(
        "mousedown",
        y
      ), d.removeEventListener(
        "mousedown",
        _
      );
    }
  };
}, W0 = (n) => {
  const e = n.src || void 0, t = n.width || void 0;
  return { url: e, previewWidth: t };
}, NL = '<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>', $L = {
  textAlignment: Fe.textAlignment,
  backgroundColor: Fe.backgroundColor,
  // File name.
  name: {
    default: ""
  },
  // File url.
  url: {
    default: ""
  },
  // File caption.
  caption: {
    default: ""
  },
  showPreview: {
    default: !0
  },
  // File preview width in px.
  previewWidth: {
    default: void 0,
    type: "number"
  }
}, IL = {
  type: "image",
  propSchema: $L,
  content: "none",
  isFileBlock: !0,
  fileBlockAccept: ["image/*"]
}, LL = (n, e) => {
  const t = document.createElement("div");
  t.innerHTML = NL;
  const r = document.createElement("div");
  r.className = "bn-visual-media-wrapper";
  const i = document.createElement("img");
  return i.className = "bn-visual-media", e.resolveFileUrl ? e.resolveFileUrl(n.props.url).then((o) => {
    i.src = o;
  }) : i.src = n.props.url, i.alt = n.props.name || n.props.caption || "BlockNote image", i.contentEditable = "false", i.draggable = !1, r.appendChild(i), ok(
    n,
    e,
    { dom: r },
    r,
    e.dictionary.file_blocks.image.add_button_text,
    t.firstElementChild
  );
}, RL = (n) => {
  if (n.tagName === "IMG")
    return n.closest("figure") ? void 0 : W0(n);
  if (n.tagName === "FIGURE") {
    const e = Pc(n, "img");
    if (!e)
      return;
    const { targetElement: t, caption: r } = e;
    return {
      ...W0(t),
      caption: r
    };
  }
}, BL = (n) => {
  if (!n.props.url) {
    const t = document.createElement("p");
    return t.textContent = "Add image", {
      dom: t
    };
  }
  let e;
  return n.props.showPreview ? (e = document.createElement("img"), e.src = n.props.url, e.alt = n.props.name || n.props.caption || "BlockNote image", n.props.previewWidth && (e.width = n.props.previewWidth)) : (e = document.createElement("a"), e.href = n.props.url, e.textContent = n.props.name || n.props.url), n.props.caption ? n.props.showPreview ? Gf(e, n.props.caption) : zc(e, n.props.caption) : {
    dom: e
  };
}, PL = Ks(IL, {
  render: LL,
  parse: RL,
  toExternalHTML: BL
}), sk = (n, e, t) => ({
  state: r,
  dispatch: i
}) => {
  const o = or(r.doc, n), s = Br(o);
  if (!s.isBlockContainer)
    throw new Error(
      `BlockContainer expected when calling splitBlock, position ${n}`
    );
  const l = [
    {
      type: s.bnBlock.node.type,
      // always keep blockcontainer type
      attrs: t ? { ...s.bnBlock.node.attrs, id: void 0 } : {}
    },
    {
      type: e ? s.blockContent.node.type : r.schema.nodes.paragraph,
      attrs: t ? { ...s.blockContent.node.attrs } : {}
    }
  ];
  return i && r.tr.split(n, 2, l), !0;
}, Hc = (n) => {
  const { blockInfo: e, selectionEmpty: t } = n.transact((o) => ({
    blockInfo: Ic(o),
    selectionEmpty: o.selection.anchor === o.selection.head
  }));
  if (!e.isBlockContainer)
    return !1;
  const { bnBlock: r, blockContent: i } = e;
  return !(i.node.type.name === "toggleListItem" || i.node.type.name === "bulletListItem" || i.node.type.name === "numberedListItem" || i.node.type.name === "checkListItem") || !t ? !1 : n._tiptapEditor.commands.first(({ state: o, chain: s, commands: l }) => [
    () => (
      // Changes list item block to a paragraph block if the content is empty.
      l.command(() => i.node.childCount === 0 ? l.command(
        rt(r.beforePos, {
          type: "paragraph",
          props: {}
        })
      ) : !1)
    ),
    () => (
      // Splits the current block, moving content inside that's after the cursor
      // to a new block of the same type below.
      l.command(() => i.node.childCount > 0 ? (s().deleteSelection().command(sk(o.selection.from, !0)).run(), !0) : !1)
    )
  ]);
}, zL = {
  ...Fe
}, HL = bn({
  name: "toggleListItem",
  content: "inline*",
  group: "blockContent",
  // This is to make sure that the list item Enter keyboard handler takes
  // priority over the default one.
  priority: 90,
  addKeyboardShortcuts() {
    return {
      Enter: () => Hc(this.options.editor),
      "Mod-Shift-6": () => {
        const n = ge(this.editor.state);
        return !n.isBlockContainer || n.blockContent.node.type.spec.content !== "inline*" ? !0 : this.editor.commands.command(
          rt(n.bnBlock.beforePos, {
            type: "toggleListItem",
            props: {}
          })
        );
      }
    };
  },
  parseHTML() {
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e, t;
    return Ft(
      this.name,
      "p",
      {
        ...((e = this.options.domAttributes) == null ? void 0 : e.blockContent) || {},
        ...n
      },
      ((t = this.options.domAttributes) == null ? void 0 : t.inlineContent) || {}
    );
  },
  addNodeView() {
    return ({ HTMLAttributes: n, getPos: e }) => {
      var t, r;
      const { dom: i, contentDOM: o } = Ft(
        this.name,
        "p",
        {
          ...((t = this.options.domAttributes) == null ? void 0 : t.blockContent) || {},
          ...n
        },
        ((r = this.options.domAttributes) == null ? void 0 : r.inlineContent) || {}
      ), s = this.options.editor, l = Pf(e, s, this.editor, this.name), a = rk(
        l,
        s,
        o
      );
      return i.appendChild(a.dom), {
        dom: i,
        contentDOM: o,
        ignoreMutation: a.ignoreMutation,
        destroy: a.destroy
      };
    };
  }
}), VL = ar(
  HL,
  zL
);
function Kf(n, e, t) {
  var r, i, o;
  const s = On.fromSchema(e), l = n, a = document.createElement("div");
  a.setAttribute("data-node-type", "blockGroup");
  for (const f of Array.from(l.childNodes))
    a.appendChild(f.cloneNode(!0));
  let c = s.parse(a, {
    topNode: e.nodes.blockGroup.create()
  });
  ((i = (r = c.firstChild) == null ? void 0 : r.firstChild) == null ? void 0 : i.type.name) === "checkListItem" && (c = c.copy(
    c.content.cut(
      c.firstChild.firstChild.nodeSize + 2
    )
  ));
  const d = (o = c.firstChild) == null ? void 0 : o.firstChild;
  if (!(d != null && d.isTextblock))
    return A.from(c);
  const u = e.nodes[t].create(
    {},
    d.content
  ), h = c.content.cut(
    // +2 for the `blockGroup` node's start and end markers
    d.nodeSize + 2
  );
  if (h.size > 0) {
    const f = c.copy(h);
    return u.content.addToEnd(f);
  }
  return u.content;
}
const UL = {
  ...Fe
}, qL = bn({
  name: "bulletListItem",
  content: "inline*",
  group: "blockContent",
  // This is to make sure that check list parse rules run before, since they
  // both parse `li` elements but check lists are more specific.
  priority: 90,
  addInputRules() {
    return [
      // Creates an unordered list when starting with "-", "+", or "*".
      new Fr({
        find: new RegExp("^[-+*]\\s$"),
        handler: ({ state: n, chain: e, range: t }) => {
          const r = ge(n);
          !r.isBlockContainer || r.blockContent.node.type.spec.content !== "inline*" || r.blockNoteType === "heading" || e().command(
            rt(r.bnBlock.beforePos, {
              type: "bulletListItem",
              props: {}
            })
          ).deleteRange({ from: t.from, to: t.to });
        }
      })
    ];
  },
  addKeyboardShortcuts() {
    return {
      Enter: () => Hc(this.options.editor),
      "Mod-Shift-8": () => {
        const n = ge(this.editor.state);
        return !n.isBlockContainer || n.blockContent.node.type.spec.content !== "inline*" ? !0 : this.editor.commands.command(
          rt(n.bnBlock.beforePos, {
            type: "bulletListItem",
            props: {}
          })
        );
      }
    };
  },
  parseHTML() {
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      },
      // Parse from external HTML.
      {
        tag: "li",
        getAttrs: (n) => {
          var e;
          if (typeof n == "string")
            return !1;
          const t = n.parentElement;
          return t === null ? !1 : t.tagName === "UL" || t.tagName === "DIV" && ((e = t.parentElement) == null ? void 0 : e.tagName) === "UL" ? {} : !1;
        },
        // As `li` elements can contain multiple paragraphs, we need to merge their contents
        // into a single one so that ProseMirror can parse everything correctly.
        getContent: (n, e) => Kf(n, e, this.name),
        node: "bulletListItem"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e, t;
    return Ft(
      this.name,
      // We use a <p> tag, because for <li> tags we'd need a <ul> element to put
      // them in to be semantically correct, which we can't have due to the
      // schema.
      "p",
      {
        ...((e = this.options.domAttributes) == null ? void 0 : e.blockContent) || {},
        ...n
      },
      ((t = this.options.domAttributes) == null ? void 0 : t.inlineContent) || {}
    );
  }
}), jL = ar(
  qL,
  UL
), lk = {
  ...Fe,
  checked: {
    default: !1
  }
}, WL = bn({
  name: "checkListItem",
  content: "inline*",
  group: "blockContent",
  addAttributes() {
    return $c(lk);
  },
  addInputRules() {
    return [
      // Creates a checklist when starting with "[]" or "[X]".
      new Fr({
        find: new RegExp("\\[\\s*\\]\\s$"),
        handler: ({ state: n, chain: e, range: t }) => {
          const r = ge(n);
          !r.isBlockContainer || r.blockContent.node.type.spec.content !== "inline*" || e().command(
            rt(r.bnBlock.beforePos, {
              type: "checkListItem",
              props: {
                checked: !1
              }
            })
          ).deleteRange({ from: t.from, to: t.to });
        }
      }),
      new Fr({
        find: new RegExp("\\[[Xx]\\]\\s$"),
        handler: ({ state: n, chain: e, range: t }) => {
          const r = ge(n);
          !r.isBlockContainer || r.blockContent.node.type.spec.content !== "inline*" || e().command(
            rt(r.bnBlock.beforePos, {
              type: "checkListItem",
              props: {
                checked: !0
              }
            })
          ).deleteRange({ from: t.from, to: t.to });
        }
      })
    ];
  },
  addKeyboardShortcuts() {
    return {
      Enter: () => Hc(this.options.editor),
      "Mod-Shift-9": () => {
        const n = ge(this.editor.state);
        return !n.isBlockContainer || n.blockContent.node.type.spec.content !== "inline*" ? !0 : this.editor.commands.command(
          rt(n.bnBlock.beforePos, {
            type: "checkListItem",
            props: {}
          })
        );
      }
    };
  },
  parseHTML() {
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      },
      // Parse from external HTML.
      {
        tag: "input",
        getAttrs: (n) => typeof n == "string" || n.closest("[data-content-type]") || n.closest("li") ? !1 : n.type === "checkbox" ? { checked: n.checked } : !1,
        node: "checkListItem"
      },
      {
        tag: "li",
        getAttrs: (n) => {
          var e;
          if (typeof n == "string")
            return !1;
          const t = n.parentElement;
          if (t === null)
            return !1;
          if (t.tagName === "UL" || t.tagName === "DIV" && ((e = t.parentElement) == null ? void 0 : e.tagName) === "UL") {
            const r = n.querySelector(
              "input[type=checkbox]"
            ) || null;
            return r === null ? !1 : { checked: r.checked };
          }
          return !1;
        },
        // As `li` elements can contain multiple paragraphs, we need to merge their contents
        // into a single one so that ProseMirror can parse everything correctly.
        getContent: (n, e) => Kf(n, e, this.name),
        node: "checkListItem"
      }
    ];
  },
  // Since there is no HTML checklist element, there isn't really any
  // standardization for what checklists should look like in the DOM. GDocs'
  // and Notion's aren't cross compatible, for example. This implementation
  // has a semantically correct DOM structure (though missing a label for the
  // checkbox) which is also converted correctly to Markdown by remark.
  renderHTML({ node: n, HTMLAttributes: e }) {
    var t, r;
    const i = document.createElement("input");
    i.type = "checkbox", i.checked = n.attrs.checked, n.attrs.checked && i.setAttribute("checked", "");
    const { dom: o, contentDOM: s } = Ft(
      this.name,
      "p",
      {
        ...((t = this.options.domAttributes) == null ? void 0 : t.blockContent) || {},
        ...e
      },
      ((r = this.options.domAttributes) == null ? void 0 : r.inlineContent) || {}
    );
    return o.insertBefore(i, s), { dom: o, contentDOM: s };
  },
  // Need to render node view since the checkbox needs to be able to update the
  // node. This is only possible with a node view as it exposes `getPos`.
  addNodeView() {
    return ({ node: n, getPos: e, editor: t, HTMLAttributes: r }) => {
      var i, o;
      const s = document.createElement("div"), l = document.createElement("div");
      l.contentEditable = "false";
      const a = document.createElement("input");
      a.type = "checkbox", a.checked = n.attrs.checked, n.attrs.checked && a.setAttribute("checked", "");
      const c = () => {
        if (!t.isEditable) {
          a.checked = !a.checked;
          return;
        }
        if (typeof e != "boolean") {
          const h = or(
            t.state.doc,
            e()
          );
          if (h.node.type.name !== "blockContainer")
            throw new Error(
              `Expected blockContainer node, got ${h.node.type.name}`
            );
          this.editor.commands.command(
            rt(h.posBeforeNode, {
              type: "checkListItem",
              props: {
                checked: a.checked
              }
            })
          );
        }
      };
      a.addEventListener("change", c);
      const { dom: d, contentDOM: u } = Ft(
        this.name,
        "p",
        {
          ...((i = this.options.domAttributes) == null ? void 0 : i.blockContent) || {},
          ...r
        },
        ((o = this.options.domAttributes) == null ? void 0 : o.inlineContent) || {}
      );
      if (typeof e != "boolean") {
        const h = "label-" + this.editor.state.doc.resolve(e()).node().attrs.id;
        a.setAttribute("aria-labelledby", h), u.id = h;
      }
      return d.removeChild(u), d.appendChild(s), s.appendChild(l), s.appendChild(u), l.appendChild(a), {
        dom: d,
        contentDOM: u,
        destroy: () => {
          a.removeEventListener("change", c);
        }
      };
    };
  }
}), GL = ar(
  WL,
  lk
), KL = new te("numbered-list-indexing"), JL = () => new G({
  key: KL,
  appendTransaction: (n, e, t) => {
    const r = t.tr;
    r.setMeta("numberedListIndexing", !0);
    let i = !1;
    return t.doc.descendants((o, s) => {
      var l;
      if (o.type.name === "blockContainer" && o.firstChild.type.name === "numberedListItem") {
        let a = `${o.firstChild.attrs.start || 1}`;
        const c = Br({
          posBeforeNode: s,
          node: o
        });
        if (!c.isBlockContainer)
          throw new Error("impossible");
        const d = r.doc.resolve(
          c.bnBlock.beforePos
        ).nodeBefore;
        if (d) {
          const p = Br({
            posBeforeNode: c.bnBlock.beforePos - d.nodeSize,
            node: d
          });
          if (p.blockNoteType === "numberedListItem") {
            if (!p.isBlockContainer)
              throw new Error("impossible");
            const m = p.blockContent.node.attrs.index;
            a = (parseInt(m) + 1).toString();
          }
        }
        const u = c.blockContent.node, h = u.attrs.index, f = ((l = d == null ? void 0 : d.firstChild) == null ? void 0 : l.type.name) !== "numberedListItem";
        if (h !== a || u.attrs.start && !f) {
          i = !0;
          const { start: p, ...m } = u.attrs;
          r.setNodeMarkup(c.blockContent.beforePos, void 0, {
            ...m,
            index: a,
            ...typeof p == "number" && f && {
              start: p
            }
          });
        }
      }
    }), i ? r : null;
  }
}), ak = {
  ...Fe,
  start: { default: void 0, type: "number" }
}, YL = bn({
  name: "numberedListItem",
  content: "inline*",
  group: "blockContent",
  priority: 90,
  addAttributes() {
    return {
      ...$c(ak),
      // the index attribute is only used internally (it's not part of the blocknote schema)
      // that's why it's defined explicitly here, and not part of the prop schema
      index: {
        default: null,
        parseHTML: (n) => n.getAttribute("data-index"),
        renderHTML: (n) => ({
          "data-index": n.index
        })
      }
    };
  },
  addInputRules() {
    return [
      // Creates an ordered list when starting with "1.".
      new Fr({
        find: new RegExp("^(\\d+)\\.\\s$"),
        handler: ({ state: n, chain: e, range: t, match: r }) => {
          const i = ge(n);
          if (!i.isBlockContainer || i.blockContent.node.type.spec.content !== "inline*" || i.blockNoteType === "numberedListItem" || i.blockNoteType === "heading")
            return;
          const o = parseInt(r[1]);
          e().command(
            rt(i.bnBlock.beforePos, {
              type: "numberedListItem",
              props: o === 1 && {} || {
                start: o
              }
            })
          ).deleteRange({ from: t.from, to: t.to });
        }
      })
    ];
  },
  addKeyboardShortcuts() {
    return {
      Enter: () => Hc(this.options.editor),
      "Mod-Shift-7": () => {
        const n = ge(this.editor.state);
        return !n.isBlockContainer || n.blockContent.node.type.spec.content !== "inline*" ? !0 : this.editor.commands.command(
          rt(n.bnBlock.beforePos, {
            type: "numberedListItem",
            props: {}
          })
        );
      }
    };
  },
  addProseMirrorPlugins() {
    return [JL()];
  },
  parseHTML() {
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      },
      // Parse from external HTML.
      {
        tag: "li",
        getAttrs: (n) => {
          var e;
          if (typeof n == "string")
            return !1;
          const t = n.parentElement;
          if (t === null)
            return !1;
          if (t.tagName === "OL" || t.tagName === "DIV" && ((e = t.parentElement) == null ? void 0 : e.tagName) === "OL") {
            const r = parseInt(t.getAttribute("start") || "1") || 1;
            return n.previousSibling || r === 1 ? {} : {
              start: r
            };
          }
          return !1;
        },
        // As `li` elements can contain multiple paragraphs, we need to merge their contents
        // into a single one so that ProseMirror can parse everything correctly.
        getContent: (n, e) => Kf(n, e, this.name),
        priority: 300,
        node: "numberedListItem"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e, t;
    return Ft(
      this.name,
      // We use a <p> tag, because for <li> tags we'd need an <ol> element to
      // put them in to be semantically correct, which we can't have due to the
      // schema.
      "p",
      {
        ...((e = this.options.domAttributes) == null ? void 0 : e.blockContent) || {},
        ...n
      },
      ((t = this.options.domAttributes) == null ? void 0 : t.inlineContent) || {}
    );
  }
}), XL = ar(
  YL,
  ak
), ZL = {
  ...Fe
}, QL = bn({
  name: "paragraph",
  content: "inline*",
  group: "blockContent",
  addKeyboardShortcuts() {
    return {
      "Mod-Alt-0": () => {
        const n = ge(this.editor.state);
        return !n.isBlockContainer || n.blockContent.node.type.spec.content !== "inline*" ? !0 : this.editor.commands.command(
          rt(n.bnBlock.beforePos, {
            type: "paragraph",
            props: {}
          })
        );
      }
    };
  },
  parseHTML() {
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      },
      // Parse from external HTML.
      {
        tag: "p",
        getAttrs: (n) => {
          var e;
          return typeof n == "string" || !((e = n.textContent) != null && e.trim()) ? !1 : {};
        },
        node: "paragraph"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e, t;
    return Ft(
      this.name,
      "p",
      {
        ...((e = this.options.domAttributes) == null ? void 0 : e.blockContent) || {},
        ...n
      },
      ((t = this.options.domAttributes) == null ? void 0 : t.inlineContent) || {}
    );
  }
}), eR = ar(
  QL,
  ZL
), tR = {
  ...Fe
}, nR = bn({
  name: "quote",
  content: "inline*",
  group: "blockContent",
  addInputRules() {
    return [
      // Creates a block quote when starting with ">".
      new Fr({
        find: new RegExp("^>\\s$"),
        handler: ({ state: n, chain: e, range: t }) => {
          const r = ge(n);
          !r.isBlockContainer || r.blockContent.node.type.spec.content !== "inline*" || e().command(
            rt(r.bnBlock.beforePos, {
              type: "quote",
              props: {}
            })
          ).deleteRange({ from: t.from, to: t.to });
        }
      })
    ];
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Alt-q": () => {
        const n = ge(this.editor.state);
        return !n.isBlockContainer || n.blockContent.node.type.spec.content !== "inline*" ? !0 : this.editor.commands.command(
          rt(n.bnBlock.beforePos, {
            type: "quote"
          })
        );
      }
    };
  },
  parseHTML() {
    return [
      // Parse from internal HTML.
      {
        tag: "div[data-content-type=" + this.name + "]",
        contentElement: ".bn-inline-content"
      },
      // Parse from external HTML.
      {
        tag: "blockquote",
        node: "quote",
        getContent: (n, e) => {
          const t = n.cloneNode(!0);
          return LI(t), On.fromSchema(e).parse(t, {
            topNode: e.nodes.paragraph.create()
          }).content;
        }
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e, t;
    return Ft(
      this.name,
      "blockquote",
      {
        ...((e = this.options.domAttributes) == null ? void 0 : e.blockContent) || {},
        ...n
      },
      ((t = this.options.domAttributes) == null ? void 0 : t.inlineContent) || {}
    );
  }
}), rR = ar(
  nR,
  tR
), iR = 35, ck = 120, oR = he.create({
  name: "BlockNoteTableExtension",
  addProseMirrorPlugins: () => [
    tO({
      cellMinWidth: iR,
      defaultCellMinWidth: ck,
      // 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
    }),
    uO()
  ],
  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" }), !0) : !1,
      // 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 n = this.editor.state.selection, e = n.empty, t = n.$head.parentOffset === 0, r = n.$head.node().type.name === "tableParagraph";
        return e && t && r;
      },
      // Enables navigating cells using the tab key.
      Tab: () => this.editor.commands.command(
        ({ state: n, dispatch: e, view: t }) => Ug(1)(n, e, t)
      ),
      "Shift-Tab": () => this.editor.commands.command(
        ({ state: n, dispatch: e, view: t }) => Ug(-1)(n, e, t)
      )
    };
  },
  extendNodeSchema(n) {
    const e = {
      name: n.name,
      options: n.options,
      storage: n.storage
    };
    return {
      tableRole: X(
        R(n, "tableRole", e)
      )
    };
  }
}), sR = {
  textColor: Fe.textColor
}, lR = bn({
  name: "table",
  content: "tableRow+",
  group: "blockContent",
  tableRole: "table",
  marks: "deletion insertion modification",
  isolating: !0,
  parseHTML() {
    return [
      {
        tag: "table"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e, t;
    return Ft(
      this.name,
      "table",
      {
        ...((e = this.options.domAttributes) == null ? void 0 : e.blockContent) || {},
        ...n
      },
      ((t = this.options.domAttributes) == null ? void 0 : t.inlineContent) || {}
    );
  },
  // 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: n, HTMLAttributes: e }) => {
      var t;
      class r extends gw {
        constructor(o, s, l) {
          super(o, s), this.node = o, this.cellMinWidth = s, this.blockContentHTMLAttributes = l;
          const a = document.createElement("div");
          a.className = Rr(
            "bn-block-content",
            l.class
          ), a.setAttribute("data-content-type", "table");
          for (const [h, f] of Object.entries(
            l
          ))
            h !== "class" && a.setAttribute(h, f);
          const c = this.dom, d = document.createElement("div");
          d.className = "tableWrapper-inner", d.appendChild(c.firstChild), c.appendChild(d), a.appendChild(c);
          const u = document.createElement("div");
          u.className = "table-widgets-container", u.style.position = "relative", c.appendChild(u), this.dom = a;
        }
        ignoreMutation(o) {
          return !o.target.closest(".tableWrapper-inner") || super.ignoreMutation(o);
        }
      }
      return new r(n, ck, {
        ...((t = this.options.domAttributes) == null ? void 0 : t.blockContent) || {},
        ...e
      });
    };
  }
}), aR = bn({
  name: "tableParagraph",
  group: "tableContent",
  content: "inline*",
  parseHTML() {
    return [
      {
        tag: "p",
        getAttrs: (n) => {
          if (typeof n == "string" || !n.textContent || !n.closest("[data-content-type]"))
            return !1;
          const e = n.parentElement;
          return e === null ? !1 : e.tagName === "TD" || e.tagName === "TH" ? {} : !1;
        },
        node: "tableParagraph"
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["p", n, 0];
  }
}), cR = Mt.create({
  name: "tableRow",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "(tableCell | tableHeader)+",
  tableRole: "row",
  marks: "deletion insertion modification",
  parseHTML() {
    return [{ tag: "tr" }];
  },
  renderHTML({ HTMLAttributes: n }) {
    return [
      "tr",
      Tt(this.options.HTMLAttributes, n),
      0
    ];
  }
});
function G0(n, e) {
  const t = On.fromSchema(e).parse(n, {
    topNode: e.nodes.blockGroup.create()
  }), r = [];
  return t.content.descendants((i) => {
    if (i.isInline)
      return r.push(i), !1;
  }), A.fromArray(r);
}
const dR = ar(
  lR,
  sR,
  [
    oR,
    aR,
    m2.extend({
      /**
       * 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+",
      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: (n, e) => G0(n, e)
          }
        ];
      }
    }),
    p2.extend({
      content: "tableContent+",
      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: (n, e) => G0(n, e)
          }
        ];
      }
    }),
    cR
  ]
), K0 = (n) => {
  const e = n.src || void 0, t = n.width || void 0;
  return { url: e, previewWidth: t };
}, uR = '<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>', hR = {
  textAlignment: Fe.textAlignment,
  backgroundColor: Fe.backgroundColor,
  // File name.
  name: {
    default: ""
  },
  // File url.
  url: {
    default: ""
  },
  // File caption.
  caption: {
    default: ""
  },
  showPreview: {
    default: !0
  },
  // File preview width in px.
  previewWidth: {
    default: void 0,
    type: "number"
  }
}, fR = {
  type: "video",
  propSchema: hR,
  content: "none",
  isFileBlock: !0,
  fileBlockAccept: ["video/*"]
}, pR = (n, e) => {
  const t = document.createElement("div");
  t.innerHTML = uR;
  const r = document.createElement("div");
  r.className = "bn-visual-media-wrapper";
  const i = document.createElement("video");
  return i.className = "bn-visual-media", e.resolveFileUrl ? e.resolveFileUrl(n.props.url).then((o) => {
    i.src = o;
  }) : i.src = n.props.url, i.controls = !0, i.contentEditable = "false", i.draggable = !1, i.width = n.props.previewWidth, r.appendChild(i), ok(
    n,
    e,
    { dom: r },
    r,
    e.dictionary.file_blocks.video.add_button_text,
    t.firstElementChild
  );
}, mR = (n) => {
  if (n.tagName === "VIDEO")
    return n.closest("figure") ? void 0 : K0(n);
  if (n.tagName === "FIGURE") {
    const e = Pc(n, "video");
    if (!e)
      return;
    const { targetElement: t, caption: r } = e;
    return {
      ...K0(t),
      caption: r
    };
  }
}, gR = (n) => {
  if (!n.props.url) {
    const t = document.createElement("p");
    return t.textContent = "Add video", {
      dom: t
    };
  }
  let e;
  return n.props.showPreview ? (e = document.createElement("video"), e.src = n.props.url, n.props.previewWidth && (e.width = n.props.previewWidth)) : (e = document.createElement("a"), e.href = n.props.url, e.textContent = n.props.name || n.props.url), n.props.caption ? n.props.showPreview ? Gf(e, n.props.caption) : zc(e, n.props.caption) : {
    dom: e
  };
}, bR = Ks(fR, {
  render: pR,
  parse: mR,
  toExternalHTML: gR
}), dk = {
  paragraph: eR,
  heading: FL,
  quote: rR,
  codeBlock: yL,
  toggleListItem: VL,
  bulletListItem: jL,
  numberedListItem: XL,
  checkListItem: GL,
  table: dR,
  file: AL,
  image: PL,
  video: bR,
  audio: mL
}, yR = H1(dk), uk = {
  bold: Yr(t2, "boolean"),
  italic: Yr(c2, "boolean"),
  underline: Yr(f2, "boolean"),
  strike: Yr(h2, "boolean"),
  code: Yr(i2, "boolean"),
  textColor: vL,
  backgroundColor: wL
};
j1(uk);
const hk = {
  text: { config: "text", implementation: {} },
  link: { config: "link", implementation: {} }
};
q1(
  hk
);
function fk(n, e) {
  return n in e.schema.blockSchema && e.schema.blockSchema[n] === yR[n];
}
function _R(n, e, t) {
  return e.type === n && e.type in t.schema.blockSchema && fk(e.type, t);
}
function J0(n) {
  return n instanceof le;
}
function eu(n) {
  return n && Object.fromEntries(
    Object.entries(n).filter(([, e]) => e !== void 0)
  );
}
class Vc {
  constructor(e) {
    E(this, "blockSpecs"), E(this, "inlineContentSpecs"), E(this, "styleSpecs"), E(this, "blockSchema"), E(this, "inlineContentSchema"), E(this, "styleSchema"), E(this, "BlockNoteEditor", "only for types"), E(this, "Block", "only for types"), E(this, "PartialBlock", "only for types"), this.blockSpecs = eu(e == null ? void 0 : e.blockSpecs) || dk, this.inlineContentSpecs = eu(e == null ? void 0 : e.inlineContentSpecs) || hk, this.styleSpecs = eu(e == null ? void 0 : e.styleSpecs) || uk, this.blockSchema = H1(this.blockSpecs), this.inlineContentSchema = q1(
      this.inlineContentSpecs
    ), this.styleSchema = j1(this.styleSpecs);
  }
  static create(e) {
    return new Vc(e);
  }
}
const wR = {
  type: "pageBreak",
  propSchema: {},
  content: "none",
  isFileBlock: !1,
  isSelectable: !1
}, kR = () => {
  const n = document.createElement("div");
  return n.className = "bn-page-break", n.setAttribute("data-page-break", ""), {
    dom: n
  };
}, vR = (n) => {
  if (n.tagName === "DIV" && n.hasAttribute("data-page-break"))
    return {
      type: "pageBreak"
    };
}, CR = () => {
  const n = document.createElement("div");
  return n.setAttribute("data-page-break", ""), {
    dom: n
  };
}, SR = Ks(wR, {
  render: kR,
  parse: vR,
  toExternalHTML: CR
});
Vc.create({
  blockSpecs: {
    pageBreak: SR
  }
});
function ER(n) {
  return n.transact((e) => {
    const t = or(e.doc, e.selection.anchor);
    if (e.selection instanceof le)
      return {
        type: "cell",
        anchorBlockId: t.node.attrs.id,
        anchorCellOffset: e.selection.$anchorCell.pos - t.posBeforeNode,
        headCellOffset: e.selection.$headCell.pos - t.posBeforeNode
      };
    if (e.selection instanceof P)
      return {
        type: "node",
        anchorBlockId: t.node.attrs.id
      };
    {
      const r = or(e.doc, e.selection.head);
      return {
        type: "text",
        anchorBlockId: t.node.attrs.id,
        headBlockId: r.node.attrs.id,
        anchorOffset: e.selection.anchor - t.posBeforeNode,
        headOffset: e.selection.head - r.posBeforeNode
      };
    }
  });
}
function xR(n, e) {
  var t, r;
  const i = (t = Nt(e.anchorBlockId, n.doc)) == null ? void 0 : t.posBeforeNode;
  if (i === void 0)
    throw new Error(
      `Could not find block with ID ${e.anchorBlockId} to update selection`
    );
  let o;
  if (e.type === "cell")
    o = le.create(
      n.doc,
      i + e.anchorCellOffset,
      i + e.headCellOffset
    );
  else if (e.type === "node")
    o = P.create(n.doc, i + 1);
  else {
    const s = (r = Nt(e.headBlockId, n.doc)) == null ? void 0 : r.posBeforeNode;
    if (s === void 0)
      throw new Error(
        `Could not find block with ID ${e.headBlockId} to update selection`
      );
    o = L.create(
      n.doc,
      i + e.anchorOffset,
      s + e.headOffset
    );
  }
  n.setSelection(o);
}
function mh(n) {
  return n.map((e) => e.type === "columnList" ? e.children.map((t) => mh(t.children)).flat() : {
    ...e,
    children: mh(e.children)
  }).flat();
}
function pk(n, e, t) {
  n.transact((r) => {
    var i;
    const o = ((i = n.getSelection()) == null ? void 0 : i.blocks) || [
      n.getTextCursorPosition().block
    ], s = ER(n);
    n.removeBlocks(o), n.insertBlocks(mh(o), e, t), xR(r, s);
  });
}
function mk(n) {
  return !n || n.type !== "columnList";
}
function gk(n, e, t) {
  let r, i;
  if (e ? e.children.length > 0 ? (r = e.children[e.children.length - 1], i = "after") : (r = e, i = "before") : t && (r = t, i = "before"), !r || !i)
    return;
  const o = n.getParentBlock(r);
  return mk(o) ? { referenceBlock: r, placement: i } : gk(
    n,
    i === "after" ? r : n.getPrevBlock(r),
    o
  );
}
function bk(n, e, t) {
  let r, i;
  if (e ? e.children.length > 0 ? (r = e.children[0], i = "before") : (r = e, i = "after") : t && (r = t, i = "after"), !r || !i)
    return;
  const o = n.getParentBlock(r);
  return mk(o) ? { referenceBlock: r, placement: i } : bk(
    n,
    i === "before" ? r : n.getNextBlock(r),
    o
  );
}
function DR(n) {
  n.transact(() => {
    const e = n.getSelection(), t = (e == null ? void 0 : e.blocks[0]) || n.getTextCursorPosition().block, r = gk(
      n,
      n.getPrevBlock(t),
      n.getParentBlock(t)
    );
    r && pk(
      n,
      r.referenceBlock,
      r.placement
    );
  });
}
function AR(n) {
  n.transact(() => {
    const e = n.getSelection(), t = (e == null ? void 0 : e.blocks[(e == null ? void 0 : e.blocks.length) - 1]) || n.getTextCursorPosition().block, r = bk(
      n,
      n.getNextBlock(t),
      n.getParentBlock(t)
    );
    r && pk(
      n,
      r.referenceBlock,
      r.placement
    );
  });
}
function TR(n, e, t) {
  const { $from: r, $to: i } = n.selection, o = r.blockRange(
    i,
    (f) => f.childCount > 0 && (f.type.name === "blockGroup" || f.type.name === "column")
    // change necessary to not look at first item child type
  );
  if (!o)
    return !1;
  const s = o.startIndex;
  if (s === 0)
    return !1;
  const l = o.parent.child(s - 1);
  if (l.type !== e)
    return !1;
  const a = l.lastChild && l.lastChild.type === t, c = A.from(a ? e.create() : null), d = new O(
    A.from(
      e.create(null, A.from(t.create(null, c)))
      // change necessary to create "groupType" instead of parent.type
    ),
    a ? 3 : 1,
    0
  ), u = o.start, h = o.end;
  return n.step(
    new Ae(
      u - (a ? 3 : 1),
      h,
      u,
      h,
      d,
      1,
      !0
    )
  ).scrollIntoView(), !0;
}
function yk(n) {
  return n.transact((e) => TR(
    e,
    n.pmSchema.nodes.blockContainer,
    n.pmSchema.nodes.blockGroup
  ));
}
function MR(n) {
  n._tiptapEditor.commands.liftListItem("blockContainer");
}
function OR(n) {
  return n.transact((e) => {
    const { bnBlock: t } = Ic(e);
    return e.doc.resolve(t.beforePos).nodeBefore !== null;
  });
}
function FR(n) {
  return n.transact((e) => {
    const { bnBlock: t } = Ic(e);
    return e.doc.resolve(t.beforePos).depth > 1;
  });
}
function NR(n, e) {
  const t = typeof e == "string" ? e : e.id, r = Ue(n), i = Nt(t, n);
  if (i)
    return Se(i.node, r);
}
function $R(n, e) {
  const t = typeof e == "string" ? e : e.id, r = Nt(t, n), i = Ue(n);
  if (!r)
    return;
  const o = n.resolve(r.posBeforeNode).nodeBefore;
  if (o)
    return Se(o, i);
}
function IR(n, e) {
  const t = typeof e == "string" ? e : e.id, r = Nt(t, n), i = Ue(n);
  if (!r)
    return;
  const o = n.resolve(
    r.posBeforeNode + r.node.nodeSize
  ).nodeAfter;
  if (o)
    return Se(o, i);
}
function LR(n, e) {
  const t = typeof e == "string" ? e : e.id, r = Ue(n), i = Nt(t, n);
  if (!i)
    return;
  const o = n.resolve(i.posBeforeNode), s = o.node(), l = o.node(-1), a = l.type.name !== "doc" ? s.type.name === "blockGroup" ? l : s : void 0;
  if (a)
    return Se(a, r);
}
function RR(n, e, t, r = { updateSelection: !0 }) {
  let { from: i, to: o } = typeof e == "number" ? { from: e, to: e } : { from: e.from, to: e.to }, s = !0, l = !0, a = "";
  if (t.forEach((c) => {
    c.check(), s && c.isText && c.marks.length === 0 ? a += c.text : s = !1, l = l ? c.isBlock : !1;
  }), i === o && l) {
    const { parent: c } = n.doc.resolve(i);
    c.isTextblock && !c.type.spec.code && !c.childCount && (i -= 1, o += 1);
  }
  return s ? n.insertText(a, i, o) : n.replaceWith(i, o, t), r.updateSelection && G_(n, n.steps.length - 1, -1), !0;
}
function BR(n) {
  const e = Ue(n);
  if (n.selection.empty || "node" in n.selection)
    return;
  const t = n.doc.resolve(
    or(n.doc, n.selection.from).posBeforeNode
  ), r = n.doc.resolve(
    or(n.doc, n.selection.to).posBeforeNode
  ), i = (c, d) => {
    const u = t.posAtIndex(c, d), h = n.doc.resolve(u).nodeAfter;
    if (!h)
      throw new Error(
        `Error getting selection - node not found at position ${u}`
      );
    return Se(h, e);
  }, o = [], s = t.sharedDepth(r.pos), l = t.index(s), a = r.index(s);
  if (t.depth > s) {
    o.push(Se(t.nodeAfter, e));
    for (let c = t.depth; c > s; c--)
      if (t.node(c).type.isInGroup("childContainer")) {
        const d = t.index(c) + 1, u = t.node(c).childCount;
        for (let h = d; h < u; h++)
          o.push(i(h, c));
      }
  } else
    o.push(i(l, s));
  for (let c = l + 1; c <= a; c++)
    o.push(i(c, s));
  if (o.length === 0)
    throw new Error(
      `Error getting selection - selection doesn't span any blocks (${n.selection})`
    );
  return {
    blocks: o
  };
}
function PR(n, e, t) {
  const r = typeof e == "string" ? e : e.id, i = typeof t == "string" ? t : t.id, o = Ue(n), s = Ys(o);
  if (r === i)
    throw new Error(
      `Attempting to set selection with the same anchor and head blocks (id ${r})`
    );
  const l = Nt(r, n.doc);
  if (!l)
    throw new Error(`Block with ID ${r} not found`);
  const a = Nt(i, n.doc);
  if (!a)
    throw new Error(`Block with ID ${i} not found`);
  const c = Br(l), d = Br(a), u = s.blockSchema[c.blockNoteType], h = s.blockSchema[d.blockNoteType];
  if (!c.isBlockContainer || u.content === "none")
    throw new Error(
      `Attempting to set selection anchor in block without content (id ${r})`
    );
  if (!d.isBlockContainer || h.content === "none")
    throw new Error(
      `Attempting to set selection anchor in block without content (id ${i})`
    );
  let f, p;
  if (u.content === "table") {
    const m = we.get(c.blockContent.node);
    f = c.blockContent.beforePos + m.positionAt(0, 0, c.blockContent.node) + 1 + 2;
  } else
    f = c.blockContent.beforePos + 1;
  if (h.content === "table") {
    const m = we.get(d.blockContent.node), g = d.blockContent.beforePos + m.positionAt(
      m.height - 1,
      m.width - 1,
      d.blockContent.node
    ) + 1, y = n.doc.resolve(g).nodeAfter.nodeSize;
    p = g + y - 2;
  } else
    p = d.blockContent.afterPos - 1;
  n.setSelection(L.create(n.doc, f, p));
}
function zR(n) {
  const e = Ue(n);
  let t = n.selection.$from, r = n.selection.$to;
  for (; r.parentOffset >= r.parent.nodeSize - 2 && r.depth > 0; )
    r = n.doc.resolve(r.pos + 1);
  for (; r.parentOffset === 0 && r.depth > 0; )
    r = n.doc.resolve(r.pos - 1);
  for (; t.parentOffset === 0 && t.depth > 0; )
    t = n.doc.resolve(t.pos - 1);
  for (; t.parentOffset >= t.parent.nodeSize - 2 && t.depth > 0; )
    t = n.doc.resolve(t.pos + 1);
  const i = HI(
    n.doc.slice(t.pos, r.pos, !0),
    e
  );
  return {
    _meta: {
      startPos: t.pos,
      endPos: r.pos
    },
    ...i
  };
}
function HR(n) {
  const { bnBlock: e } = Ic(n), t = Ue(n.doc), r = n.doc.resolve(e.beforePos), i = r.nodeBefore, o = n.doc.resolve(e.afterPos).nodeAfter;
  let s;
  return r.depth > 1 && (s = r.node(), s.type.isInGroup("bnBlock") || (s = r.node(r.depth - 1))), {
    block: Se(e.node, t),
    prevBlock: i === null ? void 0 : Se(i, t),
    nextBlock: o === null ? void 0 : Se(o, t),
    parentBlock: s === void 0 ? void 0 : Se(s, t)
  };
}
function _k(n, e, t = "start") {
  const r = typeof e == "string" ? e : e.id, i = Ue(n.doc), o = Ys(i), s = Nt(r, n.doc);
  if (!s)
    throw new Error(`Block with ID ${r} not found`);
  const l = Br(s), a = o.blockSchema[l.blockNoteType].content;
  if (l.isBlockContainer) {
    const c = l.blockContent;
    if (a === "none") {
      n.setSelection(P.create(n.doc, c.beforePos));
      return;
    }
    if (a === "inline")
      t === "start" ? n.setSelection(
        L.create(n.doc, c.beforePos + 1)
      ) : n.setSelection(
        L.create(n.doc, c.afterPos - 1)
      );
    else if (a === "table")
      t === "start" ? n.setSelection(
        L.create(n.doc, c.beforePos + 4)
      ) : n.setSelection(
        L.create(n.doc, c.afterPos - 4)
      );
    else
      throw new In(a);
  } else {
    const c = t === "start" ? l.childContainer.node.firstChild : l.childContainer.node.lastChild;
    _k(n, c.attrs.id, t);
  }
}
let Wi;
async function Jf() {
  if (Wi)
    return Wi;
  const n = await Promise.all([
    import("./index-eQFSwyun.js"),
    import("./index-6CYX9x9d.js"),
    import("./index-Gd_Tx3fp.js"),
    import("./index-Qh6QH6OP.js"),
    import("./index-BH6kCplX.js"),
    import("./index-Drx7d3x_.js"),
    import("./index-Cm-QMPO9.js"),
    import("./index-CdswoX8u.js"),
    import("./index-DSJwFkSU.js"),
    import("./index-BZTjh2Y4.js")
  ]);
  return Wi = {
    rehypeParse: n[0],
    rehypeStringify: n[1],
    unified: n[2],
    hastUtilFromDom: n[3],
    rehypeRemark: n[4],
    remarkGfm: n[5],
    remarkStringify: n[6],
    remarkParse: n[7],
    remarkRehype: n[8],
    rehypeFormat: n[9]
  }, Wi;
}
function VR() {
  const n = (e) => {
    let t = e.children.length;
    for (let r = 0; r < t; r++) {
      const i = e.children[r];
      if (i.type === "element" && (n(i), i.tagName === "u"))
        if (i.children.length > 0) {
          e.children.splice(r, 1, ...i.children);
          const o = i.children.length - 1;
          t += o, r += o;
        } else
          e.children.splice(r, 1), t--, r--;
    }
  };
  return n;
}
function UR() {
  const n = Wi;
  if (!n)
    throw new Error(
      "addSpacesToCheckboxes requires ESM dependencies to be initialized"
    );
  const e = (t) => {
    var r;
    if (t.children && "length" in t.children && t.children.length)
      for (let i = t.children.length - 1; i >= 0; i--) {
        const o = t.children[i], s = i + 1 < t.children.length ? t.children[i + 1] : void 0;
        o.type === "element" && o.tagName === "input" && ((r = o.properties) == null ? void 0 : r.type) === "checkbox" && (s == null ? void 0 : s.type) === "element" && s.tagName === "p" ? (s.tagName = "span", s.children.splice(
          0,
          0,
          n.hastUtilFromDom.fromDom(
            document.createTextNode(" ")
          )
        )) : e(o);
      }
  };
  return e;
}
function Yf(n) {
  const e = Wi;
  if (!e)
    throw new Error(
      "cleanHTMLToMarkdown requires ESM dependencies to be initialized"
    );
  return e.unified.unified().use(e.rehypeParse.default, { fragment: !0 }).use(VR).use(UR).use(e.rehypeRemark.default).use(e.remarkGfm.default).use(e.remarkStringify.default, {
    handlers: { text: (t) => t.value }
  }).processSync(n).value;
}
async function qR(n, e, t, r) {
  await Jf();
  const i = Bc(e, t).exportBlocks(n, r);
  return Yf(i);
}
function jR(n) {
  return Array.prototype.indexOf.call(n.parentElement.childNodes, n);
}
function WR(n) {
  return n.nodeType === 3 && !/\S/.test(n.nodeValue || "");
}
function GR(n) {
  n.querySelectorAll("li > ul, li > ol").forEach((e) => {
    const t = jR(e), r = e.parentElement, i = Array.from(r.childNodes).slice(
      t + 1
    );
    e.remove(), i.forEach((o) => {
      o.remove();
    }), r.insertAdjacentElement("afterend", e), i.reverse().forEach((o) => {
      if (WR(o))
        return;
      const s = document.createElement("li");
      s.append(o), e.insertAdjacentElement("afterend", s);
    }), r.childNodes.length === 0 && r.remove();
  });
}
function KR(n) {
  n.querySelectorAll("li + ul, li + ol").forEach((e) => {
    var t, r;
    const i = e.previousElementSibling, o = document.createElement("div");
    i.insertAdjacentElement("afterend", o), o.append(i);
    const s = document.createElement("div");
    for (s.setAttribute("data-node-type", "blockGroup"), o.append(s); ((t = o.nextElementSibling) == null ? void 0 : t.nodeName) === "UL" || ((r = o.nextElementSibling) == null ? void 0 : r.nodeName) === "OL"; )
      s.append(o.nextElementSibling);
  });
}
let Y0 = null;
function JR() {
  return Y0 || (Y0 = document.implementation.createHTMLDocument("title"));
}
function wk(n) {
  if (typeof n == "string") {
    const e = JR().createElement("div");
    e.innerHTML = n, n = e;
  }
  return GR(n), KR(n), n;
}
async function kk(n, e) {
  const t = wk(n), r = On.fromSchema(e).parse(t, {
    topNode: e.nodes.blockGroup.create()
  }), i = [];
  for (let o = 0; o < r.childCount; o++)
    i.push(Se(r.child(o), e));
  return i;
}
function YR(n, e) {
  const t = e.value ? e.value : "", r = {};
  e.lang && (r["data-language"] = e.lang);
  let i = {
    type: "element",
    tagName: "code",
    properties: r,
    children: [{ type: "text", value: t }]
  };
  return e.meta && (i.data = { meta: e.meta }), n.patch(e, i), i = n.applyData(e, i), i = {
    type: "element",
    tagName: "pre",
    properties: {},
    children: [i]
  }, n.patch(e, i), i;
}
async function vk(n) {
  const e = await Jf();
  return e.unified.unified().use(e.remarkParse.default).use(e.remarkGfm.default).use(e.remarkRehype.default, {
    handlers: {
      ...e.remarkRehype.defaultHandlers,
      code: YR
    }
  }).use(e.rehypeStringify.default).processSync(n).value;
}
async function XR(n, e) {
  const t = await vk(n);
  return kk(t, e);
}
const Xf = [
  "vscode-editor-data",
  "blocknote/html",
  "text/markdown",
  "text/html",
  "text/plain",
  "Files"
];
function ZR(n, e) {
  if (!n.startsWith(".") || !e.startsWith("."))
    throw new Error("The strings provided are not valid file extensions.");
  return n === e;
}
function QR(n, e) {
  const t = n.split("/"), r = e.split("/");
  if (t.length !== 2)
    throw new Error(`The string ${n} is not a valid MIME type.`);
  if (r.length !== 2)
    throw new Error(`The string ${e} is not a valid MIME type.`);
  return t[1] === "*" || r[1] === "*" ? t[0] === r[0] : (t[0] === "*" || r[0] === "*" || t[0] === r[0]) && t[1] === r[1];
}
function X0(n, e, t, r = "after") {
  let i;
  return Array.isArray(e.content) && e.content.length === 0 ? i = n.updateBlock(e, t).id : i = n.insertBlocks(
    [t],
    e,
    r
  )[0].id, i;
}
async function Ck(n, e) {
  var t;
  if (!e.uploadFile) {
    console.warn(
      "Attempted ot insert file, but uploadFile is not set in the BlockNote editor options"
    );
    return;
  }
  const r = "dataTransfer" in n ? n.dataTransfer : n.clipboardData;
  if (r === null)
    return;
  let i = null;
  for (const l of Xf)
    if (r.types.includes(l)) {
      i = l;
      break;
    }
  if (i !== "Files")
    return;
  const o = r.items;
  if (!o)
    return;
  n.preventDefault();
  const s = Object.values(e.schema.blockSchema).filter(
    (l) => l.isFileBlock
  );
  for (let l = 0; l < o.length; l++) {
    let a = "file";
    for (const d of s)
      for (const u of d.fileBlockAccept || []) {
        const h = u.startsWith("."), f = o[l].getAsFile();
        if (f && (!h && f.type && QR(o[l].type, u) || h && ZR(
          "." + f.name.split(".").pop(),
          u
        ))) {
          a = d.type;
          break;
        }
      }
    const c = o[l].getAsFile();
    if (c) {
      const d = {
        type: a,
        props: {
          name: c.name
        }
      };
      let u;
      if (n.type === "paste") {
        const p = e.getTextCursorPosition().block;
        u = X0(e, p, d);
      } else if (n.type === "drop") {
        const p = {
          left: n.clientX,
          top: n.clientY
        }, m = (t = e.prosemirrorView) == null ? void 0 : t.posAtCoords(p);
        if (!m)
          return;
        u = e.transact((g) => {
          var y;
          const _ = or(g.doc, m.pos), b = (y = e.prosemirrorView) == null ? void 0 : y.dom.querySelector(
            `[data-id="${_.node.attrs.id}"]`
          ), k = b == null ? void 0 : b.getBoundingClientRect();
          return X0(
            e,
            e.getBlock(_.node.attrs.id),
            d,
            k && (k.top + k.bottom) / 2 > p.top ? "before" : "after"
          );
        });
      } else
        return;
      const h = await e.uploadFile(c, u), f = typeof h == "string" ? {
        props: {
          url: h
        }
      } : { ...h };
      e.updateBlock(u, f);
    }
  }
}
const eB = (n) => he.create({
  name: "dropFile",
  addProseMirrorPlugins() {
    return [
      new G({
        props: {
          handleDOMEvents: {
            drop(e, t) {
              if (!n.isEditable)
                return;
              let r = null;
              for (const i of Xf)
                if (t.dataTransfer.types.includes(i)) {
                  r = i;
                  break;
                }
              return r === null ? !0 : r === "Files" ? (Ck(t, n), !0) : !1;
            }
          }
        }
      })
    ];
  }
}), tB = /(^|\n) {0,3}#{1,6} {1,8}[^\n]{1,64}\r?\n\r?\n\s{0,32}\S/, nB = /(_|__|\*|\*\*|~~|==|\+\+)(?!\s)(?:[^\s](?:.{0,62}[^\s])?|\S)(?=\1)/, rB = /\[[^\]]{1,128}\]\(https?:\/\/\S{1,999}\)/, iB = /(?:\s|^)`(?!\s)(?:[^\s`](?:[^`]{0,46}[^\s`])?|[^\s`])`([^\w]|$)/, oB = /(?:^|\n)\s{0,5}-\s{1}[^\n]+\n\s{0,15}-\s/, sB = /(?:^|\n)\s{0,5}\d+\.\s{1}[^\n]+\n\s{0,15}\d+\.\s/, lB = /\n{2} {0,3}-{2,48}\n{2}/, aB = /(?:\n|^)(```|~~~|\$\$)(?!`|~)[^\s]{0,64} {0,64}[^\n]{0,64}\n[\s\S]{0,9999}?\s*\1 {0,64}(?:\n+|$)/, cB = /(?:\n|^)(?!\s)\w[^\n]{0,64}\r?\n(-|=)\1{0,64}\n\n\s{0,64}(\w|$)/, dB = /(?:^|(\r?\n\r?\n))( {0,3}>[^\n]{1,333}\n){1,999}($|(\r?\n))/, uB = /^\s*\|(.+\|)+\s*$/m, hB = /^\s*\|(\s*[-:]+[-:]\s*\|)+\s*$/m, fB = /^\s*\|(.+\|)+\s*$/m, pB = (n) => tB.test(n) || nB.test(n) || rB.test(n) || iB.test(n) || oB.test(n) || sB.test(n) || lB.test(n) || aB.test(n) || cB.test(n) || dB.test(n) || uB.test(n) || hB.test(n) || fB.test(n);
async function mB(n, e) {
  const { schema: t } = e.state;
  if (!n.clipboardData)
    return !1;
  const r = n.clipboardData.getData("text/plain");
  if (!r)
    return !1;
  if (!t.nodes.codeBlock)
    return e.pasteText(r), !0;
  const i = n.clipboardData.getData("vscode-editor-data"), o = i ? JSON.parse(i) : void 0, s = o == null ? void 0 : o.mode;
  return s ? (e.pasteHTML(
    `<pre><code class="language-${s}">${r.replace(
      /\r\n?/g,
      `
`
    )}</code></pre>`
  ), !0) : !1;
}
function gB({
  event: n,
  editor: e,
  prioritizeMarkdownOverHTML: t,
  plainTextAsMarkdown: r
}) {
  var i;
  if (e.transact(
    (l) => l.selection.$from.parent.type.spec.code && l.selection.$to.parent.type.spec.code
  )) {
    const l = (i = n.clipboardData) == null ? void 0 : i.getData("text/plain");
    if (l)
      return e.pasteText(l), !0;
  }
  let o;
  for (const l of Xf)
    if (n.clipboardData.types.includes(l)) {
      o = l;
      break;
    }
  if (!o)
    return !0;
  if (o === "vscode-editor-data")
    return mB(n, e.prosemirrorView), !0;
  if (o === "Files")
    return Ck(n, e), !0;
  const s = n.clipboardData.getData(o);
  if (o === "blocknote/html")
    return e.pasteHTML(s, !0), !0;
  if (o === "text/markdown")
    return e.pasteMarkdown(s), !0;
  if (t) {
    const l = n.clipboardData.getData("text/plain");
    if (pB(l))
      return e.pasteMarkdown(l), !0;
  }
  return o === "text/html" ? (e.pasteHTML(s), !0) : r ? (e.pasteMarkdown(s), !0) : (e.pasteText(s), !0);
}
const bB = (n, e) => he.create({
  name: "pasteFromClipboard",
  addProseMirrorPlugins() {
    return [
      new G({
        props: {
          handleDOMEvents: {
            paste(t, r) {
              if (r.preventDefault(), !!n.isEditable)
                return e({
                  event: r,
                  editor: n,
                  defaultPasteHandler: ({
                    prioritizeMarkdownOverHTML: i = !0,
                    plainTextAsMarkdown: o = !0
                  } = {}) => gB({
                    event: r,
                    editor: n,
                    prioritizeMarkdownOverHTML: i,
                    plainTextAsMarkdown: o
                  })
                });
            }
          }
        }
      })
    ];
  }
});
function Sk(n) {
  const e = [];
  return n.descendants((t) => {
    var r, i;
    const o = Ue(t);
    return t.type.name === "blockContainer" && ((r = t.firstChild) == null ? void 0 : r.type.name) === "blockGroup" ? !0 : t.type.name === "columnList" && t.childCount === 1 ? ((i = t.firstChild) == null || i.forEach((s) => {
      e.push(Se(s, o));
    }), !1) : t.type.isInGroup("bnBlock") ? (e.push(Se(t, o)), !1) : !0;
  }), e;
}
function yB(n, e, t) {
  var r;
  let i = !1;
  const o = n.state.selection instanceof le;
  if (!o) {
    const a = n.state.doc.slice(
      n.state.selection.from,
      n.state.selection.to,
      !1
    ).content, c = [];
    for (let d = 0; d < a.childCount; d++)
      c.push(a.child(d));
    i = c.find(
      (d) => d.type.isInGroup("bnBlock") || d.type.name === "blockGroup" || d.type.spec.group === "blockContent"
    ) === void 0, i && (e = a);
  }
  let s;
  const l = Bc(
    n.state.schema,
    t
  );
  if (o) {
    ((r = e.firstChild) == null ? void 0 : r.type.name) === "table" && (e = e.firstChild.content);
    const a = U1(
      e,
      t.schema.inlineContentSchema,
      t.schema.styleSchema
    );
    s = `<table>${l.exportInlineContent(
      a,
      {}
    )}</table>`;
  } else if (i) {
    const a = Lc(
      e,
      t.schema.inlineContentSchema,
      t.schema.styleSchema
    );
    s = l.exportInlineContent(a, {});
  } else {
    const a = Sk(e);
    s = l.exportBlocks(a, {});
  }
  return s;
}
function Ek(n, e) {
  "node" in n.state.selection && n.state.selection.node.type.spec.group === "blockContent" && e.transact(
    (s) => s.setSelection(
      new P(s.doc.resolve(n.state.selection.from - 1))
    )
  );
  const t = n.serializeForClipboard(
    n.state.selection.content()
  ).dom.innerHTML, r = n.state.selection.content().content, i = yB(
    n,
    r,
    e
  ), o = Yf(i);
  return { clipboardHTML: t, externalHTML: i, markdown: o };
}
const Z0 = () => {
  const n = window.getSelection();
  if (!n || n.isCollapsed)
    return !0;
  let e = n.focusNode;
  for (; e; ) {
    if (e instanceof HTMLElement && e.getAttribute("contenteditable") === "false")
      return !0;
    e = e.parentElement;
  }
  return !1;
}, Q0 = (n, e, t) => {
  t.preventDefault(), t.clipboardData.clearData();
  const { clipboardHTML: r, externalHTML: i, markdown: o } = Ek(
    e,
    n
  );
  t.clipboardData.setData("blocknote/html", r), t.clipboardData.setData("text/html", i), t.clipboardData.setData("text/plain", o);
}, _B = (n) => he.create({
  name: "copyToClipboard",
  addProseMirrorPlugins() {
    return [
      new G({
        props: {
          handleDOMEvents: {
            copy(e, t) {
              return Z0() || Q0(n, e, t), !0;
            },
            cut(e, t) {
              return Z0() || (Q0(n, e, t), e.editable && e.dispatch(e.state.tr.deleteSelection())), !0;
            },
            // 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(e, t) {
              if (!("node" in e.state.selection) || e.state.selection.node.type.spec.group !== "blockContent")
                return;
              n.transact(
                (s) => s.setSelection(
                  new P(
                    s.doc.resolve(e.state.selection.from - 1)
                  )
                )
              ), t.preventDefault(), t.dataTransfer.clearData();
              const { clipboardHTML: r, externalHTML: i, markdown: o } = Ek(e, n);
              return t.dataTransfer.setData("blocknote/html", r), t.dataTransfer.setData("text/html", i), t.dataTransfer.setData("text/plain", o), !0;
            }
          }
        }
      })
    ];
  }
}), wB = he.create({
  name: "blockBackgroundColor",
  addGlobalAttributes() {
    return [
      {
        types: ["blockContainer", "tableCell", "tableHeader"],
        attributes: {
          backgroundColor: {
            default: Fe.backgroundColor.default,
            parseHTML: (n) => n.hasAttribute("data-background-color") ? n.getAttribute("data-background-color") : Fe.backgroundColor.default,
            renderHTML: (n) => n.backgroundColor === Fe.backgroundColor.default ? {} : {
              "data-background-color": n.backgroundColor
            }
          }
        }
      }
    ];
  }
});
class Zf {
  constructor() {
    E(this, "callbacks", {});
  }
  on(e, t) {
    return this.callbacks[e] || (this.callbacks[e] = []), this.callbacks[e].push(t), () => this.off(e, t);
  }
  emit(e, ...t) {
    const r = this.callbacks[e];
    r && r.forEach((i) => i.apply(this, t));
  }
  off(e, t) {
    const r = this.callbacks[e];
    r && (t ? this.callbacks[e] = r.filter((i) => i !== t) : delete this.callbacks[e]);
  }
  removeAllListeners() {
    this.callbacks = {};
  }
}
class Ve extends Zf {
  // eslint-disable-next-line
  constructor(...e) {
    super(), E(this, "plugins", []);
  }
  static key() {
    throw new Error("You must implement the key method in your extension");
  }
  addProsemirrorPlugin(e) {
    this.plugins.push(e);
  }
  get priority() {
  }
}
class kB extends Ve {
  constructor() {
    super(), E(this, "beforeChangeCallbacks", []), this.addProsemirrorPlugin(
      new G({
        filterTransaction: (e) => {
          let t;
          return this.beforeChangeCallbacks.reduce((r, i) => r === !1 ? r : i({
            getChanges() {
              return t || (t = Y1(e), t);
            },
            tr: e
          }) !== !1, !0);
        }
      })
    );
  }
  static key() {
    return "blockChange";
  }
  subscribe(e) {
    return this.beforeChangeCallbacks.push(e), () => {
      this.beforeChangeCallbacks = this.beforeChangeCallbacks.filter(
        (t) => t !== e
      );
    };
  }
}
const oa = class xk extends Ve {
  constructor(e) {
    super(), E(this, "provider"), E(this, "recentlyUpdatedCursors"), E(this, "renderCursor", (t, r) => {
      let i = this.recentlyUpdatedCursors.get(r);
      if (!i) {
        const o = (this.collaboration.renderCursor ?? xk.defaultCursorRender)(t);
        this.collaboration.showCursorLabels !== "always" && (o.addEventListener("mouseenter", () => {
          const s = this.recentlyUpdatedCursors.get(r);
          s.element.setAttribute("data-active", ""), s.hideTimeout && (clearTimeout(s.hideTimeout), this.recentlyUpdatedCursors.set(r, {
            element: s.element,
            hideTimeout: void 0
          }));
        }), o.addEventListener("mouseleave", () => {
          const s = this.recentlyUpdatedCursors.get(r);
          this.recentlyUpdatedCursors.set(r, {
            element: s.element,
            hideTimeout: setTimeout(() => {
              s.element.removeAttribute("data-active");
            }, 2e3)
          });
        })), i = {
          element: o,
          hideTimeout: void 0
        }, this.recentlyUpdatedCursors.set(r, i);
      }
      return i.element;
    }), E(this, "updateUser", (t) => {
      this.provider.awareness.setLocalStateField("user", t);
    }), this.collaboration = e, this.provider = e.provider, this.recentlyUpdatedCursors = /* @__PURE__ */ new Map(), this.provider.awareness.setLocalStateField("user", e.user), e.showCursorLabels !== "always" && this.provider.awareness.on(
      "change",
      ({
        updated: t
      }) => {
        for (const r of t) {
          const i = this.recentlyUpdatedCursors.get(r);
          i && (i.element.setAttribute("data-active", ""), i.hideTimeout && clearTimeout(i.hideTimeout), this.recentlyUpdatedCursors.set(r, {
            element: i.element,
            hideTimeout: setTimeout(() => {
              i.element.removeAttribute("data-active");
            }, 2e3)
          }));
        }
      }
    ), this.addProsemirrorPlugin(
      kI(this.provider.awareness, {
        selectionBuilder: R1,
        cursorBuilder: this.renderCursor
      })
    );
  }
  static key() {
    return "yCursorPlugin";
  }
  get priority() {
    return 999;
  }
  /**
   * Determine whether the foreground color should be white or black based on a provided background color
   * Inspired by: https://stackoverflow.com/a/3943023
   *
   */
  static isDarkColor(e) {
    const t = e.charAt(0) === "#" ? e.substring(1, 7) : e, r = parseInt(t.substring(0, 2), 16), i = parseInt(t.substring(2, 4), 16), o = parseInt(t.substring(4, 6), 16), s = [r / 255, i / 255, o / 255].map((l) => l <= 0.03928 ? l / 12.92 : Math.pow((l + 0.055) / 1.055, 2.4));
    return 0.2126 * s[0] + 0.7152 * s[1] + 0.0722 * s[2] <= 0.179;
  }
};
E(oa, "defaultCursorRender", (n) => {
  const e = document.createElement("span");
  e.classList.add("bn-collaboration-cursor__base");
  const t = document.createElement("span");
  t.setAttribute("contentedEditable", "false"), t.classList.add("bn-collaboration-cursor__caret"), t.setAttribute(
    "style",
    `background-color: ${n.color}; color: ${oa.isDarkColor(n.color) ? "white" : "black"}`
  );
  const r = document.createElement("span");
  return r.classList.add("bn-collaboration-cursor__label"), r.setAttribute(
    "style",
    `background-color: ${n.color}; color: ${oa.isDarkColor(n.color) ? "white" : "black"}`
  ), r.insertBefore(document.createTextNode(n.name), null), t.insertBefore(r, null), e.insertBefore(document.createTextNode("⁠"), null), e.insertBefore(t, null), e.insertBefore(document.createTextNode("⁠"), null), e;
});
let Dk = oa;
class gh extends Ve {
  static key() {
    return "ySyncPlugin";
  }
  constructor(e) {
    super(), this.addProsemirrorPlugin(oI(e));
  }
  get priority() {
    return 1001;
  }
}
class bh extends Ve {
  static key() {
    return "yUndoPlugin";
  }
  constructor({ editor: e }) {
    super(), this.addProsemirrorPlugin(AI({ trackedOrigins: [e] }));
  }
  get priority() {
    return 1e3;
  }
}
const Ak = Je.create({
  name: "comment",
  excludes: "",
  inclusive: !1,
  keepOnSplit: !0,
  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: (n) => !!n.getAttribute("data-orphan"),
        renderHTML: (n) => n.orphan ? {
          "data-orphan": "true"
        } : {},
        default: !1
      },
      threadId: {
        parseHTML: (n) => n.getAttribute("data-bn-thread-id"),
        renderHTML: (n) => ({
          "data-bn-thread-id": n.threadId
        }),
        default: ""
      }
    };
  },
  renderHTML({ HTMLAttributes: n }) {
    return [
      "span",
      Tt(n, {
        class: "bn-thread-mark"
      })
    ];
  },
  parseHTML() {
    return [{ tag: "span.bn-thread-mark" }];
  },
  extendMarkSchema(n) {
    return n.name === "comment" ? {
      blocknoteIgnore: !0
    } : {};
  }
});
class vB extends Zf {
  constructor(e) {
    super(), E(this, "userCache", /* @__PURE__ */ new Map()), E(this, "loadingUsers", /* @__PURE__ */ new Set()), this.resolveUsers = e;
  }
  /**
   * Load information about users based on an array of user ids.
   */
  async loadUsers(e) {
    const t = e.filter(
      (r) => !this.userCache.has(r) && !this.loadingUsers.has(r)
    );
    if (t.length !== 0) {
      for (const r of t)
        this.loadingUsers.add(r);
      try {
        const r = await this.resolveUsers(t);
        for (const i of r)
          this.userCache.set(i.id, i);
        this.emit("update", this.userCache);
      } finally {
        for (const r of t)
          this.loadingUsers.delete(r);
      }
    }
  }
  /**
   * Retrieve information about a user based on their id, if cached.
   *
   * The user will have to be loaded via `loadUsers` first
   */
  getUser(e) {
    return this.userCache.get(e);
  }
  /**
   * 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(e) {
    return this.on("update", e);
  }
}
const Rl = new te("blocknote-comments"), CB = "SET_SELECTED_THREAD_ID";
function SB(n, e) {
  const t = /* @__PURE__ */ new Map();
  return n.descendants((r, i) => {
    r.marks.forEach((o) => {
      if (o.type.name === e) {
        const s = o.attrs.threadId;
        if (!s)
          return;
        const l = i, a = l + r.nodeSize, c = t.get(s) ?? {
          from: 1 / 0,
          to: 0
        };
        t.set(s, {
          from: Math.min(l, c.from),
          to: Math.max(a, c.to)
        });
      }
    });
  }), t;
}
class EB extends Ve {
  constructor(e, t, r) {
    if (super(), E(this, "userStore"), E(this, "pendingComment", !1), E(this, "selectedThreadId"), E(this, "threadPositions", /* @__PURE__ */ new Map()), E(this, "updateMarksFromThreads", (o) => {
      this.editor.transact((s) => {
        s.doc.descendants((l, a) => {
          l.marks.forEach((c) => {
            if (c.type.name === this.markType) {
              const d = c.type, u = c.attrs.threadId, h = o.get(u), f = !!(!h || h.resolved || h.deletedAt);
              if (f !== c.attrs.orphan) {
                const p = Math.max(a, 0), m = Math.min(
                  a + l.nodeSize,
                  s.doc.content.size - 1,
                  s.doc.content.size - 1
                );
                s.removeMark(p, m, c), s.addMark(
                  p,
                  m,
                  d.create({
                    ...c.attrs,
                    orphan: f
                  })
                ), f && this.selectedThreadId === u && (this.selectedThreadId = void 0, this.emitStateUpdate());
              }
            }
          });
        });
      });
    }), this.editor = e, this.threadStore = t, this.markType = r, !e.resolveUsers)
      throw new Error("resolveUsers is required for comments");
    this.userStore = new vB(e.resolveUsers), this.threadStore.subscribe(this.updateMarksFromThreads), e.onCreate(() => {
      this.updateMarksFromThreads(this.threadStore.getThreads()), e.onSelectionChange(() => {
        this.pendingComment && (this.pendingComment = !1, this.emitStateUpdate());
      });
    });
    const i = this;
    this.addProsemirrorPlugin(
      new G({
        key: Rl,
        state: {
          init() {
            return {
              decorations: Q.empty
            };
          },
          apply(o, s) {
            const l = o.getMeta(Rl);
            if (!o.docChanged && !l)
              return s;
            const a = o.docChanged ? SB(o.doc, i.markType) : i.threadPositions;
            (a.size > 0 || i.threadPositions.size > 0) && (i.threadPositions = a, i.emitStateUpdate());
            const c = [];
            if (i.selectedThreadId) {
              const d = a.get(
                i.selectedThreadId
              );
              d && c.push(
                se.inline(
                  d.from,
                  d.to,
                  {
                    class: "bn-thread-mark-selected"
                  }
                )
              );
            }
            return {
              decorations: Q.create(o.doc, c)
            };
          }
        },
        props: {
          decorations(o) {
            var s;
            return ((s = Rl.getState(o)) == null ? void 0 : s.decorations) ?? Q.empty;
          },
          /**
           * Handle click on a thread mark and mark it as selected
           */
          handleClick: (o, s, l) => {
            if (l.button !== 0)
              return;
            const a = o.state.doc.nodeAt(s);
            if (!a) {
              i.selectThread(void 0);
              return;
            }
            const c = a.marks.find(
              (u) => u.type.name === r && u.attrs.orphan !== !0
            ), d = c == null ? void 0 : c.attrs.threadId;
            i.selectThread(d, !1);
          }
        }
      })
    );
  }
  static key() {
    return "comments";
  }
  emitStateUpdate() {
    this.emit("update", {
      selectedThreadId: this.selectedThreadId,
      pendingComment: this.pendingComment,
      threadPositions: this.threadPositions
    });
  }
  /**
   * Subscribe to state updates
   */
  onUpdate(e) {
    return this.on("update", e);
  }
  /**
   * Set the selected thread
   */
  selectThread(e, t = !0) {
    var r, i;
    if (this.selectedThreadId !== e && (this.selectedThreadId = e, this.emitStateUpdate(), this.editor.transact(
      (o) => o.setMeta(Rl, {
        name: CB
      })
    ), e && t)) {
      const o = this.threadPositions.get(e);
      if (!o)
        return;
      (i = (r = this.editor.prosemirrorView) == null ? void 0 : r.domAtPos(o.from).node) == null || i.scrollIntoView({
        behavior: "smooth",
        block: "center"
      });
    }
  }
  /**
   * Start a pending comment (e.g.: when clicking the "Add comment" button)
   */
  startPendingComment() {
    this.pendingComment = !0, this.emitStateUpdate();
  }
  /**
   * Stop a pending comment (e.g.: user closes the comment composer)
   */
  stopPendingComment() {
    this.pendingComment = !1, this.emitStateUpdate();
  }
  /**
   * Create a thread at the current selection
   */
  async createThread(e) {
    const t = await this.threadStore.createThread(e);
    if (this.threadStore.addThreadToDocument) {
      const r = this.editor.prosemirrorView, i = r.state.selection, o = ne.getState(r.state), s = {
        prosemirror: {
          head: i.head,
          anchor: i.anchor
        },
        yjs: o ? ac(o.binding, r.state) : void 0
        // if we're not using yjs
      };
      await this.threadStore.addThreadToDocument({
        threadId: t.id,
        selection: s
      });
    } else
      this.editor._tiptapEditor.commands.setMark(this.markType, {
        orphan: !1,
        threadId: t.id
      });
  }
}
class xB {
  constructor(e, t, r, i) {
    E(this, "state"), E(this, "emitUpdate"), E(this, "mouseDownHandler", () => {
      var o;
      (o = this.state) != null && o.show && (this.state.show = !1, this.emitUpdate());
    }), E(this, "dragstartHandler", () => {
      var o;
      (o = this.state) != null && o.show && (this.state.show = !1, this.emitUpdate());
    }), E(this, "scrollHandler", () => {
      var o;
      if ((o = this.state) != null && o.show) {
        const s = this.pmView.root.querySelector(
          `[data-node-type="blockContainer"][data-id="${this.state.block.id}"]`
        );
        if (!s)
          return;
        this.state.referencePos = s.getBoundingClientRect(), this.emitUpdate();
      }
    }), E(this, "closeMenu", () => {
      var o;
      (o = this.state) != null && o.show && (this.state.show = !1, this.emitUpdate());
    }), this.editor = e, this.pluginKey = t, this.pmView = r, this.emitUpdate = () => {
      if (!this.state)
        throw new Error("Attempting to update uninitialized file panel");
      i(this.state);
    }, r.dom.addEventListener("mousedown", this.mouseDownHandler), r.dom.addEventListener("dragstart", this.dragstartHandler), r.root.addEventListener("scroll", this.scrollHandler, !0);
  }
  update(e, t) {
    var r, i;
    const o = this.pluginKey.getState(e.state), s = this.pluginKey.getState(t);
    if (!((r = this.state) != null && r.show) && o != null && o.block && this.editor.isEditable) {
      const c = this.pmView.root.querySelector(
        `[data-node-type="blockContainer"][data-id="${o.block.id}"]`
      );
      if (!c)
        return;
      this.state = {
        show: !0,
        referencePos: c.getBoundingClientRect(),
        block: o.block
      }, this.emitUpdate();
      return;
    }
    const l = (o == null ? void 0 : o.block) && !(s != null && s.block), a = !(o != null && o.block) && (s == null ? void 0 : s.block);
    l && this.state && !this.state.show && (this.state.show = !0, this.emitUpdate()), a && (i = this.state) != null && i.show && (this.state.show = !1, this.emitUpdate());
  }
  destroy() {
    this.pmView.dom.removeEventListener("mousedown", this.mouseDownHandler), this.pmView.dom.removeEventListener("dragstart", this.dragstartHandler), this.pmView.root.removeEventListener("scroll", this.scrollHandler, !0);
  }
}
const tu = new te(
  "FilePanelPlugin"
);
class DB extends Ve {
  constructor(e) {
    super(), E(this, "view"), E(this, "closeMenu", () => {
      var t;
      return (t = this.view) == null ? void 0 : t.closeMenu();
    }), this.addProsemirrorPlugin(
      new G({
        key: tu,
        view: (t) => (this.view = new xB(
          e,
          tu,
          t,
          (r) => {
            this.emit("update", r);
          }
        ), this.view),
        props: {
          handleKeyDown: (t, r) => {
            var i;
            return r.key === "Escape" && this.shown ? ((i = this.view) == null || i.closeMenu(), !0) : !1;
          }
        },
        state: {
          init: () => ({
            block: void 0
          }),
          apply: (t, r) => t.getMeta(tu) || (!t.getMeta(ne) && (t.selectionSet || t.docChanged) ? { block: void 0 } : r)
        }
      })
    );
  }
  static key() {
    return "filePanel";
  }
  get shown() {
    var e, t;
    return ((t = (e = this.view) == null ? void 0 : e.state) == null ? void 0 : t.show) || !1;
  }
  onUpdate(e) {
    return this.on("update", e);
  }
}
class AB {
  constructor(e, t, r) {
    E(this, "state"), E(this, "emitUpdate"), E(this, "preventHide", !1), E(this, "preventShow", !1), E(this, "shouldShow", ({ view: i, state: o, from: s, to: l }) => {
      const { doc: a, selection: c } = o, { empty: d } = c, u = !a.textBetween(s, l).length && vc(o.selection);
      if (c.$from.parent.type.spec.code || $u(c) && c.node.type.spec.code || d || u)
        return !1;
      const h = document.activeElement;
      return !(!this.isElementWithinEditorWrapper(h) && i.editable);
    }), E(this, "blurHandler", (i) => {
      var o;
      if (this.preventHide) {
        this.preventHide = !1;
        return;
      }
      const s = this.pmView.dom.parentElement;
      i && i.relatedTarget && // Element is inside the editor.
      (s === i.relatedTarget || s.contains(i.relatedTarget) || i.relatedTarget.matches(
        ".bn-ui-container, .bn-ui-container *"
      )) || (o = this.state) != null && o.show && (this.state.show = !1, this.emitUpdate());
    }), E(this, "isElementWithinEditorWrapper", (i) => {
      if (!i)
        return !1;
      const o = this.pmView.dom.parentElement;
      return o ? o.contains(i) : !1;
    }), E(this, "viewMousedownHandler", (i) => {
      (!this.isElementWithinEditorWrapper(i.target) || i.button === 0) && (this.preventShow = !0);
    }), E(this, "mouseupHandler", () => {
      this.preventShow && (this.preventShow = !1, setTimeout(() => this.update(this.pmView)));
    }), E(this, "dragHandler", () => {
      var i;
      (i = this.state) != null && i.show && (this.state.show = !1, this.emitUpdate());
    }), E(this, "scrollHandler", () => {
      var i;
      (i = this.state) != null && i.show && (this.state.referencePos = this.getSelectionBoundingBox(), this.emitUpdate());
    }), E(this, "closeMenu", () => {
      var i;
      (i = this.state) != null && i.show && (this.state.show = !1, this.emitUpdate());
    }), this.editor = e, this.pmView = t, this.emitUpdate = () => {
      if (!this.state)
        throw new Error(
          "Attempting to update uninitialized formatting toolbar"
        );
      r(this.state);
    }, t.dom.addEventListener("mousedown", this.viewMousedownHandler), t.root.addEventListener("mouseup", this.mouseupHandler), t.dom.addEventListener("dragstart", this.dragHandler), t.dom.addEventListener("dragover", this.dragHandler), t.dom.addEventListener("blur", this.blurHandler), t.root.addEventListener("scroll", this.scrollHandler, !0);
  }
  update(e, t) {
    var r, i, o;
    const { state: s, composing: l } = e, { doc: a, selection: c } = s, d = t && t.doc.eq(a) && t.selection.eq(c);
    if (l || d)
      return;
    const { ranges: u } = c, h = Math.min(...u.map((g) => g.$from.pos)), f = Math.max(...u.map((g) => g.$to.pos)), p = this.shouldShow({
      view: e,
      state: s,
      from: h,
      to: f
    }), m = typeof Range.prototype.getClientRects > "u";
    if (!this.preventShow && (p || this.preventHide) && !m) {
      const g = {
        show: !0,
        referencePos: this.getSelectionBoundingBox()
      };
      (g.show !== ((r = this.state) == null ? void 0 : r.show) || g.referencePos.toJSON() !== ((i = this.state) == null ? void 0 : i.referencePos.toJSON())) && (this.state = g, this.emitUpdate());
      return;
    }
    if ((o = this.state) != null && o.show && !this.preventHide && (!p || this.preventShow || !this.editor.isEditable)) {
      this.state.show = !1, this.emitUpdate();
      return;
    }
  }
  destroy() {
    this.pmView.dom.removeEventListener("mousedown", this.viewMousedownHandler), this.pmView.root.removeEventListener("mouseup", this.mouseupHandler), this.pmView.dom.removeEventListener("dragstart", this.dragHandler), this.pmView.dom.removeEventListener("dragover", this.dragHandler), this.pmView.dom.removeEventListener("blur", this.blurHandler), this.pmView.root.removeEventListener("scroll", this.scrollHandler, !0);
  }
  getSelectionBoundingBox() {
    const { state: e } = this.pmView, { selection: t } = e, { ranges: r } = t, i = Math.min(...r.map((s) => s.$from.pos)), o = Math.max(...r.map((s) => s.$to.pos));
    if ($u(t)) {
      const s = this.pmView.nodeDOM(i);
      if (s)
        return s.getBoundingClientRect();
    }
    return Sa(this.pmView, i, o);
  }
}
const TB = new te(
  "FormattingToolbarPlugin"
);
class MB extends Ve {
  constructor(e) {
    super(), E(this, "view"), E(this, "closeMenu", () => this.view.closeMenu()), this.addProsemirrorPlugin(
      new G({
        key: TB,
        view: (t) => (this.view = new AB(e, t, (r) => {
          this.emit("update", r);
        }), this.view),
        props: {
          handleKeyDown: (t, r) => r.key === "Escape" && this.shown ? (this.view.closeMenu(), !0) : !1
        }
      })
    );
  }
  static key() {
    return "formattingToolbar";
  }
  get shown() {
    var e, t;
    return ((t = (e = this.view) == null ? void 0 : e.state) == null ? void 0 : t.show) || !1;
  }
  onUpdate(e) {
    return this.on("update", e);
  }
}
const OB = Mt.create({
  name: "hardBreak",
  inline: !0,
  group: "inline",
  selectable: !1,
  linebreakReplacement: !0,
  priority: 10,
  parseHTML() {
    return [{ tag: "br" }];
  },
  renderHTML({ HTMLAttributes: n }) {
    return ["br", Tt(this.options.HTMLAttributes, n)];
  },
  renderText() {
    return `
`;
  }
}), eb = (n, e) => {
  const t = n.resolve(e);
  if (t.depth <= 1)
    return;
  const r = t.posAtIndex(
    t.index(t.depth - 1),
    t.depth - 1
  );
  return Js(
    n.resolve(r)
  );
}, sa = (n, e) => {
  const t = n.resolve(e), r = t.index();
  if (r === 0)
    return;
  const i = t.posAtIndex(r - 1);
  return Js(
    n.resolve(i)
  );
}, Tk = (n, e) => {
  for (; e.childContainer; ) {
    const t = e.childContainer.node, r = n.resolve(e.childContainer.beforePos + 1).posAtIndex(t.childCount - 1);
    e = Js(n.resolve(r));
  }
  return e;
}, FB = (n, e) => n.isBlockContainer && n.blockContent.node.type.spec.content === "inline*" && n.blockContent.node.childCount > 0 && e.isBlockContainer && e.blockContent.node.type.spec.content === "inline*", NB = (n, e, t, r) => {
  if (!r.isBlockContainer)
    throw new Error(
      `Attempted to merge block at position ${r.bnBlock.beforePos} into previous block at position ${t.bnBlock.beforePos}, but next block is not a block container`
    );
  if (r.childContainer) {
    const i = n.doc.resolve(
      r.childContainer.beforePos + 1
    ), o = n.doc.resolve(
      r.childContainer.afterPos - 1
    ), s = i.blockRange(o);
    if (e) {
      const l = n.doc.resolve(r.bnBlock.beforePos);
      n.tr.lift(s, l.depth);
    }
  }
  if (e) {
    if (!t.isBlockContainer)
      throw new Error(
        `Attempted to merge block at position ${r.bnBlock.beforePos} into previous block at position ${t.bnBlock.beforePos}, but previous block is not a block container`
      );
    e(
      n.tr.delete(
        t.blockContent.afterPos - 1,
        r.blockContent.beforePos + 1
      )
    );
  }
  return !0;
}, tb = (n) => ({
  state: e,
  dispatch: t
}) => {
  const r = e.doc.resolve(n), i = Js(r), o = sa(
    e.doc,
    i.bnBlock.beforePos
  );
  if (!o)
    return !1;
  const s = Tk(
    e.doc,
    o
  );
  return FB(s, i) ? NB(e, t, s, i) : !1;
}, $B = he.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 n = () => this.editor.commands.first(({ chain: r, commands: i }) => [
      // Deletes the selection if it's not empty.
      () => i.deleteSelection(),
      // Undoes an input rule if one was triggered in the last editor state change.
      () => i.undoInputRule(),
      // Reverts block content type to a paragraph if the selection is at the start of the block.
      () => i.command(({ state: o }) => {
        const s = ge(o);
        if (!s.isBlockContainer)
          return !1;
        const l = o.selection.from === s.blockContent.beforePos + 1, a = s.blockContent.node.type.name === "paragraph";
        return l && !a ? i.command(
          rt(s.bnBlock.beforePos, {
            type: "paragraph",
            props: {}
          })
        ) : !1;
      }),
      // Removes a level of nesting if the block is indented if the selection is at the start of the block.
      () => i.command(({ state: o }) => {
        const s = ge(o);
        if (!s.isBlockContainer)
          return !1;
        const { blockContent: l } = s;
        return o.selection.from === l.beforePos + 1 ? i.liftListItem("blockContainer") : !1;
      }),
      // 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.
      () => i.command(({ state: o }) => {
        const s = ge(o);
        if (!s.isBlockContainer)
          return !1;
        const { bnBlock: l, blockContent: a } = s, c = o.selection.from === a.beforePos + 1, d = o.selection.empty, u = l.beforePos;
        return c && d ? r().command(tb(u)).scrollIntoView().run() : !1;
      }),
      () => i.command(({ state: o, dispatch: s }) => {
        const l = ge(o);
        if (!l.isBlockContainer || o.selection.from !== l.blockContent.beforePos + 1 || sa(
          o.doc,
          l.bnBlock.beforePos
        ))
          return !1;
        const a = eb(
          o.doc,
          l.bnBlock.beforePos
        );
        if ((a == null ? void 0 : a.blockNoteType) !== "column")
          return !1;
        const c = a, d = eb(
          o.doc,
          c.bnBlock.beforePos
        );
        if ((d == null ? void 0 : d.blockNoteType) !== "columnList")
          throw new Error("parent of column is not a column list");
        const u = c.childContainer.node.childCount === 1, h = u && d.childContainer.node.childCount === 2, f = d.childContainer.node.firstChild === c.bnBlock.node;
        if (s) {
          const p = o.doc.slice(
            l.bnBlock.beforePos,
            l.bnBlock.afterPos,
            !1
          );
          if (h)
            if (f) {
              o.tr.step(
                new Ae(
                  // replace entire column list
                  d.bnBlock.beforePos,
                  d.bnBlock.afterPos,
                  // select content of remaining column:
                  c.bnBlock.afterPos + 1,
                  d.bnBlock.afterPos - 2,
                  p,
                  p.size,
                  // append existing content to blockToMove
                  !1
                )
              );
              const m = o.tr.doc.resolve(c.bnBlock.beforePos);
              o.tr.setSelection(L.between(m, m));
            } else {
              o.tr.step(
                new Ae(
                  // replace entire column list
                  d.bnBlock.beforePos,
                  d.bnBlock.afterPos,
                  // select content of existing column:
                  d.bnBlock.beforePos + 2,
                  c.bnBlock.beforePos - 1,
                  p,
                  0,
                  // prepend existing content to blockToMove
                  !1
                )
              );
              const m = o.tr.doc.resolve(
                o.tr.mapping.map(c.bnBlock.beforePos - 1)
              );
              o.tr.setSelection(L.between(m, m));
            }
          else if (u)
            if (f) {
              o.tr.delete(
                c.bnBlock.beforePos,
                c.bnBlock.afterPos
              ), o.tr.insert(
                d.bnBlock.beforePos,
                p.content
              );
              const m = o.tr.doc.resolve(
                d.bnBlock.beforePos
              );
              o.tr.setSelection(L.between(m, m));
            } else
              o.tr.delete(
                c.bnBlock.beforePos - 1,
                c.bnBlock.beforePos + 1
              );
          else {
            o.tr.delete(
              l.bnBlock.beforePos,
              l.bnBlock.afterPos
            ), f ? o.tr.insert(
              d.bnBlock.beforePos - 1,
              p.content
            ) : o.tr.insert(
              c.bnBlock.beforePos - 1,
              p.content
            );
            const m = o.tr.doc.resolve(c.bnBlock.beforePos - 1);
            o.tr.setSelection(L.between(m, m));
          }
        }
        return !0;
      }),
      // Deletes the current block if it's an empty block with inline content,
      // and moves the selection to the previous block.
      () => i.command(({ state: o }) => {
        const s = ge(o);
        if (!s.isBlockContainer)
          return !1;
        if (s.blockContent.node.childCount === 0 && s.blockContent.node.type.spec.content === "inline*") {
          const l = sa(
            o.doc,
            s.bnBlock.beforePos
          );
          if (!l || !l.isBlockContainer)
            return !1;
          let a = r();
          if (l.blockContent.node.type.spec.content === "tableRow+") {
            const c = s.bnBlock.beforePos - 1 - 1 - 1 - 1 - 1;
            a = a.setTextSelection(
              c
            );
          } else if (l.blockContent.node.type.spec.content === "") {
            const c = l.blockContent.afterPos - l.blockContent.node.nodeSize;
            a = a.setNodeSelection(
              c
            );
          } else {
            const c = l.blockContent.afterPos - l.blockContent.node.nodeSize;
            a = a.setTextSelection(c);
          }
          return a.deleteRange({
            from: s.bnBlock.beforePos,
            to: s.bnBlock.afterPos
          }).scrollIntoView().run();
        }
        return !1;
      }),
      // 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.
      () => i.command(({ state: o }) => {
        const s = ge(o);
        if (!s.isBlockContainer)
          throw new Error("todo");
        const l = o.selection.from === s.blockContent.beforePos + 1, a = o.selection.empty, c = sa(
          o.doc,
          s.bnBlock.beforePos
        );
        if (c && l && a) {
          const d = Tk(
            o.doc,
            c
          );
          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 r().cut(
              {
                from: s.bnBlock.beforePos,
                to: s.bnBlock.afterPos
              },
              d.bnBlock.afterPos
            ).deleteRange({
              from: d.bnBlock.beforePos,
              to: d.bnBlock.afterPos
            }).run();
        }
        return !1;
      })
    ]), e = () => this.editor.commands.first(({ commands: r }) => [
      // Deletes the selection if it's not empty.
      () => r.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.
      () => r.command(({ state: i }) => {
        const o = ge(i);
        if (!o.isBlockContainer)
          return !1;
        const {
          bnBlock: s,
          blockContent: l,
          childContainer: a
        } = o, { depth: c } = i.doc.resolve(s.beforePos), d = s.afterPos === i.doc.nodeSize - 3, u = i.selection.from === l.afterPos - 1, h = i.selection.empty;
        if (!d && u && h && a === void 0) {
          let f = c, p = s.afterPos + 1, m = i.doc.resolve(p).depth;
          for (; m < f; )
            f = m, p += 2, m = i.doc.resolve(p).depth;
          return r.command(tb(p - 1));
        }
        return !1;
      })
    ]), t = (r = !1) => this.editor.commands.first(({ commands: i, tr: o }) => [
      // Removes a level of nesting if the block is empty & indented, while the selection is also empty & at the start
      // of the block.
      () => i.command(({ state: s }) => {
        const l = ge(s);
        if (!l.isBlockContainer)
          return !1;
        const { bnBlock: a, blockContent: c } = l, { depth: d } = s.doc.resolve(a.beforePos), u = s.selection.$anchor.parentOffset === 0, h = s.selection.anchor === s.selection.head, f = c.node.childCount === 0, p = d > 1;
        return u && h && f && p ? i.liftListItem("blockContainer") : !1;
      }),
      // Creates a hard break if block is configured to do so.
      () => i.command(({ state: s }) => {
        const l = ge(s), a = this.options.editor.schema.blockSchema[l.blockNoteType].hardBreakShortcut ?? "shift+enter";
        if (a === "none")
          return !1;
        if (
          // If shortcut is not configured, or is configured as "shift+enter",
          // create a hard break for shift+enter, but not for enter.
          a === "shift+enter" && r || // If shortcut is configured as "enter", create a hard break for
          // both enter and shift+enter.
          a === "enter"
        ) {
          const c = o.storedMarks || o.selection.$head.marks().filter(
            (d) => this.editor.extensionManager.splittableMarks.includes(
              d.type.name
            )
          );
          return o.insert(
            o.selection.head,
            o.doc.type.schema.nodes.hardBreak.create()
          ).ensureMarks(c), !0;
        }
        return !1;
      }),
      // 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.
      () => i.command(({ state: s, dispatch: l }) => {
        const a = ge(s);
        if (!a.isBlockContainer)
          return !1;
        const { bnBlock: c, blockContent: d } = a, u = s.selection.$anchor.parentOffset === 0, h = s.selection.anchor === s.selection.head, f = d.node.childCount === 0;
        if (u && h && f) {
          const p = c.afterPos, m = p + 2;
          if (l) {
            const g = s.schema.nodes.blockContainer.createAndFill();
            s.tr.insert(p, g).scrollIntoView(), s.tr.setSelection(
              new L(s.doc.resolve(m))
            );
          }
          return !0;
        }
        return !1;
      }),
      // 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.
      () => i.command(({ state: s, chain: l }) => {
        const a = ge(s);
        if (!a.isBlockContainer)
          return !1;
        const { blockContent: c } = a, d = s.selection.$anchor.parentOffset === 0;
        return c.node.childCount === 0 ? !1 : (l().deleteSelection().command(
          sk(
            s.selection.from,
            d,
            d
          )
        ).run(), !0);
      })
    ]);
    return {
      Backspace: n,
      Delete: e,
      Enter: () => t(),
      "Shift-Enter": () => t(!0),
      // 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 r, i, o;
        return this.options.tabBehavior !== "prefer-indent" && ((r = this.options.editor.formattingToolbar) != null && r.shown || (i = this.options.editor.linkToolbar) != null && i.shown || (o = this.options.editor.filePanel) != null && o.shown) ? !1 : yk(this.options.editor);
      },
      "Shift-Tab": () => {
        var r, i, o;
        return this.options.tabBehavior !== "prefer-indent" && ((r = this.options.editor.formattingToolbar) != null && r.shown || (i = this.options.editor.linkToolbar) != null && i.shown || (o = this.options.editor.filePanel) != null && o.shown) ? !1 : (this.editor.commands.liftListItem("blockContainer"), !0);
      },
      "Shift-Mod-ArrowUp": () => (this.options.editor.moveBlocksUp(), !0),
      "Shift-Mod-ArrowDown": () => (this.options.editor.moveBlocksDown(), !0),
      "Mod-z": () => this.options.editor.undo(),
      "Mod-y": () => this.options.editor.redo(),
      "Shift-Mod-z": () => this.options.editor.redo()
    };
  }
});
class IB {
  constructor(e, t, r) {
    E(this, "state"), E(this, "emitUpdate"), E(this, "menuUpdateTimer"), E(this, "startMenuUpdateTimer"), E(this, "stopMenuUpdateTimer"), E(this, "mouseHoveredLinkMark"), E(this, "mouseHoveredLinkMarkRange"), E(this, "keyboardHoveredLinkMark"), E(this, "keyboardHoveredLinkMarkRange"), E(this, "linkMark"), E(this, "linkMarkRange"), E(this, "mouseOverHandler", (i) => {
      if (this.mouseHoveredLinkMark = void 0, this.mouseHoveredLinkMarkRange = void 0, this.stopMenuUpdateTimer(), i.target instanceof HTMLAnchorElement && i.target.nodeName === "A") {
        const o = i.target, s = this.pmView.posAtDOM(o, 0) + 1, l = this.pmView.state.doc.resolve(s), a = l.marks();
        for (const c of a)
          if (c.type.name === this.pmView.state.schema.mark("link").type.name) {
            this.mouseHoveredLinkMark = c, this.mouseHoveredLinkMarkRange = bs(l, c.type, c.attrs) || void 0;
            break;
          }
      }
      return this.startMenuUpdateTimer(), !1;
    }), E(this, "clickHandler", (i) => {
      var o;
      const s = this.pmView.dom.parentElement;
      this.linkMark && // An element is clicked.
      i && i.target && // The clicked element is not the editor.
      !(s === i.target || s.contains(i.target)) && (o = this.state) != null && o.show && (this.state.show = !1, this.emitUpdate());
    }), E(this, "scrollHandler", () => {
      var i;
      this.linkMark !== void 0 && (i = this.state) != null && i.show && (this.state.referencePos = Sa(
        this.pmView,
        this.linkMarkRange.from,
        this.linkMarkRange.to
      ), this.emitUpdate());
    }), E(this, "closeMenu", () => {
      var i;
      (i = this.state) != null && i.show && (this.state.show = !1, this.emitUpdate());
    }), this.editor = e, this.pmView = t, this.emitUpdate = () => {
      if (!this.state)
        throw new Error("Attempting to update uninitialized link toolbar");
      r(this.state);
    }, this.startMenuUpdateTimer = () => {
      this.menuUpdateTimer = setTimeout(() => {
        this.update(this.pmView, void 0, !0);
      }, 250);
    }, this.stopMenuUpdateTimer = () => (this.menuUpdateTimer && (clearTimeout(this.menuUpdateTimer), this.menuUpdateTimer = void 0), !1), this.pmView.dom.addEventListener("mouseover", this.mouseOverHandler), this.pmView.root.addEventListener(
      "click",
      this.clickHandler,
      !0
    ), this.pmView.root.addEventListener("scroll", this.scrollHandler, !0);
  }
  editLink(e, t) {
    var r;
    this.editor.transact((i) => {
      const o = Ue(i);
      i.insertText(t, this.linkMarkRange.from, this.linkMarkRange.to), i.addMark(
        this.linkMarkRange.from,
        this.linkMarkRange.from + t.length,
        o.mark("link", { href: e })
      );
    }), this.pmView.focus(), (r = this.state) != null && r.show && (this.state.show = !1, this.emitUpdate());
  }
  deleteLink() {
    var e;
    this.editor.transact(
      (t) => t.removeMark(
        this.linkMarkRange.from,
        this.linkMarkRange.to,
        this.linkMark.type
      ).setMeta("preventAutolink", !0)
    ), this.pmView.focus(), (e = this.state) != null && e.show && (this.state.show = !1, this.emitUpdate());
  }
  update(e, t, r = !1) {
    var i;
    const { state: o } = e;
    if (t && t.selection.from === o.selection.from && t.selection.to === o.selection.to || !this.pmView.hasFocus())
      return;
    const s = this.linkMark;
    if (this.linkMark = void 0, this.linkMarkRange = void 0, this.keyboardHoveredLinkMark = void 0, this.keyboardHoveredLinkMarkRange = void 0, this.pmView.state.selection.empty) {
      const l = this.pmView.state.selection.$from.marks();
      for (const a of l)
        if (a.type.name === this.pmView.state.schema.mark("link").type.name) {
          this.keyboardHoveredLinkMark = a, this.keyboardHoveredLinkMarkRange = bs(
            this.pmView.state.selection.$from,
            a.type,
            a.attrs
          ) || void 0;
          break;
        }
    }
    if (this.mouseHoveredLinkMark && r && (this.linkMark = this.mouseHoveredLinkMark, this.linkMarkRange = this.mouseHoveredLinkMarkRange), this.keyboardHoveredLinkMark && (this.linkMark = this.keyboardHoveredLinkMark, this.linkMarkRange = this.keyboardHoveredLinkMarkRange), this.linkMark && this.editor.isEditable) {
      this.state = {
        show: !0,
        referencePos: Sa(
          this.pmView,
          this.linkMarkRange.from,
          this.linkMarkRange.to
        ),
        url: this.linkMark.attrs.href,
        text: this.pmView.state.doc.textBetween(
          this.linkMarkRange.from,
          this.linkMarkRange.to
        )
      }, this.emitUpdate();
      return;
    }
    if ((i = this.state) != null && i.show && s && (!this.linkMark || !this.editor.isEditable)) {
      this.state.show = !1, this.emitUpdate();
      return;
    }
  }
  destroy() {
    this.pmView.dom.removeEventListener("mouseover", this.mouseOverHandler), this.pmView.root.removeEventListener("scroll", this.scrollHandler, !0), this.pmView.root.removeEventListener(
      "click",
      this.clickHandler,
      !0
    );
  }
}
const LB = new te("LinkToolbarPlugin");
class RB extends Ve {
  constructor(e) {
    super(), E(this, "view"), E(this, "editLink", (t, r) => {
      this.view.editLink(t, r);
    }), E(this, "deleteLink", () => {
      this.view.deleteLink();
    }), E(this, "startHideTimer", () => {
      this.view.startMenuUpdateTimer();
    }), E(this, "stopHideTimer", () => {
      this.view.stopMenuUpdateTimer();
    }), E(this, "closeMenu", () => this.view.closeMenu()), this.addProsemirrorPlugin(
      new G({
        key: LB,
        view: (t) => (this.view = new IB(e, t, (r) => {
          this.emit("update", r);
        }), this.view),
        props: {
          handleKeyDown: (t, r) => r.key === "Escape" && this.shown ? (this.view.closeMenu(), !0) : !1
        }
      })
    );
  }
  static key() {
    return "linkToolbar";
  }
  onUpdate(e) {
    return this.on("update", e);
  }
  get shown() {
    var e, t;
    return ((t = (e = this.view) == null ? void 0 : e.state) == null ? void 0 : t.show) || !1;
  }
}
const BB = [
  "http",
  "https",
  "ftp",
  "ftps",
  "mailto",
  "tel",
  "callto",
  "sms",
  "cid",
  "xmpp"
], PB = "https", zB = new te("node-selection-keyboard");
class HB extends Ve {
  static key() {
    return "nodeSelectionKeyboard";
  }
  constructor() {
    super(), this.addProsemirrorPlugin(
      new G({
        key: zB,
        props: {
          handleKeyDown: (e, t) => {
            if ("node" in e.state.selection) {
              if (t.ctrlKey || t.metaKey)
                return !1;
              if (t.key.length === 1)
                return t.preventDefault(), !0;
              if (t.key === "Enter" && !t.shiftKey && !t.altKey && !t.ctrlKey && !t.metaKey) {
                const r = e.state.tr;
                return e.dispatch(
                  r.insert(
                    e.state.tr.selection.$to.after(),
                    e.state.schema.nodes.paragraph.createChecked()
                  ).setSelection(
                    new L(
                      r.doc.resolve(e.state.tr.selection.$to.after() + 1)
                    )
                  )
                ), !0;
              }
            }
            return !1;
          }
        }
      })
    );
  }
}
const VB = new te("blocknote-placeholder");
class UB extends Ve {
  static key() {
    return "placeholder";
  }
  constructor(e, t) {
    super(), this.addProsemirrorPlugin(
      new G({
        key: VB,
        view: (r) => {
          var i, o;
          const s = `placeholder-selector-${lw()}`;
          r.dom.classList.add(s);
          const l = document.createElement("style"), a = e._tiptapEditor.options.injectNonce;
          a && l.setAttribute("nonce", a), ((i = e.prosemirrorView) == null ? void 0 : i.root) instanceof ShadowRoot ? e.prosemirrorView.root.append(l) : (o = e.prosemirrorView) == null || o.root.head.appendChild(l);
          const c = l.sheet, d = (u = "") => `.${s} .bn-block-content${u} .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child):before`;
          try {
            const {
              default: u,
              emptyDocument: h,
              ...f
            } = t;
            for (const [g, y] of Object.entries(f)) {
              const _ = `[data-content-type="${g}"]`;
              c.insertRule(
                `${d(_)} { content: ${JSON.stringify(
                  y
                )}; }`
              );
            }
            c.insertRule(
              `${d("[data-is-only-empty-block]")} { content: ${JSON.stringify(
                h
              )}; }`
            ), c.insertRule(
              `${d("[data-is-empty-and-focused]")} { content: ${JSON.stringify(
                u
              )}; }`
            );
          } catch (u) {
            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)",
              u
            );
          }
          return {
            destroy: () => {
              var u, h;
              ((u = e.prosemirrorView) == null ? void 0 : u.root) instanceof ShadowRoot ? e.prosemirrorView.root.removeChild(l) : (h = e.prosemirrorView) == null || h.root.head.removeChild(l);
            }
          };
        },
        props: {
          decorations: (r) => {
            const { doc: i, selection: o } = r;
            if (!e.isEditable || !o.empty || o.$from.parent.type.spec.code)
              return;
            const s = [];
            r.doc.content.size === 6 && s.push(
              se.node(2, 4, {
                "data-is-only-empty-block": "true"
              })
            );
            const l = o.$anchor, a = l.parent;
            if (a.content.size === 0) {
              const c = l.before();
              s.push(
                se.node(c, c + a.nodeSize, {
                  "data-is-empty-and-focused": "true"
                })
              );
            }
            return Q.create(i, s);
          }
        }
      })
    );
  }
}
const nb = new te("previous-blocks"), qB = {
  // Numbered List Items
  index: "index",
  // Headings
  level: "level",
  // All Blocks
  type: "type",
  depth: "depth",
  "depth-change": "depth-change"
};
class jB extends Ve {
  static key() {
    return "previousBlockType";
  }
  constructor() {
    super();
    let e;
    this.addProsemirrorPlugin(
      new G({
        key: nb,
        view(t) {
          return {
            update: async (r, i) => {
              var o;
              ((o = this.key) == null ? void 0 : o.getState(r.state).updatedBlocks.size) > 0 && (e = setTimeout(() => {
                r.dispatch(
                  r.state.tr.setMeta(nb, { clearUpdate: !0 })
                );
              }, 0));
            },
            destroy: () => {
              e && clearTimeout(e);
            }
          };
        },
        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(t, r, i, o) {
            if (r.currentTransactionOldBlockAttrs = {}, r.updatedBlocks.clear(), !t.docChanged || i.doc.eq(o.doc))
              return r;
            const s = {}, l = Rg(
              i.doc,
              (d) => d.attrs.id
            ), a = new Map(
              l.map((d) => [d.node.attrs.id, d])
            ), c = Rg(
              o.doc,
              (d) => d.attrs.id
            );
            for (const d of c) {
              const u = a.get(d.node.attrs.id), h = u == null ? void 0 : u.node.firstChild, f = d.node.firstChild;
              if (u && h && f) {
                const p = {
                  index: f.attrs.index,
                  level: f.attrs.level,
                  type: f.type.name,
                  depth: o.doc.resolve(d.pos).depth
                };
                let m = {
                  index: h.attrs.index,
                  level: h.attrs.level,
                  type: h.type.name,
                  depth: i.doc.resolve(u.pos).depth
                };
                s[d.node.attrs.id] = m, t.getMeta("numberedListIndexing") && (d.node.attrs.id in r.prevTransactionOldBlockAttrs && (m = r.prevTransactionOldBlockAttrs[d.node.attrs.id]), p.type === "numberedListItem" && (m.index = p.index)), r.currentTransactionOldBlockAttrs[d.node.attrs.id] = m, JSON.stringify(m) !== JSON.stringify(p) && (m["depth-change"] = m.depth - p.depth, r.updatedBlocks.add(d.node.attrs.id));
              }
            }
            return r.prevTransactionOldBlockAttrs = s, r;
          }
        },
        props: {
          decorations(t) {
            const r = this.getState(t);
            if (r.updatedBlocks.size === 0)
              return;
            const i = [];
            return t.doc.descendants((o, s) => {
              if (!o.attrs.id || !r.updatedBlocks.has(o.attrs.id))
                return;
              const l = r.currentTransactionOldBlockAttrs[o.attrs.id], a = {};
              for (const [d, u] of Object.entries(l))
                a["data-prev-" + qB[d]] = u || "none";
              const c = se.node(s, s + o.nodeSize, {
                ...a
              });
              i.push(c);
            }), Q.create(t.doc, i);
          }
        }
      })
    );
  }
}
const rb = new te("blocknote-show-selection");
class WB extends Ve {
  constructor(e) {
    super(), E(this, "enabled", !1), this.editor = e, this.addProsemirrorPlugin(
      new G({
        key: rb,
        props: {
          decorations: (t) => {
            const { doc: r, selection: i } = t;
            if (!this.enabled)
              return Q.empty;
            const o = se.inline(i.from, i.to, {
              "data-show-selection": "true"
            });
            return Q.create(r, [o]);
          }
        }
      })
    );
  }
  static key() {
    return "showSelection";
  }
  setEnabled(e) {
    this.enabled !== e && (this.enabled = e, this.editor.transact((t) => t.setMeta(rb, {})));
  }
  getEnabled() {
    return this.enabled;
  }
}
function Mk(n, e) {
  for (var t, r; n && n.parentElement && n.parentElement !== e.dom && ((t = n.getAttribute) == null ? void 0 : t.call(n, "data-node-type")) !== "blockContainer"; )
    n = n.parentElement;
  if (((r = n.getAttribute) == null ? void 0 : r.call(n, "data-node-type")) === "blockContainer")
    return { node: n, id: n.getAttribute("data-id") };
}
class di extends V {
  constructor(e, t) {
    super(e, t), E(this, "nodes");
    const r = e.node();
    this.nodes = [], e.doc.nodesBetween(e.pos, t.pos, (i, o, s) => {
      if (s !== null && s.eq(r))
        return this.nodes.push(i), !1;
    });
  }
  static create(e, t, r = t) {
    return new di(e.resolve(t), e.resolve(r));
  }
  content() {
    return new O(A.from(this.nodes), 0, 0);
  }
  eq(e) {
    if (!(e instanceof di) || this.nodes.length !== e.nodes.length || this.from !== e.from || this.to !== e.to)
      return !1;
    for (let t = 0; t < this.nodes.length; t++)
      if (!this.nodes[t].eq(e.nodes[t]))
        return !1;
    return !0;
  }
  map(e, t) {
    const r = t.mapResult(this.from), i = t.mapResult(this.to);
    return i.deleted ? V.near(e.resolve(r.pos)) : r.deleted ? V.near(e.resolve(i.pos)) : new di(
      e.resolve(r.pos),
      e.resolve(i.pos)
    );
  }
  toJSON() {
    return { type: "multiple-node", anchor: this.anchor, head: this.head };
  }
}
V.jsonID("multiple-node", di);
let on;
function GB(n, e) {
  let t, r;
  const i = e.resolve(n.from).node().type.spec.group === "blockContent", o = e.resolve(n.to).node().type.spec.group === "blockContent", s = Math.min(n.$anchor.depth, n.$head.depth);
  if (i && o) {
    const l = n.$from.start(s - 1), a = n.$to.end(s - 1);
    t = e.resolve(l - 1).pos, r = e.resolve(a + 1).pos;
  } else
    t = n.from, r = n.to;
  return { from: t, to: r };
}
function ib(n, e, t = e) {
  e === t && (t += n.state.doc.resolve(e + 1).node().nodeSize);
  const r = n.domAtPos(e).node.cloneNode(!0), i = n.domAtPos(e).node, o = (d, u) => Array.prototype.indexOf.call(d.children, u), s = o(
    i,
    // Expects from position to be just before the first selected block.
    n.domAtPos(e + 1).node.parentElement
  ), l = o(
    i,
    // Expects to position to be just after the last selected block.
    n.domAtPos(t - 1).node.parentElement
  );
  for (let d = i.childElementCount - 1; d >= 0; d--)
    (d > l || d < s) && r.removeChild(r.children[d]);
  Ok(n.root), on = r;
  const a = on.getElementsByTagName("iframe");
  for (let d = 0; d < a.length; d++) {
    const u = a[d], h = u.parentElement;
    h && h.removeChild(u);
  }
  const c = n.dom.className.split(" ").filter(
    (d) => d !== "ProseMirror" && d !== "bn-root" && d !== "bn-editor"
  ).join(" ");
  on.className = on.className + " bn-drag-preview " + c, n.root instanceof ShadowRoot ? n.root.appendChild(on) : n.root.body.appendChild(on);
}
function Ok(n) {
  on !== void 0 && (n instanceof ShadowRoot ? n.removeChild(on) : n.body.removeChild(on), on = void 0);
}
function KB(n, e, t) {
  if (!n.dataTransfer)
    return;
  const r = t.prosemirrorView;
  if (!r)
    return;
  const i = Nt(e.id, r.state.doc);
  if (!i)
    throw new Error(`Block with ID ${e.id} not found`);
  const o = i.posBeforeNode;
  if (o != null) {
    const s = r.state.selection, l = r.state.doc, { from: a, to: c } = GB(s, l), d = a <= o && o < c, u = s.$anchor.node() !== s.$head.node() || s instanceof di;
    d && u ? (r.dispatch(
      r.state.tr.setSelection(di.create(l, a, c))
    ), ib(r, a, c)) : (r.dispatch(
      r.state.tr.setSelection(P.create(r.state.doc, o))
    ), ib(r, o));
    const h = r.state.selection.content(), f = t.pmSchema, p = r.serializeForClipboard(h).dom.innerHTML, m = Bc(f, t), g = Sk(h.content), y = m.exportBlocks(g, {}), _ = Yf(y);
    n.dataTransfer.clearData(), n.dataTransfer.setData("blocknote/html", p), n.dataTransfer.setData("text/html", y), n.dataTransfer.setData("text/plain", _), n.dataTransfer.effectAllowed = "move", n.dataTransfer.setDragImage(on, 0, 0);
  }
}
const ob = 250;
function yh(n, e, t = !0) {
  const r = n.root.elementsFromPoint(e.left, e.top);
  for (const i of r)
    if (n.dom.contains(i))
      return t && i.closest("[data-node-type=columnList]") ? yh(
        n,
        {
          // TODO can we do better than this?
          left: e.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: e.top
        },
        !1
      ) : Mk(i, n);
}
function JB(n, e) {
  if (!e.dom.firstChild)
    return;
  const t = e.dom.firstChild.getBoundingClientRect(), r = {
    // Clamps the x position to the editor's bounding box.
    left: Math.min(
      Math.max(t.left + 10, n.x),
      t.right - 10
    ),
    top: n.y
  }, i = yh(e, r);
  if (!i)
    return;
  const o = i.node.getBoundingClientRect();
  return yh(
    e,
    {
      left: o.right - 10,
      top: n.y
    },
    !1
  );
}
class YB {
  constructor(e, t, r) {
    E(this, "state"), E(this, "emitUpdate"), E(this, "mousePos"), E(this, "hoveredBlock"), E(this, "menuFrozen", !1), E(this, "isDragOrigin", !1), E(this, "updateState", (i) => {
      this.state = i, this.emitUpdate(this.state);
    }), E(this, "updateStateFromMousePos", () => {
      var i, o, s, l, a;
      if (this.menuFrozen || !this.mousePos)
        return;
      const c = this.findClosestEditorElement({
        clientX: this.mousePos.x,
        clientY: this.mousePos.y
      });
      if ((c == null ? void 0 : c.element) !== this.pmView.dom || c.distance > ob) {
        (i = this.state) != null && i.show && (this.state.show = !1, this.updateState(this.state));
        return;
      }
      const d = JB(this.mousePos, this.pmView);
      if (!d || !this.editor.isEditable) {
        (o = this.state) != null && o.show && (this.state.show = !1, this.updateState(this.state));
        return;
      }
      if ((s = this.state) != null && s.show && (l = this.hoveredBlock) != null && l.hasAttribute("data-id") && ((a = this.hoveredBlock) == null ? void 0 : a.getAttribute("data-id")) === d.id)
        return;
      this.hoveredBlock = d.node;
      const u = d.node.firstChild;
      if (u && this.editor.isEditable) {
        const h = u.getBoundingClientRect(), f = d.node.closest("[data-node-type=column]");
        this.updateState({
          show: !0,
          referencePos: new DOMRect(
            f ? (
              // 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.
              f.firstElementChild.getBoundingClientRect().x
            ) : this.pmView.dom.firstChild.getBoundingClientRect().x,
            h.y,
            h.width,
            h.height
          ),
          block: this.editor.getBlock(
            this.hoveredBlock.getAttribute("data-id")
          )
        });
      }
    }), E(this, "onDragStart", (i) => {
      var o;
      const s = (o = i.dataTransfer) == null ? void 0 : o.getData("blocknote/html");
      if (!s || this.pmView.dragging)
        return;
      const l = document.createElement("div");
      l.innerHTML = s;
      const a = On.fromSchema(this.pmView.state.schema).parse(l, {
        topNode: this.pmView.state.schema.nodes.blockGroup.create()
      });
      this.pmView.dragging = {
        slice: new O(a.content, 0, 0),
        move: !0
      };
    }), E(this, "findClosestEditorElement", (i) => {
      const o = Array.from(this.pmView.root.querySelectorAll(".bn-editor"));
      if (o.length === 0)
        return null;
      let s = o[0], l = Number.MAX_VALUE;
      return o.forEach((a) => {
        const c = a.querySelector(".bn-block-group").getBoundingClientRect(), d = i.clientX < c.left ? c.left - i.clientX : i.clientX > c.right ? i.clientX - c.right : 0, u = i.clientY < c.top ? c.top - i.clientY : i.clientY > c.bottom ? i.clientY - c.bottom : 0, h = Math.sqrt(
          Math.pow(d, 2) + Math.pow(u, 2)
        );
        h < l && (l = h, s = a);
      }), {
        element: s,
        distance: l
      };
    }), E(this, "onDragOver", (i) => {
      if (i.synthetic)
        return;
      const o = this.getDragEventContext(i);
      if (!o || !o.isDropPoint) {
        this.closeDropCursor();
        return;
      }
      o.isDropPoint && !o.isDropWithinEditorBounds && this.dispatchSyntheticEvent(i);
    }), E(this, "closeDropCursor", () => {
      const i = new Event("dragleave", { bubbles: !1 });
      i.synthetic = !0, this.pmView.dom.dispatchEvent(i);
    }), E(this, "getDragEventContext", (i) => {
      var o;
      const s = !((o = i.dataTransfer) != null && o.types.includes("blocknote/html")) && !!this.pmView.dragging, l = !!this.isDragOrigin, a = s || l, c = this.findClosestEditorElement(i);
      if (!c || c.distance > ob)
        return;
      const d = c.element === this.pmView.dom, u = d && c.distance === 0;
      if (!(!d && !a))
        return {
          isDropPoint: d,
          isDropWithinEditorBounds: u,
          isDragOrigin: a
        };
    }), E(this, "onDrop", (i) => {
      if (i.synthetic)
        return;
      const o = this.getDragEventContext(i);
      if (!o) {
        this.closeDropCursor();
        return;
      }
      const { isDropPoint: s, isDropWithinEditorBounds: l, isDragOrigin: a } = o;
      if (!l && s && this.dispatchSyntheticEvent(i), s) {
        if (this.pmView.dragging)
          return;
        this.pmView.dispatch(
          this.pmView.state.tr.setSelection(
            L.create(
              this.pmView.state.tr.doc,
              this.pmView.state.tr.selection.anchor
            )
          )
        );
        return;
      } else if (a) {
        setTimeout(
          () => this.pmView.dispatch(this.pmView.state.tr.deleteSelection()),
          0
        );
        return;
      }
    }), E(this, "onDragEnd", (i) => {
      i.synthetic || (this.pmView.dragging = null);
    }), E(this, "onKeyDown", (i) => {
      var o;
      (o = this.state) != null && o.show && this.editor.isFocused() && (this.state.show = !1, this.emitUpdate(this.state));
    }), E(this, "onMouseMove", (i) => {
      var o;
      if (this.menuFrozen)
        return;
      this.mousePos = { x: i.clientX, y: i.clientY };
      const s = this.pmView.dom.getBoundingClientRect(), l = this.mousePos.x > s.left && this.mousePos.x < s.right && this.mousePos.y > s.top && this.mousePos.y < s.bottom, a = this.pmView.dom.parentElement;
      if (
        // Cursor is within the editor area
        l && // An element is hovered
        i && i.target && // Element is outside the editor
        !(a === i.target || a.contains(i.target))
      ) {
        (o = this.state) != null && o.show && (this.state.show = !1, this.emitUpdate(this.state));
        return;
      }
      this.updateStateFromMousePos();
    }), E(this, "onScroll", () => {
      var i;
      (i = this.state) != null && i.show && (this.state.referencePos = this.hoveredBlock.getBoundingClientRect(), this.emitUpdate(this.state)), this.updateStateFromMousePos();
    }), this.editor = e, this.pmView = t, this.emitUpdate = () => {
      if (!this.state)
        throw new Error("Attempting to update uninitialized side menu");
      r(this.state);
    }, this.pmView.root.addEventListener(
      "dragstart",
      this.onDragStart
    ), this.pmView.root.addEventListener(
      "dragover",
      this.onDragOver
    ), this.pmView.root.addEventListener(
      "drop",
      this.onDrop,
      !0
    ), this.pmView.root.addEventListener(
      "dragend",
      this.onDragEnd,
      !0
    ), Jf(), this.pmView.root.addEventListener(
      "mousemove",
      this.onMouseMove,
      !0
    ), this.pmView.root.addEventListener(
      "keydown",
      this.onKeyDown,
      !0
    ), t.root.addEventListener("scroll", this.onScroll, !0);
  }
  dispatchSyntheticEvent(e) {
    const t = new Event(e.type, e), r = this.pmView.dom.firstChild.getBoundingClientRect();
    t.clientX = e.clientX, t.clientY = e.clientY, t.clientX = Math.min(
      Math.max(e.clientX, r.left),
      r.left + r.width
    ), t.clientY = Math.min(
      Math.max(e.clientY, r.top),
      r.top + r.height
    ), t.dataTransfer = e.dataTransfer, t.preventDefault = () => e.preventDefault(), t.synthetic = !0, this.pmView.dom.dispatchEvent(t);
  }
  // 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(e, t) {
    var r;
    !t.doc.eq(this.pmView.state.doc) && (r = this.state) != null && r.show && this.updateStateFromMousePos();
  }
  destroy() {
    var e;
    (e = this.state) != null && e.show && (this.state.show = !1, this.emitUpdate(this.state)), this.pmView.root.removeEventListener(
      "mousemove",
      this.onMouseMove,
      !0
    ), this.pmView.root.removeEventListener(
      "dragstart",
      this.onDragStart
    ), this.pmView.root.removeEventListener(
      "dragover",
      this.onDragOver
    ), this.pmView.root.removeEventListener(
      "drop",
      this.onDrop,
      !0
    ), this.pmView.root.removeEventListener(
      "dragend",
      this.onDragEnd,
      !0
    ), this.pmView.root.removeEventListener(
      "keydown",
      this.onKeyDown,
      !0
    ), this.pmView.root.removeEventListener("scroll", this.onScroll, !0);
  }
}
const XB = new te("SideMenuPlugin");
class ZB extends Ve {
  constructor(e) {
    super(), E(this, "view"), E(this, "blockDragStart", (t, r) => {
      this.view && (this.view.isDragOrigin = !0), KB(t, r, this.editor);
    }), E(this, "blockDragEnd", () => {
      this.editor.prosemirrorView && Ok(this.editor.prosemirrorView.root), this.view && (this.view.isDragOrigin = !1);
    }), E(this, "freezeMenu", () => {
      this.view.menuFrozen = !0, this.view.state.show = !0, this.view.emitUpdate(this.view.state);
    }), E(this, "unfreezeMenu", () => {
      this.view.menuFrozen = !1, this.view.state.show = !1, this.view.emitUpdate(this.view.state);
    }), this.editor = e, this.addProsemirrorPlugin(
      new G({
        key: XB,
        view: (t) => (this.view = new YB(e, t, (r) => {
          this.emit("update", r);
        }), this.view)
      })
    );
  }
  static key() {
    return "sideMenu";
  }
  onUpdate(e) {
    return this.on("update", e);
  }
}
const Bl = /* @__PURE__ */ new Map();
function QB(n) {
  if (Bl.has(n))
    return Bl.get(n);
  const e = new ro();
  return n._tiptapEditor.on("transaction", ({ transaction: t }) => {
    e.appendMapping(t.mapping);
  }), n._tiptapEditor.on("destroy", () => {
    Bl.delete(n);
  }), Bl.set(n, e), e;
}
function eP(n, e, t = "left") {
  const r = ne.getState(
    n._tiptapEditor.state
  );
  if (!r) {
    const o = QB(n), s = o.maps.length;
    return () => o.slice(s).map(e, t === "left" ? -1 : 1);
  }
  const i = Ns(
    // Track the position after the position if we are on the right side
    e + (t === "right" ? 1 : 0),
    r.binding.type,
    r.binding.mapping
  );
  return () => {
    const o = ne.getState(
      n._tiptapEditor.state
    ), s = ci(
      o.doc,
      o.binding.type,
      i,
      o.binding.mapping
    );
    if (s === null)
      throw new Error("Position not found, cannot track positions");
    return s + (t === "right" ? -1 : 0);
  };
}
const tP = Sc((n) => n.type.name === "blockContainer");
class nP {
  constructor(e, t) {
    E(this, "state"), E(this, "emitUpdate"), E(this, "rootEl"), E(this, "pluginState"), E(this, "handleScroll", () => {
      var o, s;
      if ((o = this.state) != null && o.show) {
        const l = (s = this.rootEl) == null ? void 0 : s.querySelector(
          `[data-decoration-id="${this.pluginState.decorationId}"]`
        );
        if (!l)
          return;
        this.state.referencePos = l.getBoundingClientRect(), this.emitUpdate(this.pluginState.triggerCharacter);
      }
    }), E(this, "closeMenu", () => {
      this.editor.transact((o) => o.setMeta(no, null));
    }), E(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((o) => o.selection.from)
      }).run();
    });
    var r, i;
    this.editor = e, this.pluginState = void 0, this.emitUpdate = (o) => {
      var s;
      if (!this.state)
        throw new Error("Attempting to update uninitialized suggestions menu");
      t(o, {
        ...this.state,
        ignoreQueryLength: (s = this.pluginState) == null ? void 0 : s.ignoreQueryLength
      });
    }, this.rootEl = (r = this.editor.prosemirrorView) == null ? void 0 : r.root, (i = this.rootEl) == null || i.addEventListener("scroll", this.handleScroll, !0);
  }
  update(e, t) {
    var r;
    const i = no.getState(t), o = no.getState(
      e.state
    ), s = i === void 0 && o !== void 0, l = i !== void 0 && o === void 0;
    if (!s && !(i !== void 0 && o !== void 0) && !l)
      return;
    if (this.pluginState = l ? i : o, l || !this.editor.isEditable) {
      this.state && (this.state.show = !1), this.emitUpdate(this.pluginState.triggerCharacter);
      return;
    }
    const a = (r = this.rootEl) == null ? void 0 : r.querySelector(
      `[data-decoration-id="${this.pluginState.decorationId}"]`
    );
    this.editor.isEditable && a && (this.state = {
      show: !0,
      referencePos: a.getBoundingClientRect(),
      query: this.pluginState.query
    }, this.emitUpdate(this.pluginState.triggerCharacter));
  }
  destroy() {
    var e;
    (e = this.rootEl) == null || e.removeEventListener("scroll", this.handleScroll, !0);
  }
}
const no = new te("SuggestionMenuPlugin");
class rP extends Ve {
  constructor(e) {
    super(), E(this, "view"), E(this, "triggerCharacters", []), E(this, "addTriggerCharacter", (r) => {
      this.triggerCharacters.push(r);
    }), E(this, "removeTriggerCharacter", (r) => {
      this.triggerCharacters = this.triggerCharacters.filter(
        (i) => i !== r
      );
    }), E(this, "closeMenu", () => this.view.closeMenu()), E(this, "clearQuery", () => this.view.clearQuery());
    const t = this.triggerCharacters;
    this.addProsemirrorPlugin(
      new G({
        key: no,
        view: () => (this.view = new nP(
          e,
          (r, i) => {
            this.emit(`update ${r}`, i);
          }
        ), this.view),
        state: {
          // Initialize the plugin's internal state.
          init() {
          },
          // Apply changes to the plugin state from an editor transaction.
          apply: (r, i, o, s) => {
            if (r.getMeta("orderedListIndexing") !== void 0 || r.selection.$from.parent.type.spec.code)
              return i;
            const l = r.getMeta(no);
            if (typeof l == "object" && l !== null) {
              i && this.closeMenu();
              const c = eP(
                e,
                s.selection.from - // Need to account for the trigger char that was inserted, so we offset the position by the length of the trigger character.
                l.triggerCharacter.length
              );
              return {
                triggerCharacter: l.triggerCharacter,
                deleteTriggerCharacter: l.deleteTriggerCharacter !== !1,
                // When reading the queryStartPos, we offset the result by the length of the trigger character, to make it easy on the caller
                queryStartPos: () => c() + l.triggerCharacter.length,
                query: "",
                decorationId: `id_${Math.floor(Math.random() * 4294967295)}`,
                ignoreQueryLength: l == null ? void 0 : l.ignoreQueryLength
              };
            }
            if (i === void 0)
              return i;
            if (
              // Highlighting text should hide the menu.
              s.selection.from !== s.selection.to || // Transactions with plugin metadata should hide the menu.
              l === null || // Certain mouse events should hide the menu.
              // TODO: Change to global mousedown listener.
              r.getMeta("focus") || r.getMeta("blur") || r.getMeta("pointer") || // Moving the caret before the character which triggered the menu should hide it.
              i.triggerCharacter !== void 0 && s.selection.from < i.queryStartPos() || // Moving the caret to a new block should hide the menu.
              !s.selection.$from.sameParent(
                s.doc.resolve(i.queryStartPos())
              )
            )
              return;
            const a = { ...i };
            return a.query = s.doc.textBetween(
              i.queryStartPos(),
              s.selection.from
            ), a;
          }
        },
        props: {
          handleTextInput(r, i, o, s) {
            if (i === o) {
              const l = r.state.doc;
              for (const a of t) {
                const c = a.length > 1 ? l.textBetween(i - a.length, i) + s : s;
                if (a === c)
                  return r.dispatch(r.state.tr.insertText(s)), r.dispatch(
                    r.state.tr.setMeta(no, {
                      triggerCharacter: c
                    }).scrollIntoView()
                  ), !0;
              }
            }
            return !1;
          },
          // Setup decorator on the currently active suggestion.
          decorations(r) {
            const i = this.getState(r);
            if (i === void 0)
              return null;
            if (!i.deleteTriggerCharacter) {
              const o = tP(r.selection);
              if (o)
                return Q.create(r.doc, [
                  se.node(
                    o.pos,
                    o.pos + o.node.nodeSize,
                    {
                      nodeName: "span",
                      class: "bn-suggestion-decorator",
                      "data-decoration-id": i.decorationId
                    }
                  )
                ]);
            }
            return Q.create(r.doc, [
              se.inline(
                i.queryStartPos() - i.triggerCharacter.length,
                i.queryStartPos(),
                {
                  nodeName: "span",
                  class: "bn-suggestion-decorator",
                  "data-decoration-id": i.decorationId
                }
              )
            ]);
          }
        }
      })
    );
  }
  static key() {
    return "suggestionMenu";
  }
  onUpdate(e, t) {
    return this.triggerCharacters.includes(e) || this.addTriggerCharacter(e), this.on(`update ${e}`, t);
  }
  get shown() {
    var e, t;
    return ((t = (e = this.view) == null ? void 0 : e.state) == null ? void 0 : t.show) || !1;
  }
}
const iP = Je.create({
  name: "insertion",
  inclusive: !1,
  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(n) {
    return n.name !== "insertion" ? {} : {
      blocknoteIgnore: !0,
      inclusive: !1,
      toDOM(e, t) {
        return [
          "ins",
          {
            "data-id": String(e.attrs.id),
            "data-inline": String(t),
            ...!t && { style: "display: contents" }
            // changed to "contents" to make this work for table rows
          },
          0
        ];
      },
      parseDOM: [
        {
          tag: "ins",
          getAttrs(e) {
            return e.dataset.id ? {
              id: parseInt(e.dataset.id, 10)
            } : !1;
          }
        }
      ]
    };
  }
}), oP = Je.create({
  name: "deletion",
  inclusive: !1,
  excludes: "insertion modification deletion",
  addAttributes() {
    return {
      id: { default: null, validate: "number" }
      // note: validate is supported in prosemirror but not in tiptap
    };
  },
  extendMarkSchema(n) {
    return n.name !== "deletion" ? {} : {
      blocknoteIgnore: !0,
      inclusive: !1,
      // attrs: {
      //   id: { validate: "number" },
      // },
      toDOM(e, t) {
        return [
          "del",
          {
            "data-id": String(e.attrs.id),
            "data-inline": String(t),
            ...!t && { style: "display: contents" }
            // changed to "contents" to make this work for table rows
          },
          0
        ];
      },
      parseDOM: [
        {
          tag: "del",
          getAttrs(e) {
            return e.dataset.id ? {
              id: parseInt(e.dataset.id, 10)
            } : !1;
          }
        }
      ]
    };
  }
}), sP = Je.create({
  name: "modification",
  inclusive: !1,
  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(n) {
    return n.name !== "modification" ? {} : {
      blocknoteIgnore: !0,
      inclusive: !1,
      // attrs: {
      //   id: { validate: "number" },
      //   type: { validate: "string" },
      //   attrName: { default: null, validate: "string|null" },
      //   previousValue: { default: null },
      //   newValue: { default: null },
      // },
      toDOM(e, t) {
        return [
          t ? "span" : "div",
          {
            "data-type": "modification",
            "data-id": String(e.attrs.id),
            "data-mod-type": e.attrs.type,
            "data-mod-prev-val": JSON.stringify(e.attrs.previousValue),
            // TODO: Try to serialize marks with toJSON?
            "data-mod-new-val": JSON.stringify(e.attrs.newValue)
          },
          0
        ];
      },
      parseDOM: [
        {
          tag: "span[data-type='modification']",
          getAttrs(e) {
            return e.dataset.id ? {
              id: parseInt(e.dataset.id, 10),
              type: e.dataset.modType,
              previousValue: e.dataset.modPrevVal,
              newValue: e.dataset.modNewVal
            } : !1;
          }
        },
        {
          tag: "div[data-type='modification']",
          getAttrs(e) {
            return e.dataset.id ? {
              id: parseInt(e.dataset.id, 10),
              type: e.dataset.modType,
              previousValue: e.dataset.modPrevVal
            } : !1;
          }
        }
      ]
    };
  }
});
let bt;
function sb(n) {
  bt || (bt = document.createElement("div"), bt.innerHTML = "_", bt.style.opacity = "0", bt.style.height = "1px", bt.style.width = "1px", n instanceof Document ? n.body.appendChild(bt) : n.appendChild(bt));
}
function lP(n) {
  bt && (n instanceof Document ? n.body.removeChild(bt) : n.removeChild(bt), bt = void 0);
}
function Pl(n) {
  return Array.prototype.indexOf.call(n.parentElement.childNodes, n);
}
function aP(n) {
  let e = n;
  for (; e && e.nodeName !== "TD" && e.nodeName !== "TH" && !e.classList.contains("tableWrapper"); ) {
    if (e.classList.contains("ProseMirror"))
      return;
    const t = e.parentNode;
    if (!t || !(t instanceof Element))
      return;
    e = t;
  }
  return e.nodeName === "TD" || e.nodeName === "TH" ? {
    type: "cell",
    domNode: e,
    tbodyNode: e.closest("tbody")
  } : {
    type: "wrapper",
    domNode: e,
    tbodyNode: e.querySelector("tbody")
  };
}
function cP(n, e) {
  const t = e.querySelectorAll(n);
  for (let r = 0; r < t.length; r++)
    t[r].style.visibility = "hidden";
}
class dP {
  constructor(e, t, r) {
    E(this, "state"), E(this, "emitUpdate"), E(this, "tableId"), E(this, "tablePos"), E(this, "tableElement"), E(this, "menuFrozen", !1), E(this, "mouseState", "up"), E(this, "prevWasEditable", null), E(this, "viewMousedownHandler", () => {
      this.mouseState = "down";
    }), E(this, "mouseUpHandler", (i) => {
      this.mouseState = "up", this.mouseMoveHandler(i);
    }), E(this, "mouseMoveHandler", (i) => {
      var o, s, l, a, c, d, u;
      if (this.menuFrozen || this.mouseState === "selecting" || !(i.target instanceof Element) || !this.pmView.dom.contains(i.target))
        return;
      const h = aP(i.target);
      if ((h == null ? void 0 : h.type) === "cell" && this.mouseState === "down" && !((o = this.state) != null && o.draggingState)) {
        this.mouseState = "selecting", (s = this.state) != null && s.show && (this.state.show = !1, this.state.showAddOrRemoveRowsButton = !1, this.state.showAddOrRemoveColumnsButton = !1, this.emitUpdate());
        return;
      }
      if (!h || !this.editor.isEditable) {
        (l = this.state) != null && l.show && (this.state.show = !1, this.state.showAddOrRemoveRowsButton = !1, this.state.showAddOrRemoveColumnsButton = !1, this.emitUpdate());
        return;
      }
      if (!h.tbodyNode)
        return;
      const f = h.tbodyNode.getBoundingClientRect(), p = Mk(h.domNode, this.pmView);
      if (!p)
        return;
      this.tableElement = p.node;
      let m;
      const g = this.editor.transact(
        (b) => Nt(p.id, b.doc)
      );
      if (!g)
        throw new Error(`Block with ID ${p.id} not found`);
      const y = Se(
        g.node,
        this.editor.pmSchema,
        this.editor.schema.blockSchema,
        this.editor.schema.inlineContentSchema,
        this.editor.schema.styleSchema
      );
      if (_R("table", y, this.editor) && (this.tablePos = g.posBeforeNode + 1, m = y), !m)
        return;
      this.tableId = p.id;
      const _ = (a = h.domNode.closest(".tableWrapper")) == null ? void 0 : a.querySelector(".table-widgets-container");
      if ((h == null ? void 0 : h.type) === "wrapper") {
        const b = i.clientY >= f.bottom - 1 && // -1 to account for fractions of pixels in "bottom"
        i.clientY < f.bottom + 20, k = i.clientX >= f.right - 1 && i.clientX < f.right + 20, C = i.clientX > f.right || i.clientY > f.bottom;
        this.state = {
          ...this.state,
          show: !0,
          showAddOrRemoveRowsButton: b,
          showAddOrRemoveColumnsButton: k,
          referencePosTable: f,
          block: m,
          widgetContainer: _,
          colIndex: C || (c = this.state) == null ? void 0 : c.colIndex,
          rowIndex: C || (d = this.state) == null ? void 0 : d.rowIndex,
          referencePosCell: C || (u = this.state) == null ? void 0 : u.referencePosCell
        };
      } else {
        const b = Pl(h.domNode), k = Pl(h.domNode.parentElement), C = h.domNode.getBoundingClientRect();
        if (this.state !== void 0 && this.state.show && this.tableId === p.id && this.state.rowIndex === k && this.state.colIndex === b)
          return;
        this.state = {
          show: !0,
          showAddOrRemoveColumnsButton: b === m.content.rows[0].cells.length - 1,
          showAddOrRemoveRowsButton: k === m.content.rows.length - 1,
          referencePosTable: f,
          block: m,
          draggingState: void 0,
          referencePosCell: C,
          colIndex: b,
          rowIndex: k,
          widgetContainer: _
        };
      }
      return this.emitUpdate(), !1;
    }), E(this, "dragOverHandler", (i) => {
      var o;
      if (((o = this.state) == null ? void 0 : o.draggingState) === void 0)
        return;
      i.preventDefault(), i.dataTransfer.dropEffect = "move", cP(
        ".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline",
        this.pmView.root
      );
      const s = {
        left: Math.min(
          Math.max(i.clientX, this.state.referencePosTable.left + 1),
          this.state.referencePosTable.right - 1
        ),
        top: Math.min(
          Math.max(i.clientY, this.state.referencePosTable.top + 1),
          this.state.referencePosTable.bottom - 1
        )
      }, l = this.pmView.root.elementsFromPoint(s.left, s.top).filter(
        (m) => m.tagName === "TD" || m.tagName === "TH"
      );
      if (l.length === 0)
        return;
      const a = l[0];
      let c = !1;
      const d = Pl(a.parentElement), u = Pl(a), h = this.state.draggingState.draggedCellOrientation === "row" ? this.state.rowIndex : this.state.colIndex, f = (this.state.draggingState.draggedCellOrientation === "row" ? d : u) !== h;
      (this.state.rowIndex !== d || this.state.colIndex !== u) && (this.state.rowIndex = d, this.state.colIndex = u, this.state.referencePosCell = a.getBoundingClientRect(), c = !0);
      const p = this.state.draggingState.draggedCellOrientation === "row" ? s.top : s.left;
      this.state.draggingState.mousePos !== p && (this.state.draggingState.mousePos = p, c = !0), c && this.emitUpdate(), f && this.editor.transact((m) => m.setMeta(Uo, !0));
    }), E(this, "dropHandler", (i) => {
      if (this.mouseState = "up", this.state === void 0 || this.state.draggingState === void 0)
        return !1;
      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."
        );
      i.preventDefault();
      const { draggingState: o, colIndex: s, rowIndex: l } = this.state, a = this.state.block.content.columnWidths;
      if (o.draggedCellOrientation === "row") {
        if (!G1(
          this.state.block,
          o.originalIndex,
          l
        ))
          return !1;
        const c = qI(
          this.state.block,
          o.originalIndex,
          l
        );
        this.editor.updateBlock(this.state.block, {
          type: "table",
          content: {
            ...this.state.block.content,
            rows: c
          }
        });
      } else {
        if (!K1(
          this.state.block,
          o.originalIndex,
          s
        ))
          return !1;
        const c = UI(
          this.state.block,
          o.originalIndex,
          s
        ), [d] = a.splice(o.originalIndex, 1);
        a.splice(s, 0, d), this.editor.updateBlock(this.state.block, {
          type: "table",
          content: {
            ...this.state.block.content,
            columnWidths: a,
            rows: c
          }
        });
      }
      return this.editor.setTextCursorPosition(this.state.block.id), !0;
    }), this.editor = e, this.pmView = t, this.emitUpdate = () => {
      if (!this.state)
        throw new Error("Attempting to update uninitialized image toolbar");
      r(this.state);
    }, t.dom.addEventListener("mousemove", this.mouseMoveHandler), t.dom.addEventListener("mousedown", this.viewMousedownHandler), window.addEventListener("mouseup", this.mouseUpHandler), t.root.addEventListener(
      "dragover",
      this.dragOverHandler
    ), t.root.addEventListener(
      "drop",
      this.dropHandler
    );
  }
  // Updates drag handles when the table is modified or removed.
  update() {
    var e;
    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
    !((e = this.tableElement) != null && e.isConnected)) {
      this.state.show = !1, this.state.showAddOrRemoveRowsButton = !1, this.state.showAddOrRemoveColumnsButton = !1, this.emitUpdate();
      return;
    }
    const { height: t, width: r } = qf(
      this.state.block
    );
    this.state.rowIndex !== void 0 && this.state.colIndex !== void 0 && (this.state.rowIndex >= t && (this.state.rowIndex = t - 1), this.state.colIndex >= r && (this.state.colIndex = r - 1));
    const i = this.tableElement.querySelector("tbody");
    if (!i)
      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 o = i.children[this.state.rowIndex].children[this.state.colIndex];
      o ? this.state.referencePosCell = o.getBoundingClientRect() : (this.state.rowIndex = void 0, this.state.colIndex = void 0);
    }
    this.state.referencePosTable = i.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
    );
  }
}
const Uo = new te("TableHandlesPlugin");
class uP extends Ve {
  constructor(e) {
    super(), E(this, "view"), E(this, "colDragStart", (t) => {
      if (this.view.state === void 0 || this.view.state.colIndex === void 0)
        throw new Error(
          "Attempted to drag table column, but no table block was hovered prior."
        );
      if (this.view.state.draggingState = {
        draggedCellOrientation: "col",
        originalIndex: this.view.state.colIndex,
        mousePos: t.clientX
      }, this.view.emitUpdate(), this.editor.transact(
        (r) => r.setMeta(Uo, {
          draggedCellOrientation: this.view.state.draggingState.draggedCellOrientation,
          originalIndex: this.view.state.colIndex,
          newIndex: this.view.state.colIndex,
          tablePos: this.view.tablePos
        })
      ), !this.editor.prosemirrorView)
        throw new Error("Editor view not initialized.");
      sb(this.editor.prosemirrorView.root), t.dataTransfer.setDragImage(bt, 0, 0), t.dataTransfer.effectAllowed = "move";
    }), E(this, "rowDragStart", (t) => {
      if (this.view.state === void 0 || this.view.state.rowIndex === void 0)
        throw new Error(
          "Attempted to drag table row, but no table block was hovered prior."
        );
      if (this.view.state.draggingState = {
        draggedCellOrientation: "row",
        originalIndex: this.view.state.rowIndex,
        mousePos: t.clientY
      }, this.view.emitUpdate(), this.editor.transact(
        (r) => r.setMeta(Uo, {
          draggedCellOrientation: this.view.state.draggingState.draggedCellOrientation,
          originalIndex: this.view.state.rowIndex,
          newIndex: this.view.state.rowIndex,
          tablePos: this.view.tablePos
        })
      ), !this.editor.prosemirrorView)
        throw new Error("Editor view not initialized.");
      sb(this.editor.prosemirrorView.root), t.dataTransfer.setDragImage(bt, 0, 0), t.dataTransfer.effectAllowed = "copyMove";
    }), E(this, "dragEnd", () => {
      if (this.view.state === void 0)
        throw new Error(
          "Attempted to drag table row, but no table block was hovered prior."
        );
      if (this.view.state.draggingState = void 0, this.view.emitUpdate(), this.editor.transact((t) => t.setMeta(Uo, null)), !this.editor.prosemirrorView)
        throw new Error("Editor view not initialized.");
      lP(this.editor.prosemirrorView.root);
    }), E(this, "freezeHandles", () => {
      this.view.menuFrozen = !0;
    }), E(this, "unfreezeHandles", () => {
      this.view.menuFrozen = !1;
    }), E(this, "getCellsAtRowHandle", (t, r) => uh(t, r)), E(this, "getCellsAtColumnHandle", (t, r) => hh(t, r)), E(this, "setCellSelection", (t, r, i = r) => {
      const o = this.view;
      if (!o)
        throw new Error("Table handles view not initialized");
      const s = t.doc.resolve(o.tablePos + 1), l = t.doc.resolve(
        s.posAtIndex(r.row) + 1
      ), a = t.doc.resolve(
        // No need for +1, since CellSelection expects the position before the cell
        l.posAtIndex(r.col)
      ), c = t.doc.resolve(
        s.posAtIndex(i.row) + 1
      ), d = t.doc.resolve(
        // No need for +1, since CellSelection expects the position before the cell
        c.posAtIndex(i.col)
      ), u = t.tr;
      return u.setSelection(
        new le(a, d)
      ), t.apply(u);
    }), E(this, "addRowOrColumn", (t, r) => {
      this.editor.exec((i, o) => {
        const s = this.setCellSelection(
          i,
          r.orientation === "row" ? { row: t, col: 0 } : { row: 0, col: t }
        );
        return r.orientation === "row" ? r.side === "above" ? R2(s, o) : B2(s, o) : r.side === "left" ? F2(s, o) : N2(s, o);
      });
    }), E(this, "removeRowOrColumn", (t, r) => r === "row" ? this.editor.exec((i, o) => {
      const s = this.setCellSelection(i, {
        row: t,
        col: 0
      });
      return z2(s, o);
    }) : this.editor.exec((i, o) => {
      const s = this.setCellSelection(i, {
        row: 0,
        col: t
      });
      return I2(s, o);
    })), E(this, "mergeCells", (t) => this.editor.exec((r, i) => {
      const o = t ? this.setCellSelection(
        r,
        t.relativeStartCell,
        t.relativeEndCell
      ) : r;
      return V2(o, i);
    })), E(this, "splitCell", (t) => this.editor.exec((r, i) => {
      const o = t ? this.setCellSelection(r, t) : r;
      return U2(o, i);
    })), E(this, "getCellSelection", () => this.editor.transact((t) => {
      const r = t.selection;
      let i = r.$from, o = r.$to;
      if (J0(r)) {
        const { ranges: p } = r;
        p.forEach((m) => {
          i = m.$from.min(i ?? m.$from), o = m.$to.max(o ?? m.$to);
        });
      } else if (i = t.doc.resolve(
        r.$from.pos - r.$from.parentOffset - 1
      ), o = t.doc.resolve(
        r.$to.pos - r.$to.parentOffset - 1
      ), i.pos === 0 || o.pos === 0)
        return;
      const s = t.doc.resolve(
        i.pos - i.parentOffset - 1
      ), l = t.doc.resolve(o.pos - o.parentOffset - 1), a = t.doc.resolve(s.pos - s.parentOffset - 1), c = i.index(s.depth), d = s.index(a.depth), u = o.index(l.depth), h = l.index(a.depth), f = [];
      for (let p = d; p <= h; p++)
        for (let m = c; m <= u; m++)
          f.push({ row: p, col: m });
      return {
        from: {
          row: d,
          col: c
        },
        to: {
          row: h,
          col: u
        },
        cells: f
      };
    })), E(this, "getMergeDirection", (t) => this.editor.transact((r) => {
      const i = J0(r.selection) ? r.selection : void 0;
      if (!i || !t || // Only offer the merge button if there is more than one cell selected.
      i.ranges.length <= 1)
        return;
      const o = this.getCellSelection();
      if (o)
        return GI(o.from, o.to, t) ? "vertical" : "horizontal";
    })), E(this, "cropEmptyRowsOrColumns", (t, r) => jI(t, r)), E(this, "addRowsOrColumns", (t, r, i) => WI(t, r, i)), this.editor = e, this.addProsemirrorPlugin(
      new G({
        key: Uo,
        view: (t) => (this.view = new dP(e, t, (r) => {
          this.emit("update", r);
        }), this.view),
        // 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: (t) => {
            if (this.view === void 0 || this.view.state === void 0 || this.view.state.draggingState === void 0 || this.view.tablePos === void 0)
              return;
            const r = this.view.state.draggingState.draggedCellOrientation === "row" ? this.view.state.rowIndex : this.view.state.colIndex;
            if (r === void 0)
              return;
            const i = [], { block: o, draggingState: s } = this.view.state, { originalIndex: l, draggedCellOrientation: a } = s;
            if (r === l || !o || a === "row" && !G1(o, l, r) || a === "col" && !K1(o, l, r))
              return Q.create(t.doc, i);
            const c = t.doc.resolve(this.view.tablePos + 1);
            return this.view.state.draggingState.draggedCellOrientation === "row" ? uh(
              this.view.state.block,
              r
            ).forEach(({ row: d, col: u }) => {
              const h = t.doc.resolve(
                c.posAtIndex(d) + 1
              ), f = t.doc.resolve(
                h.posAtIndex(u) + 1
              ), p = f.node(), m = f.pos + (r > l ? p.nodeSize - 2 : 0);
              i.push(
                // The widget is a small bar which spans the width of the cell.
                se.widget(m, () => {
                  const g = document.createElement("div");
                  return g.className = "bn-table-drop-cursor", g.style.left = "0", g.style.right = "0", r > l ? g.style.bottom = "-2px" : g.style.top = "-3px", g.style.height = "4px", g;
                })
              );
            }) : hh(
              this.view.state.block,
              r
            ).forEach(({ row: d, col: u }) => {
              const h = t.doc.resolve(
                c.posAtIndex(d) + 1
              ), f = t.doc.resolve(
                h.posAtIndex(u) + 1
              ), p = f.node(), m = f.pos + (r > l ? p.nodeSize - 2 : 0);
              i.push(
                // The widget is a small bar which spans the height of the cell.
                se.widget(m, () => {
                  const g = document.createElement("div");
                  return g.className = "bn-table-drop-cursor", g.style.top = "0", g.style.bottom = "0", r > l ? g.style.right = "-2px" : g.style.left = "-3px", g.style.width = "4px", g;
                })
              );
            }), Q.create(t.doc, i);
          }
        }
      })
    );
  }
  static key() {
    return "tableHandles";
  }
  onUpdate(e) {
    return this.on("update", e);
  }
}
const hP = he.create({
  name: "textAlignment",
  addGlobalAttributes() {
    return [
      {
        // Attribute is applied to block content instead of container so that child blocks don't inherit the text
        // alignment styling.
        types: [
          "paragraph",
          "heading",
          "bulletListItem",
          "numberedListItem",
          "checkListItem",
          "tableCell",
          "tableHeader"
        ],
        attributes: {
          textAlignment: {
            default: "left",
            parseHTML: (n) => n.getAttribute("data-text-alignment"),
            renderHTML: (n) => n.textAlignment === "left" ? {} : {
              "data-text-alignment": n.textAlignment
            }
          }
        }
      }
    ];
  }
}), fP = he.create({
  name: "blockTextColor",
  addGlobalAttributes() {
    return [
      {
        types: ["blockContainer", "tableCell", "tableHeader"],
        attributes: {
          textColor: {
            default: Fe.textColor.default,
            parseHTML: (n) => n.hasAttribute("data-text-color") ? n.getAttribute("data-text-color") : Fe.textColor.default,
            renderHTML: (n) => n.textColor === Fe.textColor.default ? {} : {
              "data-text-color": n.textColor
            }
          }
        }
      }
    ];
  }
}), pP = he.create({
  name: "trailingNode",
  addProseMirrorPlugins() {
    const n = new te(this.name);
    return [
      new G({
        key: n,
        appendTransaction: (e, t, r) => {
          const { doc: i, tr: o, schema: s } = r, l = n.getState(r), a = i.content.size - 2, c = s.nodes.blockContainer, d = s.nodes.paragraph;
          if (l)
            return o.insert(
              a,
              c.create(void 0, d.create())
            );
        },
        state: {
          init: (e, t) => {
          },
          apply: (e, t) => {
            if (!e.docChanged)
              return t;
            let r = e.doc.lastChild;
            if (!r || r.type.name !== "blockGroup")
              throw new Error("Expected blockGroup");
            if (r = r.lastChild, !r || r.type.name !== "blockContainer")
              return !0;
            const i = r.firstChild;
            if (!i)
              throw new Error("Expected blockContent");
            return r.nodeSize > 4 || i.type.spec.content !== "inline*";
          }
        }
      })
    ];
  }
}), mP = {
  blockColor: "data-block-color",
  blockStyle: "data-block-style",
  id: "data-id",
  depth: "data-depth",
  depthChange: "data-depth-change"
}, gP = Mt.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: !0,
  marks: "insertion modification deletion",
  parseHTML() {
    return [
      {
        tag: "div[data-node-type=" + this.name + "]",
        getAttrs: (n) => {
          if (typeof n == "string")
            return !1;
          const e = {};
          for (const [t, r] of Object.entries(mP))
            n.getAttribute(r) && (e[t] = n.getAttribute(r));
          return e;
        }
      },
      // Ignore `blockOuter` divs, but parse the `blockContainer` divs inside them.
      {
        tag: 'div[data-node-type="blockOuter"]',
        skip: !0
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e;
    const t = document.createElement("div");
    t.className = "bn-block-outer", t.setAttribute("data-node-type", "blockOuter");
    for (const [o, s] of Object.entries(n))
      o !== "class" && t.setAttribute(o, s);
    const r = {
      ...((e = this.options.domAttributes) == null ? void 0 : e.block) || {},
      ...n
    }, i = document.createElement("div");
    i.className = Rr("bn-block", r.class), i.setAttribute("data-node-type", this.name);
    for (const [o, s] of Object.entries(r))
      o !== "class" && i.setAttribute(o, s);
    return t.appendChild(i), {
      dom: t,
      contentDOM: i
    };
  }
}), bP = Mt.create({
  name: "blockGroup",
  group: "childContainer",
  content: "blockGroupChild+",
  marks: "deletion insertion modification",
  parseHTML() {
    return [
      {
        tag: "div",
        getAttrs: (n) => typeof n == "string" ? !1 : n.getAttribute("data-node-type") === "blockGroup" ? null : !1
      }
    ];
  },
  renderHTML({ HTMLAttributes: n }) {
    var e;
    const t = {
      ...((e = this.options.domAttributes) == null ? void 0 : e.blockGroup) || {},
      ...n
    }, r = document.createElement("div");
    r.className = Rr(
      "bn-block-group",
      t.class
    ), r.setAttribute("data-node-type", "blockGroup");
    for (const [i, o] of Object.entries(t))
      i !== "class" && r.setAttribute(i, o);
    return {
      dom: r,
      contentDOM: r
    };
  }
}), yP = Mt.create({
  name: "doc",
  topNode: !0,
  content: "blockGroup",
  marks: "insertion modification deletion"
});
class _P extends Ve {
  constructor({
    editor: e,
    collaboration: t
  }) {
    super(e), E(this, "editor"), E(this, "collaboration"), E(this, "forkedState"), this.editor = e, this.collaboration = t;
  }
  static key() {
    return "ForkYDocPlugin";
  }
  /**
   * To find a fragment in another ydoc, we need to search for it.
   */
  findTypeInOtherYdoc(e, t) {
    const r = e.doc;
    if (e._item === null) {
      const i = Array.from(r.share.keys()).find(
        (o) => r.share.get(o) === e
      );
      if (i == null)
        throw new Error("type does not exist in other ydoc");
      return t.get(i, e.constructor);
    } else {
      const i = e._item, o = t.store.clients.get(i.id.client) ?? [], s = Zt(o, i.id.clock);
      return o[s].content.type;
    }
  }
  /**
   * Whether the editor is editing a forked document,
   * preserving a reference to the original document and the forked document.
   */
  get isForkedFromRemote() {
    return this.forkedState !== void 0;
  }
  /**
   * 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() {
    var e;
    if (this.isForkedFromRemote)
      return;
    const t = (e = this.collaboration) == null ? void 0 : e.fragment;
    if (!t)
      throw new Error("No fragment to fork from");
    const r = new Hr();
    y0(r, _0(t.doc));
    const i = this.findTypeInOtherYdoc(t, r);
    this.forkedState = {
      undoStack: Wt.getState(this.editor.prosemirrorState).undoManager.undoStack,
      originalFragment: t,
      forkedFragment: i
    }, this.editor._tiptapEditor.unregisterPlugin([
      Vo,
      Wt,
      ne
    ]), this.editor._tiptapEditor.registerPlugin(
      new gh(i).plugins[0]
    ), this.editor._tiptapEditor.registerPlugin(
      new bh({ editor: this.editor }).plugins[0]
    ), this.emit("forked", !0);
  }
  /**
   * 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: e }) {
    if (!this.forkedState)
      return;
    this.editor._tiptapEditor.unregisterPlugin(ne), this.editor._tiptapEditor.unregisterPlugin(Wt);
    const { originalFragment: t, forkedFragment: r, undoStack: i } = this.forkedState;
    if (this.editor.extensions.ySyncPlugin = new gh(t), this.editor.extensions.yCursorPlugin = new Dk(
      this.collaboration
    ), this.editor.extensions.yUndoPlugin = new bh({
      editor: this.editor
    }), this.editor._tiptapEditor.registerPlugin(
      this.editor.extensions.ySyncPlugin.plugins[0]
    ), this.editor._tiptapEditor.registerPlugin(
      this.editor.extensions.yCursorPlugin.plugins[0]
    ), this.editor._tiptapEditor.registerPlugin(
      this.editor.extensions.yUndoPlugin.plugins[0]
    ), Wt.getState(
      this.editor.prosemirrorState
    ).undoManager.undoStack = i, e) {
      const o = _0(
        r.doc,
        LN(t.doc)
      );
      y0(t.doc, o, this.editor);
    }
    this.forkedState = void 0, this.emit("forked", !1);
  }
}
const wP = (n) => {
  var e;
  const t = {}, r = kP(n);
  for (const o of r)
    t[o.name] = o;
  n.collaboration && (t.ySyncPlugin = new gh(n.collaboration.fragment), t.yUndoPlugin = new bh({ editor: n.editor }), (e = n.collaboration.provider) != null && e.awareness && (t.yCursorPlugin = new Dk(n.collaboration)), t.forkYDocPlugin = new _P({
    editor: n.editor,
    collaboration: n.collaboration
  })), t.formattingToolbar = new MB(
    n.editor
  ), t.linkToolbar = new RB(n.editor), t.sideMenu = new ZB(n.editor), t.suggestionMenus = new rP(n.editor), t.filePanel = new DB(n.editor), t.placeholder = new UB(n.editor, n.placeholders), (n.animations ?? !0) && (t.animations = new jB()), n.tableHandles && (t.tableHandles = new uP(n.editor)), t.nodeSelectionKeyboard = new HB(), t.blockChange = new kB(), t.showSelection = new WB(n.editor), n.comments && (t.comments = new EB(
    n.editor,
    n.comments.threadStore,
    Ak.name
  ));
  const i = n.disableExtensions || [];
  for (const o of i)
    delete t[o];
  return t;
};
let lb = !1;
const kP = (n) => {
  const e = [
    Io.ClipboardTextSerializer,
    Io.Commands,
    Io.Editable,
    Io.FocusEvents,
    Io.Tabindex,
    // DevTools,
    _O,
    // DropCursor,
    he.create({
      name: "dropCursor",
      addProseMirrorPlugins: () => [
        n.dropCursor({
          width: 5,
          color: "#ddeeff",
          editor: n.editor
        })
      ]
    }),
    Nc.configure({
      // everything from bnBlock group (nodes that represent a BlockNote block should have an id)
      types: ["blockContainer", "columnList", "column"],
      setIdAttribute: n.setIdAttribute
    }),
    OB,
    // Comments,
    // basics:
    tF,
    // marks:
    iP,
    oP,
    sP,
    eF.extend({
      inclusive: !1
    }).configure({
      defaultProtocol: PB,
      // only call this once if we have multiple editors installed. Or fix https://github.com/ueberdosis/tiptap/issues/5450
      protocols: lb ? [] : BB
    }),
    ...Object.values(n.styleSpecs).map((t) => t.implementation.mark.configure({
      editor: n.editor
    })),
    fP,
    wB,
    hP,
    // make sure escape blurs editor, so that we can tab to other elements in the host page (accessibility)
    he.create({
      name: "OverrideEscape",
      addKeyboardShortcuts() {
        return {
          Escape: () => n.editor.suggestionMenus.shown ? !1 : this.editor.commands.blur()
        };
      }
    }),
    // nodes
    yP,
    gP.configure({
      editor: n.editor,
      domAttributes: n.domAttributes
    }),
    $B.configure({
      editor: n.editor,
      tabBehavior: n.tabBehavior
    }),
    bP.configure({
      domAttributes: n.domAttributes
    }),
    ...Object.values(n.inlineContentSpecs).filter((t) => t.config !== "link" && t.config !== "text").map((t) => t.implementation.node.configure({
      editor: n.editor
    })),
    ...Object.values(n.blockSpecs).flatMap((t) => [
      // dependent nodes (e.g.: tablecell / row)
      ...(t.implementation.requiredExtensions || []).map(
        (r) => r.configure({
          editor: n.editor,
          domAttributes: n.domAttributes
        })
      ),
      // the actual node itself
      t.implementation.node.configure({
        editor: n.editor,
        domAttributes: n.domAttributes
      })
    ]),
    _B(n.editor),
    bB(
      n.editor,
      n.pasteHandler || ((t) => t.defaultPasteHandler())
    ),
    eB(n.editor),
    // This needs to be at the bottom of this list, because Key events (such as enter, when selecting a /command),
    // should be handled before Enter handlers in other components like splitListItem
    ...n.trailingBlock === void 0 || n.trailingBlock ? [pP] : [],
    ...n.comments ? [Ak] : []
  ];
  return lb = !0, n.collaboration || e.push(TO), e;
};
function vP(n, e) {
  const t = [];
  return n.forEach((r, i, o) => {
    o !== e && t.push(r);
  }), A.from(t);
}
function CP(n, e) {
  const t = [];
  for (let r = 0; r < n.childCount; r++)
    if (n.child(r).type.name === "tableRow")
      if (t.length > 0 && t[t.length - 1].type.name === "table") {
        const i = t[t.length - 1], o = i.copy(i.content.addToEnd(n.child(r)));
        t[t.length - 1] = o;
      } else {
        const i = e.nodes.table.createChecked(
          void 0,
          n.child(r)
        );
        t.push(i);
      }
    else
      t.push(n.child(r));
  return n = A.from(t), n;
}
function SP(n, e) {
  let t = A.from(n.content);
  if (t = CP(t, e.state.schema), !EP(t, e))
    return new O(t, n.openStart, n.openEnd);
  for (let r = 0; r < t.childCount; r++)
    if (t.child(r).type.spec.group === "blockContent") {
      const i = [t.child(r)];
      if (r + 1 < t.childCount && t.child(r + 1).type.name === "blockGroup") {
        const s = t.child(r + 1).child(0).child(0);
        (s.type.name === "bulletListItem" || s.type.name === "numberedListItem" || s.type.name === "checkListItem") && (i.push(t.child(r + 1)), t = vP(t, r + 1));
      }
      const o = e.state.schema.nodes.blockContainer.createChecked(
        void 0,
        i
      );
      t = t.replaceChild(r, o);
    }
  return new O(t, n.openStart, n.openEnd);
}
function EP(n, e) {
  var t, r;
  const i = n.childCount === 1, o = ((t = n.firstChild) == null ? void 0 : t.type.spec.content) === "inline*", s = ((r = n.firstChild) == null ? void 0 : r.type.spec.content) === "tableRow+";
  if (i) {
    if (o)
      return !1;
    if (s) {
      const l = ge(e.state);
      if (l.isBlockContainer)
        return l.blockContent.node.type.spec.content !== "tableRow+";
    }
  }
  return !0;
}
const _h = class extends HM {
  constructor(e, t) {
    super({ ...e, content: void 0 }), E(this, "_state"), E(this, "mount", (l, a, c) => {
      a ? (this.options.element = a, this.createViewAlternative(l, c)) : (this.destroy(), this.isInitialized = !1);
    });
    const r = this.schema;
    let i;
    const o = r.nodes.doc.createAndFill;
    r.nodes.doc.createAndFill = (...l) => {
      if (i)
        return i;
      const a = o.apply(r.nodes.doc, l), c = JSON.parse(JSON.stringify(a.toJSON()));
      return c.content[0].content[0].attrs.id = "initialBlockId", i = Qn.fromJSON(r, c), i;
    };
    let s;
    try {
      const l = e == null ? void 0 : e.content.map(
        (a) => Di(a, this.schema, t).toJSON()
      );
      s = Ca(
        {
          type: "doc",
          content: [
            {
              type: "blockGroup",
              content: l
            }
          ]
        },
        this.schema,
        this.options.parseOptions
      );
    } catch (l) {
      throw console.error(
        "Error creating document from blocks passed as `initialContent`. Caused by exception: ",
        l
      ), new Error(
        "Error creating document from blocks passed as `initialContent`:\n" + +JSON.stringify(e.content)
      );
    }
    this._state = Zr.create({
      doc: s,
      schema: this.schema
      // selection: selection || undefined,
    });
  }
  get state() {
    return this.view && (this._state = this.view.state), this._state;
  }
  dispatch(e) {
    if (!this.view) {
      this._state = this.state.apply(e), this.emit("transaction", {
        editor: this,
        transaction: e
      });
      return;
    }
    if (this.view.isDestroyed)
      return;
    if (this.isCapturingTransaction) {
      this.dispatchTransaction(e);
      return;
    }
    const { state: t, transactions: r } = this.state.applyTransaction(e), i = !this.state.selection.eq(t.selection);
    this.emit("beforeTransaction", {
      editor: this,
      transaction: e,
      nextState: t
    }), this.view.updateState(t), this.emit("transaction", {
      editor: this,
      transaction: e
    }), i && this.emit("selectionUpdate", {
      editor: this,
      transaction: e
    });
    const o = e.getMeta("focus"), s = e.getMeta("blur");
    o && this.emit("focus", {
      editor: this,
      event: o.event,
      transaction: e
    }), s && this.emit("blur", {
      editor: this,
      event: s.event,
      transaction: e
    }), !(!e.docChanged || e.getMeta("preventUpdate")) && (this.emit("update", {
      editor: this,
      transaction: e
    }), this.emit("v3-update", {
      editor: this,
      transaction: e,
      appendedTransactions: r.slice(1)
    }));
  }
  // a helper method that can enable plugins before the view has been initialized
  // currently only used for testing
  forceEnablePlugins() {
    if (this.view)
      throw new Error(
        "forcePluginsEnabled called after view has been initialized"
      );
    this._state = this.state.reconfigure({
      plugins: this.extensionManager.plugins
    });
  }
  /**
   * Replace the default `createView` method with a custom one - which we call on mount
   */
  createViewAlternative(e, t) {
    this.contentComponent = t;
    const r = {};
    this.extensionManager.extensions.forEach((o) => {
      o.type === "mark" && o.config.addMarkView && (r[o.name] = o.config.addMarkView(e));
    }), this.view = new Vh(
      { mount: this.options.element },
      // use mount option so that we reuse the existing element instead of creating a new one
      {
        ...this.options.editorProps,
        // @ts-ignore
        dispatchTransaction: this.dispatch.bind(this),
        state: this.state,
        markViews: r,
        nodeViews: this.extensionManager.nodeViews
      }
    );
    const i = this.state.reconfigure({
      plugins: this.extensionManager.plugins
    });
    this.view.updateState(i), this.commands.focus(
      this.options.autofocus || this.options.element.getAttribute("data-bn-autofocus") === "true",
      { scrollIntoView: !1 }
    ), this.emit("create", { editor: this }), this.isInitialized = !0;
  }
};
E(_h, "create", (n, e) => {
  var t, r;
  const i = (t = globalThis == null ? void 0 : globalThis.window) == null ? void 0 : t.setTimeout;
  typeof ((r = globalThis == null ? void 0 : globalThis.window) == null ? void 0 : r.setTimeout) < "u" && (globalThis.window.setTimeout = () => 0);
  try {
    return new _h(n, e);
  } finally {
    i && (globalThis.window.setTimeout = i);
  }
});
let Fk = _h;
Fk.prototype.createView = function() {
  this.options.onPaste = this.options.onDrop = void 0;
};
const xP = {
  enableInputRules: !0,
  enablePasteRules: !0,
  enableCoreExtensions: !1
};
class Qf extends Zf {
  constructor(e) {
    var t, r, i, o, s, l, a, c, d, u, h, f, p, m, g, y;
    super(), E(this, "pmSchema"), E(this, "extensions", {}), E(this, "headless", !1), E(this, "_tiptapEditor"), E(this, "elementRenderer", null), E(this, "blockCache", /* @__PURE__ */ new WeakMap()), E(this, "dictionary"), E(this, "schema"), E(this, "blockImplementations"), E(this, "inlineContentImplementations"), E(this, "styleImplementations"), E(this, "formattingToolbar"), E(this, "linkToolbar"), E(this, "sideMenu"), E(this, "suggestionMenus"), E(this, "filePanel"), E(this, "tableHandles"), E(this, "comments"), E(this, "showSelectionPlugin"), E(this, "forkYDocPlugin"), E(this, "uploadFile"), E(this, "onUploadStartCallbacks", []), E(this, "onUploadEndCallbacks", []), E(this, "resolveFileUrl"), E(this, "resolveUsers"), E(this, "settings"), E(this, "activeTransaction", null), E(this, "mount", (S, D) => {
      this._tiptapEditor.mount(this, S, D);
    }), this.options = e;
    const _ = e;
    if (_.onEditorContentChange)
      throw new Error(
        "onEditorContentChange initialization option is deprecated, use <BlockNoteView onChange={...} />, the useEditorChange(...) hook, or editor.onChange(...)"
      );
    if (_.onTextCursorPositionChange)
      throw new Error(
        "onTextCursorPositionChange initialization option is deprecated, use <BlockNoteView onSelectionChange={...} />, the useEditorSelectionChange(...) hook, or editor.onSelectionChange(...)"
      );
    if (_.onEditorReady)
      throw new Error(
        "onEditorReady is deprecated. Editor is immediately ready for use after creation."
      );
    if (_.editable)
      throw new Error(
        "editable initialization option is deprecated, use <BlockNoteView editable={true/false} />, or alternatively editor.isEditable = true/false"
      );
    this.dictionary = e.dictionary || OI, this.settings = {
      tables: {
        splitCells: ((t = e == null ? void 0 : e.tables) == null ? void 0 : t.splitCells) ?? !1,
        cellBackgroundColor: ((r = e == null ? void 0 : e.tables) == null ? void 0 : r.cellBackgroundColor) ?? !1,
        cellTextColor: ((i = e == null ? void 0 : e.tables) == null ? void 0 : i.cellTextColor) ?? !1,
        headers: ((o = e == null ? void 0 : e.tables) == null ? void 0 : o.headers) ?? !1
      },
      codeBlock: {
        indentLineWithTab: ((s = e == null ? void 0 : e.codeBlock) == null ? void 0 : s.indentLineWithTab) ?? !0,
        defaultLanguage: ((l = e == null ? void 0 : e.codeBlock) == null ? void 0 : l.defaultLanguage) ?? "text",
        supportedLanguages: ((a = e == null ? void 0 : e.codeBlock) == null ? void 0 : a.supportedLanguages) ?? {},
        createHighlighter: ((c = e == null ? void 0 : e.codeBlock) == null ? void 0 : c.createHighlighter) ?? void 0
      },
      heading: {
        levels: ((d = e == null ? void 0 : e.heading) == null ? void 0 : d.levels) ?? [1, 2, 3]
      }
    };
    const b = {
      defaultStyles: !0,
      schema: e.schema || Vc.create(),
      _headless: !1,
      ...e,
      placeholders: {
        ...this.dictionary.placeholders,
        ...e.placeholders
      }
    };
    if (b.comments && !b.resolveUsers)
      throw new Error("resolveUsers is required when using comments");
    this.resolveUsers = b.resolveUsers, this.schema = b.schema, this.blockImplementations = b.schema.blockSpecs, this.inlineContentImplementations = b.schema.inlineContentSpecs, this.styleImplementations = b.schema.styleSpecs, this.extensions = wP({
      editor: this,
      domAttributes: b.domAttributes || {},
      blockSpecs: this.schema.blockSpecs,
      styleSpecs: this.schema.styleSpecs,
      inlineContentSpecs: this.schema.inlineContentSpecs,
      collaboration: b.collaboration,
      trailingBlock: b.trailingBlock,
      disableExtensions: b.disableExtensions,
      setIdAttribute: b.setIdAttribute,
      animations: b.animations ?? !0,
      tableHandles: fk("table", this),
      dropCursor: this.options.dropCursor ?? TI,
      placeholders: b.placeholders,
      tabBehavior: b.tabBehavior,
      comments: b.comments,
      pasteHandler: b.pasteHandler
    }), (((u = b._tiptapOptions) == null ? void 0 : u.extensions) || []).forEach((S) => {
      this.extensions[S.name] = S;
    });
    for (let S of b.extensions || []) {
      typeof S == "function" && (S = S(this));
      const D = S.constructor.key();
      if (!D)
        throw new Error(
          `Extension ${S.constructor.name} does not have a key method`
        );
      if (this.extensions[D])
        throw new Error(
          `Extension ${S.constructor.name} already exists with key ${D}`
        );
      this.extensions[D] = S;
    }
    if (Object.entries(b._extensions || {}).forEach(([S, D]) => {
      const T = typeof D == "function" ? D(this) : D;
      if (!("plugin" in T)) {
        this.extensions[S] = T;
        return;
      }
      this.extensions[S] = new class extends Ve {
        static key() {
          return S;
        }
        constructor() {
          super(), this.addProsemirrorPlugin(T.plugin);
        }
        get priority() {
          return T.priority;
        }
      }();
    }), this.formattingToolbar = this.extensions.formattingToolbar, this.linkToolbar = this.extensions.linkToolbar, this.sideMenu = this.extensions.sideMenu, this.suggestionMenus = this.extensions.suggestionMenus, this.filePanel = this.extensions.filePanel, this.tableHandles = this.extensions.tableHandles, this.comments = this.extensions.comments, this.showSelectionPlugin = this.extensions.showSelection, this.forkYDocPlugin = this.extensions.forkYDocPlugin, b.uploadFile) {
      const S = b.uploadFile;
      this.uploadFile = async (D, T) => {
        this.onUploadStartCallbacks.forEach(
          (I) => I.apply(this, [T])
        );
        try {
          return await S(D, T);
        } finally {
          this.onUploadEndCallbacks.forEach(
            (I) => I.apply(this, [T])
          );
        }
      };
    }
    this.resolveFileUrl = b.resolveFileUrl, this.headless = b._headless;
    const k = "ySyncPlugin" in this.extensions || "liveblocksExtension" in this.extensions;
    k && b.initialContent && console.warn(
      "When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider"
    );
    const C = b.initialContent || (k ? [
      {
        type: "paragraph",
        id: "initialBlockId"
      }
    ] : [
      {
        type: "paragraph",
        id: Nc.options.generateID()
      }
    ]);
    if (!Array.isArray(C) || C.length === 0)
      throw new Error(
        "initialContent must be a non-empty array of blocks, received: " + C
      );
    const w = [
      ...Object.entries(this.extensions).map(([S, D]) => {
        if (D instanceof he || D instanceof Mt || D instanceof Je)
          return D;
        if (!(D instanceof Ve && !D.plugins.length))
          return he.create({
            name: S,
            priority: D.priority,
            addProseMirrorPlugins: () => D.plugins
          });
      })
    ].filter((S) => S !== void 0), x = {
      ...xP,
      ...b._tiptapOptions,
      content: C,
      extensions: w,
      editorProps: {
        ...(h = b._tiptapOptions) == null ? void 0 : h.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",
          ...(p = (f = b._tiptapOptions) == null ? void 0 : f.editorProps) == null ? void 0 : p.attributes,
          ...(m = b.domAttributes) == null ? void 0 : m.editor,
          class: Rr(
            "bn-editor",
            b.defaultStyles ? "bn-default-styles" : "",
            ((y = (g = b.domAttributes) == null ? void 0 : g.editor) == null ? void 0 : y.class) || ""
          )
        },
        transformPasted: SP
      }
    };
    this.headless ? this.pmSchema = fM(x.extensions) : (this._tiptapEditor = Fk.create(
      x,
      this.schema.styleSchema
    ), this.pmSchema = this._tiptapEditor.schema), this.pmSchema.cached.blockNoteEditor = this, this.emit("create");
  }
  static create(e = {}) {
    return new Qf(e);
  }
  /**
   * 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(e) {
    if (this.activeTransaction)
      throw new Error(
        "`exec` should not be called within a `transact` call, move the `exec` call outside of the `transact` call"
      );
    const t = this._tiptapEditor.state, r = this._tiptapEditor.view;
    return e(t, (i) => this._tiptapEditor.dispatch(i), r);
  }
  /**
   * 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(e) {
    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 t = this._tiptapEditor.state, r = this._tiptapEditor.view;
    return e(t, void 0, r);
  }
  /**
   * 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(e) {
    if (this.activeTransaction)
      return e(this.activeTransaction);
    try {
      this.activeTransaction = this._tiptapEditor.state.tr;
      const t = e(this.activeTransaction), r = this.activeTransaction;
      return this.activeTransaction = null, r && // Only dispatch if the transaction was actually modified in some way
      (r.docChanged || r.selectionSet || r.scrolledIntoView || r.storedMarksSet || !r.isGeneric) && this._tiptapEditor.dispatch(r), t;
    } finally {
      this.activeTransaction = null;
    }
  }
  // TO DISCUSS
  /**
   * Shorthand to get a typed extension from the editor, by
   * just passing in the extension class.
   *
   * @param ext - The extension class to get
   * @param key - optional, the key of the extension in the extensions object (defaults to the extension name)
   * @returns The extension instance
   */
  extension(e, t = e.key()) {
    const r = this.extensions[t];
    if (!r)
      throw new Error(`Extension ${t} not found`);
    return r;
  }
  /**
   * 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._tiptapEditor.state;
  }
  /**
   * Get the underlying prosemirror view
   * @see https://prosemirror.net/docs/ref/#view.EditorView
   */
  get prosemirrorView() {
    return this._tiptapEditor.view;
  }
  get domElement() {
    var e;
    return (e = this.prosemirrorView) == null ? void 0 : e.dom;
  }
  isFocused() {
    var e;
    return ((e = this.prosemirrorView) == null ? void 0 : e.hasFocus()) || !1;
  }
  focus() {
    var e;
    (e = this.prosemirrorView) == null || e.focus();
  }
  onUploadStart(e) {
    return this.onUploadStartCallbacks.push(e), () => {
      const t = this.onUploadStartCallbacks.indexOf(e);
      t > -1 && this.onUploadStartCallbacks.splice(t, 1);
    };
  }
  onUploadEnd(e) {
    return this.onUploadEndCallbacks.push(e), () => {
      const t = this.onUploadEndCallbacks.indexOf(e);
      t > -1 && this.onUploadEndCallbacks.splice(t, 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.transact((e) => zI(e.doc, this.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(e) {
    return this.transact((t) => NR(t.doc, e));
  }
  /**
   * 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(e) {
    return this.transact((t) => $R(t.doc, e));
  }
  /**
   * 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(e) {
    return this.transact((t) => IR(t.doc, e));
  }
  /**
   * 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(e) {
    return this.transact((t) => LR(t.doc, e));
  }
  /**
   * 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(e, t = !1) {
    const r = this.document.slice();
    t && r.reverse();
    function i(o) {
      for (const s of o) {
        if (e(s) === !1)
          return !1;
        const l = t ? s.children.slice().reverse() : s.children;
        if (!i(l))
          return !1;
      }
      return !0;
    }
    i(r);
  }
  /**
   * Executes a callback whenever the editor's contents change.
   * @param callback The callback to execute.
   *
   * @deprecated use {@link BlockNoteEditor.onChange} instead
   */
  onEditorContentChange(e) {
    this._tiptapEditor.on("update", e);
  }
  /**
   * Executes a callback whenever the editor's selection changes.
   * @param callback The callback to execute.
   *
   * @deprecated use `onSelectionChange` instead
   */
  onEditorSelectionChange(e) {
    this._tiptapEditor.on("selectionUpdate", e);
  }
  /**
   * Gets a snapshot of the current text cursor position.
   * @returns A snapshot of the current text cursor position.
   */
  getTextCursorPosition() {
    return this.transact((e) => HR(e));
  }
  /**
   * 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(e, t = "start") {
    return this.transact(
      (r) => _k(r, e, t)
    );
  }
  /**
   * 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.transact((e) => BR(e));
  }
  /**
   * 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() {
    return this.transact((e) => zR(e));
  }
  /**
   * 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(e, t) {
    return this.transact((r) => PR(r, e, t));
  }
  /**
   * 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._tiptapEditor) {
      if (!this.headless)
        throw new Error("no editor, but also not headless?");
      return !1;
    }
    return this._tiptapEditor.isEditable === void 0 ? !0 : this._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(e) {
    if (!this._tiptapEditor) {
      if (!this.headless)
        throw new Error("no editor, but also not headless?");
      return;
    }
    this._tiptapEditor.options.editable !== e && this._tiptapEditor.setEditable(e);
  }
  /**
   * 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(e, t, r = "before") {
    return this.transact(
      (i) => ZI(i, e, t, r)
    );
  }
  /**
   * 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(e, t) {
    return this.transact((r) => eL(r, e, t));
  }
  /**
   * 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(e) {
    return this.transact(
      (t) => H0(t, e, []).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(e, t) {
    return this.transact(
      (r) => H0(r, e, t)
    );
  }
  /**
   * Undo the last action.
   */
  undo() {
    return this.options.collaboration ? this.exec(SI) : this.exec(sf);
  }
  /**
   * Redo the last action.
   */
  redo() {
    return this.options.collaboration ? this.exec(EI) : this.exec(lf);
  }
  /**
   * Insert a piece of content at the current cursor position.
   *
   * @param content can be a string, or array of partial inline content elements
   */
  insertInlineContent(e, { updateSelection: t = !1 } = {}) {
    const r = mn(e, this.pmSchema);
    this.transact((i) => {
      RR(
        i,
        {
          from: i.selection.from,
          to: i.selection.to
        },
        r,
        {
          updateSelection: t
        }
      );
    });
  }
  /**
   * 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.transact((e) => {
      const t = {}, r = e.selection.$to.marks();
      for (const i of r) {
        const o = this.schema.styleSchema[i.type.name];
        if (!o) {
          i.type.name !== "link" && // "blocknoteIgnore" tagged marks (such as comments) are also not considered BlockNote "styles"
          !i.type.spec.blocknoteIgnore && console.warn("mark not found in styleschema", i.type.name);
          continue;
        }
        o.propSchema === "boolean" ? t[o.type] = !0 : t[o.type] = i.attrs.stringValue;
      }
      return t;
    });
  }
  /**
   * Adds styles to the currently selected content.
   * @param styles The styles to add.
   */
  addStyles(e) {
    for (const [t, r] of Object.entries(e)) {
      const i = this.schema.styleSchema[t];
      if (!i)
        throw new Error(`style ${t} not found in styleSchema`);
      if (i.propSchema === "boolean")
        this._tiptapEditor.commands.setMark(t);
      else if (i.propSchema === "string")
        this._tiptapEditor.commands.setMark(t, { stringValue: r });
      else
        throw new In(i.propSchema);
    }
  }
  /**
   * Removes styles from the currently selected content.
   * @param styles The styles to remove.
   */
  removeStyles(e) {
    for (const t of Object.keys(e))
      this._tiptapEditor.commands.unsetMark(t);
  }
  /**
   * Toggles styles on the currently selected content.
   * @param styles The styles to toggle.
   */
  toggleStyles(e) {
    for (const [t, r] of Object.entries(e)) {
      const i = this.schema.styleSchema[t];
      if (!i)
        throw new Error(`style ${t} not found in styleSchema`);
      if (i.propSchema === "boolean")
        this._tiptapEditor.commands.toggleMark(t);
      else if (i.propSchema === "string")
        this._tiptapEditor.commands.toggleMark(t, { stringValue: r });
      else
        throw new In(i.propSchema);
    }
  }
  /**
   * Gets the currently selected text.
   */
  getSelectedText() {
    return this.transact((e) => e.doc.textBetween(e.selection.from, e.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._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(e, t) {
    if (e === "")
      return;
    const r = this.pmSchema.mark("link", { href: e });
    this.transact((i) => {
      const { from: o, to: s } = i.selection;
      t ? i.insertText(t, o, s).addMark(o, o + t.length, r) : i.setSelection(L.create(i.doc, s)).addMark(
        o,
        s,
        r
      );
    });
  }
  /**
   * Checks if the block containing the text cursor can be nested.
   */
  canNestBlock() {
    return OR(this);
  }
  /**
   * Nests the block containing the text cursor into the block above it.
   */
  nestBlock() {
    yk(this);
  }
  /**
   * Checks if the block containing the text cursor is nested.
   */
  canUnnestBlock() {
    return FR(this);
  }
  /**
   * Lifts the block containing the text cursor out of its parent.
   */
  unnestBlock() {
    MR(this);
  }
  /**
   * 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 DR(this);
  }
  /**
   * 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 AR(this);
  }
  /**
   * 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.
   */
  async blocksToHTMLLossy(e = this.document) {
    return Bc(this.pmSchema, this).exportBlocks(e, {});
  }
  /**
   * 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.
   */
  async blocksToFullHTML(e) {
    return oL(this.pmSchema, this).serializeBlocks(e, {});
  }
  /**
   * 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.
   */
  async tryParseHTMLToBlocks(e) {
    return kk(e, this.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.
   */
  async blocksToMarkdownLossy(e = this.document) {
    return qR(e, this.pmSchema, this, {});
  }
  /**
   * 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.
   */
  async tryParseMarkdownToBlocks(e) {
    return XR(e, this.pmSchema);
  }
  /**
   * Updates the user info for the current user that's shown to other collaborators.
   */
  updateCollaborationUserInfo(e) {
    if (!this.options.collaboration)
      throw new Error(
        "Cannot update collaboration user info when collaboration is disabled."
      );
    this.extensions.yCursorPlugin.updateUser(e);
  }
  /**
   * Registers a callback which will be called before any change is applied to the editor, allowing you to cancel the change.
   */
  onBeforeChange(e) {
    return this.headless ? () => {
    } : this.extensions.blockChange.subscribe(
      (t) => e(this, t)
    );
  }
  /**
   * 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(e) {
    if (this.headless)
      return;
    const t = ({
      transaction: r,
      appendedTransactions: i
    }) => {
      e(this, {
        getChanges: () => Y1(r, i)
      });
    };
    return this._tiptapEditor.on("v3-update", t), () => {
      this._tiptapEditor.off("v3-update", t);
    };
  }
  /**
   * 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(e, t) {
    if (this.headless)
      return;
    const r = (i) => {
      i.transaction.getMeta(ne) && !t || e(this);
    };
    return this._tiptapEditor.on("selectionUpdate", r), () => {
      this._tiptapEditor.off("selectionUpdate", r);
    };
  }
  /**
   * A callback function that runs when the editor has been initialized.
   *
   * This can be useful for plugins to initialize themselves after the editor has been initialized.
   */
  onCreate(e) {
    return this.on("create", e), () => {
      this.off("create", e);
    };
  }
  getSelectionBoundingBox() {
    if (!this.prosemirrorView)
      return;
    const { selection: e } = this.prosemirrorState, { ranges: t } = e, r = Math.min(...t.map((o) => o.$from.pos)), i = Math.max(...t.map((o) => o.$to.pos));
    if ($u(e)) {
      const o = this.prosemirrorView.nodeDOM(r);
      if (o)
        return o.getBoundingClientRect();
    }
    return Sa(this.prosemirrorView, r, i);
  }
  get isEmpty() {
    const e = this.document;
    return e.length === 0 || e.length === 1 && e[0].type === "paragraph" && e[0].content.length === 0;
  }
  openSuggestionMenu(e, t) {
    this.prosemirrorView && (this.focus(), this.transact((r) => {
      t != null && t.deleteTriggerCharacter && r.insertText(e), r.scrollIntoView().setMeta(this.suggestionMenus.plugins[0], {
        triggerCharacter: e,
        deleteTriggerCharacter: (t == null ? void 0 : t.deleteTriggerCharacter) || !1,
        ignoreQueryLength: (t == null ? void 0 : t.ignoreQueryLength) || !1
      });
    }));
  }
  // `forceSelectionVisible` determines whether the editor selection is shows
  // even when the editor is not focused. This is useful for e.g. creating new
  // links, so the user still sees the affected content when an input field is
  // focused.
  // TODO: Reconsider naming?
  getForceSelectionVisible() {
    return this.showSelectionPlugin.getEnabled();
  }
  setForceSelectionVisible(e) {
    this.showSelectionPlugin.setEnabled(e);
  }
  /**
   * This will convert HTML into a format that is compatible with BlockNote.
   */
  convertHtmlToBlockNoteHtml(e) {
    return wk(e.trim()).innerHTML;
  }
  /**
   * 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(e, t = !1) {
    var r;
    let i = e;
    t || (i = this.convertHtmlToBlockNoteHtml(e)), i && ((r = this.prosemirrorView) == null || r.pasteHTML(i));
  }
  /**
   * Paste text into the editor. Defaults to interpreting text as markdown.
   * @param text The text to paste.
   */
  pasteText(e) {
    var t;
    return (t = this.prosemirrorView) == null ? void 0 : t.pasteText(e);
  }
  /**
   * Paste markdown into the editor.
   * @param markdown The markdown to paste.
   */
  async pasteMarkdown(e) {
    return this.pasteHTML(await vk(e));
  }
}
const {
  SvelteComponent: DP,
  append_hydration: ab,
  assign: AP,
  attr: zl,
  binding_callbacks: TP,
  check_outros: MP,
  children: cb,
  claim_component: ep,
  claim_element: db,
  claim_space: ub,
  claim_text: OP,
  create_component: tp,
  destroy_component: np,
  detach: qo,
  element: hb,
  flush: Rt,
  get_spread_object: FP,
  get_spread_update: NP,
  group_outros: $P,
  init: IP,
  insert_hydration: wh,
  mount_component: rp,
  safe_not_equal: LP,
  set_data: RP,
  space: fb,
  text: BP,
  transition_in: Gi,
  transition_out: cs
} = window.__gradio__svelte__internal, { onMount: PP, onDestroy: zP } = window.__gradio__svelte__internal;
function pb(n) {
  let e, t;
  const r = [
    { autoscroll: (
      /*gradio*/
      n[0].autoscroll
    ) },
    { i18n: (
      /*gradio*/
      n[0].i18n
    ) },
    /*loading_status*/
    n[8]
  ];
  let i = {};
  for (let o = 0; o < r.length; o += 1)
    i = AP(i, r[o]);
  return e = new BE({ props: i }), e.$on(
    "clear_status",
    /*clear_status_handler*/
    n[14]
  ), {
    c() {
      tp(e.$$.fragment);
    },
    l(o) {
      ep(e.$$.fragment, o);
    },
    m(o, s) {
      rp(e, o, s), t = !0;
    },
    p(o, s) {
      const l = s & /*gradio, loading_status*/
      257 ? NP(r, [
        s & /*gradio*/
        1 && { autoscroll: (
          /*gradio*/
          o[0].autoscroll
        ) },
        s & /*gradio*/
        1 && { i18n: (
          /*gradio*/
          o[0].i18n
        ) },
        s & /*loading_status*/
        256 && FP(
          /*loading_status*/
          o[8]
        )
      ]) : {};
      e.$set(l);
    },
    i(o) {
      t || (Gi(e.$$.fragment, o), t = !0);
    },
    o(o) {
      cs(e.$$.fragment, o), t = !1;
    },
    d(o) {
      np(e, o);
    }
  };
}
function HP(n) {
  let e;
  return {
    c() {
      e = BP(
        /*label*/
        n[1]
      );
    },
    l(t) {
      e = OP(
        t,
        /*label*/
        n[1]
      );
    },
    m(t, r) {
      wh(t, e, r);
    },
    p(t, r) {
      r & /*label*/
      2 && RP(
        e,
        /*label*/
        t[1]
      );
    },
    d(t) {
      t && qo(e);
    }
  };
}
function VP(n) {
  let e, t, r, i, o, s, l, a = (
    /*loading_status*/
    n[8] && pb(n)
  );
  return r = new OS({
    props: {
      show_label: (
        /*show_label*/
        n[5]
      ),
      info: void 0,
      $$slots: { default: [HP] },
      $$scope: { ctx: n }
    }
  }), {
    c() {
      a && a.c(), e = fb(), t = hb("div"), tp(r.$$.fragment), i = fb(), o = hb("div"), this.h();
    },
    l(c) {
      a && a.l(c), e = ub(c), t = db(c, "DIV", { class: !0 });
      var d = cb(t);
      ep(r.$$.fragment, d), i = ub(d), o = db(d, "DIV", { class: !0, "data-disabled": !0 }), cb(o).forEach(qo), d.forEach(qo), this.h();
    },
    h() {
      zl(o, "class", "editor svelte-1mygn1t"), zl(o, "data-disabled", s = !/*interactive*/
      n[9]), zl(t, "class", "container svelte-1mygn1t");
    },
    m(c, d) {
      a && a.m(c, d), wh(c, e, d), wh(c, t, d), rp(r, t, null), ab(t, i), ab(t, o), n[15](o), l = !0;
    },
    p(c, d) {
      /*loading_status*/
      c[8] ? a ? (a.p(c, d), d & /*loading_status*/
      256 && Gi(a, 1)) : (a = pb(c), a.c(), Gi(a, 1), a.m(e.parentNode, e)) : a && ($P(), cs(a, 1, 1, () => {
        a = null;
      }), MP());
      const u = {};
      d & /*show_label*/
      32 && (u.show_label = /*show_label*/
      c[5]), d & /*$$scope, label*/
      524290 && (u.$$scope = { dirty: d, ctx: c }), r.$set(u), (!l || d & /*interactive*/
      512 && s !== (s = !/*interactive*/
      c[9])) && zl(o, "data-disabled", s);
    },
    i(c) {
      l || (Gi(a), Gi(r.$$.fragment, c), l = !0);
    },
    o(c) {
      cs(a), cs(r.$$.fragment, c), l = !1;
    },
    d(c) {
      c && (qo(e), qo(t)), a && a.d(c), np(r), n[15](null);
    }
  };
}
function UP(n) {
  let e, t;
  return e = new ov({
    props: {
      visible: (
        /*visible*/
        n[4]
      ),
      elem_id: (
        /*elem_id*/
        n[2]
      ),
      elem_classes: (
        /*elem_classes*/
        n[3]
      ),
      scale: (
        /*scale*/
        n[6]
      ),
      min_width: (
        /*min_width*/
        n[7]
      ),
      allow_overflow: !1,
      padding: !0,
      $$slots: { default: [VP] },
      $$scope: { ctx: n }
    }
  }), {
    c() {
      tp(e.$$.fragment);
    },
    l(r) {
      ep(e.$$.fragment, r);
    },
    m(r, i) {
      rp(e, r, i), t = !0;
    },
    p(r, [i]) {
      const o = {};
      i & /*visible*/
      16 && (o.visible = /*visible*/
      r[4]), i & /*elem_id*/
      4 && (o.elem_id = /*elem_id*/
      r[2]), i & /*elem_classes*/
      8 && (o.elem_classes = /*elem_classes*/
      r[3]), i & /*scale*/
      64 && (o.scale = /*scale*/
      r[6]), i & /*min_width*/
      128 && (o.min_width = /*min_width*/
      r[7]), i & /*$$scope, interactive, element, show_label, label, gradio, loading_status*/
      526115 && (o.$$scope = { dirty: i, ctx: r }), e.$set(o);
    },
    i(r) {
      t || (Gi(e.$$.fragment, r), t = !0);
    },
    o(r) {
      cs(e.$$.fragment, r), t = !1;
    },
    d(r) {
      np(e, r);
    }
  };
}
function qP(n, e, t) {
  var r = this && this.__awaiter || function(w, x, S, D) {
    function T(I) {
      return I instanceof S ? I : new S(function(U) {
        U(I);
      });
    }
    return new (S || (S = Promise))(function(I, U) {
      function Te(K) {
        try {
          fe(D.next(K));
        } catch (be) {
          U(be);
        }
      }
      function ce(K) {
        try {
          fe(D.throw(K));
        } catch (be) {
          U(be);
        }
      }
      function fe(K) {
        K.done ? I(K.value) : T(K.value).then(Te, ce);
      }
      fe((D = D.apply(w, x || [])).next());
    });
  };
  let { gradio: i } = e, { label: o = "Rich Text Editor" } = e, { elem_id: s = "" } = e, { elem_classes: l = [] } = e, { visible: a = !0 } = e, { value: c = "" } = e, { show_label: d } = e, { scale: u = null } = e, { min_width: h = void 0 } = e, { loading_status: f = void 0 } = e, { value_is_output: p = !1 } = e, { interactive: m } = e, g, y;
  function _(w) {
    if ((w.metaKey || w.ctrlKey) && w.key === "k") {
      w.preventDefault();
      const x = y.getSelectedText(), S = y.getSelectedLinkUrl(), D = prompt("Enter URL:", S || "https://");
      if (D && D.trim()) {
        let T = D.trim();
        /^https?:\/\//i.test(T) || (T = "https://" + T), y.createLink(T, x || void 0);
      }
      y.focus();
    }
  }
  PP(() => {
    t(13, y = Qf.create({
      uploadFile: (w) => r(void 0, void 0, void 0, function* () {
        return new Promise((x) => {
          const S = new FileReader();
          S.onload = () => {
            x(S.result);
          }, S.readAsDataURL(w);
        });
      }),
      placeholders: {
        default: "",
        emptyDocument: "Write something...",
        bulletListItem: "",
        numberedListItem: "",
        checkListItem: "",
        toggleListItem: ""
      }
    })), y.mount(g), g.addEventListener("keydown", _), y.onChange(() => r(void 0, void 0, void 0, function* () {
      t(11, c = yield y.blocksToMarkdownLossy(y.document)), console.log("Editor onChange - value:", c), i.dispatch("change"), p || i.dispatch("input");
    }));
  }), zP(() => {
    g && g.removeEventListener("keydown", _);
  });
  function b() {
    return r(this, void 0, void 0, function* () {
      if (!y) return;
      if ((yield y.blocksToMarkdownLossy(y.document)) !== c) {
        const x = yield y.tryParseMarkdownToBlocks(c || "");
        y.replaceBlocks(y.document, x);
      }
    });
  }
  const k = () => i.dispatch("clear_status", f);
  function C(w) {
    TP[w ? "unshift" : "push"](() => {
      g = w, t(10, g);
    });
  }
  return n.$$set = (w) => {
    "gradio" in w && t(0, i = w.gradio), "label" in w && t(1, o = w.label), "elem_id" in w && t(2, s = w.elem_id), "elem_classes" in w && t(3, l = w.elem_classes), "visible" in w && t(4, a = w.visible), "value" in w && t(11, c = w.value), "show_label" in w && t(5, d = w.show_label), "scale" in w && t(6, u = w.scale), "min_width" in w && t(7, h = w.min_width), "loading_status" in w && t(8, f = w.loading_status), "value_is_output" in w && t(12, p = w.value_is_output), "interactive" in w && t(9, m = w.interactive);
  }, n.$$.update = () => {
    n.$$.dirty & /*editor, interactive*/
    8704 && y && t(13, y.isEditable = m, y), n.$$.dirty & /*value*/
    2048 && c === null && t(11, c = ""), n.$$.dirty & /*editor, value*/
    10240 && y && c !== void 0 && b();
  }, [
    i,
    o,
    s,
    l,
    a,
    d,
    u,
    h,
    f,
    m,
    g,
    c,
    p,
    y,
    k,
    C
  ];
}
class bZ extends DP {
  constructor(e) {
    super(), IP(this, e, qP, UP, LP, {
      gradio: 0,
      label: 1,
      elem_id: 2,
      elem_classes: 3,
      visible: 4,
      value: 11,
      show_label: 5,
      scale: 6,
      min_width: 7,
      loading_status: 8,
      value_is_output: 12,
      interactive: 9
    });
  }
  get gradio() {
    return this.$$.ctx[0];
  }
  set gradio(e) {
    this.$$set({ gradio: e }), Rt();
  }
  get label() {
    return this.$$.ctx[1];
  }
  set label(e) {
    this.$$set({ label: e }), Rt();
  }
  get elem_id() {
    return this.$$.ctx[2];
  }
  set elem_id(e) {
    this.$$set({ elem_id: e }), Rt();
  }
  get elem_classes() {
    return this.$$.ctx[3];
  }
  set elem_classes(e) {
    this.$$set({ elem_classes: e }), Rt();
  }
  get visible() {
    return this.$$.ctx[4];
  }
  set visible(e) {
    this.$$set({ visible: e }), Rt();
  }
  get value() {
    return this.$$.ctx[11];
  }
  set value(e) {
    this.$$set({ value: e }), Rt();
  }
  get show_label() {
    return this.$$.ctx[5];
  }
  set show_label(e) {
    this.$$set({ show_label: e }), Rt();
  }
  get scale() {
    return this.$$.ctx[6];
  }
  set scale(e) {
    this.$$set({ scale: e }), Rt();
  }
  get min_width() {
    return this.$$.ctx[7];
  }
  set min_width(e) {
    this.$$set({ min_width: e }), Rt();
  }
  get loading_status() {
    return this.$$.ctx[8];
  }
  set loading_status(e) {
    this.$$set({ loading_status: e }), Rt();
  }
  get value_is_output() {
    return this.$$.ctx[12];
  }
  set value_is_output(e) {
    this.$$set({ value_is_output: e }), Rt();
  }
  get interactive() {
    return this.$$.ctx[9];
  }
  set interactive(e) {
    this.$$set({ interactive: e }), Rt();
  }
}
export {
  bZ as I,
  Rp as c,
  WP as g,
  jY as p
};
