var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var require_assets = __commonJS({
  "assets/index.js"(exports) {
    (function polyfill() {
      const relList = document.createElement("link").relList;
      if (relList && relList.supports && relList.supports("modulepreload")) {
        return;
      }
      for (const link2 of document.querySelectorAll('link[rel="modulepreload"]')) {
        processPreload(link2);
      }
      new MutationObserver((mutations) => {
        for (const mutation of mutations) {
          if (mutation.type !== "childList") {
            continue;
          }
          for (const node2 of mutation.addedNodes) {
            if (node2.tagName === "LINK" && node2.rel === "modulepreload")
              processPreload(node2);
          }
        }
      }).observe(document, { childList: true, subtree: true });
      function getFetchOpts(link2) {
        const fetchOpts = {};
        if (link2.integrity) fetchOpts.integrity = link2.integrity;
        if (link2.referrerPolicy) fetchOpts.referrerPolicy = link2.referrerPolicy;
        if (link2.crossOrigin === "use-credentials")
          fetchOpts.credentials = "include";
        else if (link2.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
        else fetchOpts.credentials = "same-origin";
        return fetchOpts;
      }
      function processPreload(link2) {
        if (link2.ep)
          return;
        link2.ep = true;
        const fetchOpts = getFetchOpts(link2);
        fetch(link2.href, fetchOpts);
      }
    })();
    var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    function getDefaultExportFromCjs(x2) {
      return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
    }
    var jsxRuntime = { exports: {} };
    var reactJsxRuntime_production = {};
    /**
     * @license React
     * react-jsx-runtime.production.js
     *
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    var REACT_ELEMENT_TYPE$2 = Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE$2 = Symbol.for("react.fragment");
    function jsxProd(type, config2, maybeKey) {
      var key2 = null;
      void 0 !== maybeKey && (key2 = "" + maybeKey);
      void 0 !== config2.key && (key2 = "" + config2.key);
      if ("key" in config2) {
        maybeKey = {};
        for (var propName in config2)
          "key" !== propName && (maybeKey[propName] = config2[propName]);
      } else maybeKey = config2;
      config2 = maybeKey.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE$2,
        type,
        key: key2,
        ref: void 0 !== config2 ? config2 : null,
        props: maybeKey
      };
    }
    reactJsxRuntime_production.Fragment = REACT_FRAGMENT_TYPE$2;
    reactJsxRuntime_production.jsx = jsxProd;
    reactJsxRuntime_production.jsxs = jsxProd;
    {
      jsxRuntime.exports = reactJsxRuntime_production;
    }
    var jsxRuntimeExports = jsxRuntime.exports;
    var client = { exports: {} };
    var reactDomClient_production = {};
    var scheduler = { exports: {} };
    var scheduler_production = {};
    /**
     * @license React
     * scheduler.production.js
     *
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    (function(exports2) {
      function push2(heap2, node2) {
        var index2 = heap2.length;
        heap2.push(node2);
        a: for (; 0 < index2; ) {
          var parentIndex = index2 - 1 >>> 1, parent = heap2[parentIndex];
          if (0 < compare2(parent, node2))
            heap2[parentIndex] = node2, heap2[index2] = parent, index2 = parentIndex;
          else break a;
        }
      }
      function peek2(heap2) {
        return 0 === heap2.length ? null : heap2[0];
      }
      function pop2(heap2) {
        if (0 === heap2.length) return null;
        var first2 = heap2[0], last = heap2.pop();
        if (last !== first2) {
          heap2[0] = last;
          a: for (var index2 = 0, length = heap2.length, halfLength = length >>> 1; index2 < halfLength; ) {
            var leftIndex = 2 * (index2 + 1) - 1, left = heap2[leftIndex], rightIndex = leftIndex + 1, right = heap2[rightIndex];
            if (0 > compare2(left, last))
              rightIndex < length && 0 > compare2(right, left) ? (heap2[index2] = right, heap2[rightIndex] = last, index2 = rightIndex) : (heap2[index2] = left, heap2[leftIndex] = last, index2 = leftIndex);
            else if (rightIndex < length && 0 > compare2(right, last))
              heap2[index2] = right, heap2[rightIndex] = last, index2 = rightIndex;
            else break a;
          }
        }
        return first2;
      }
      function compare2(a, b) {
        var diff2 = a.sortIndex - b.sortIndex;
        return 0 !== diff2 ? diff2 : a.id - b.id;
      }
      exports2.unstable_now = void 0;
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var localPerformance = performance;
        exports2.unstable_now = function() {
          return localPerformance.now();
        };
      } else {
        var localDate = Date, initialTime = localDate.now();
        exports2.unstable_now = function() {
          return localDate.now() - initialTime;
        };
      }
      var taskQueue = [], timerQueue = [], taskIdCounter = 1, currentTask = null, currentPriorityLevel = 3, isPerformingWork = false, isHostCallbackScheduled = false, isHostTimeoutScheduled = false, localSetTimeout = "function" === typeof setTimeout ? setTimeout : null, localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null, localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null;
      function advanceTimers(currentTime) {
        for (var timer = peek2(timerQueue); null !== timer; ) {
          if (null === timer.callback) pop2(timerQueue);
          else if (timer.startTime <= currentTime)
            pop2(timerQueue), timer.sortIndex = timer.expirationTime, push2(taskQueue, timer);
          else break;
          timer = peek2(timerQueue);
        }
      }
      function handleTimeout(currentTime) {
        isHostTimeoutScheduled = false;
        advanceTimers(currentTime);
        if (!isHostCallbackScheduled)
          if (null !== peek2(taskQueue))
            isHostCallbackScheduled = true, requestHostCallback();
          else {
            var firstTimer = peek2(timerQueue);
            null !== firstTimer && requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
          }
      }
      var isMessageLoopRunning = false, taskTimeoutID = -1, frameInterval = 5, startTime = -1;
      function shouldYieldToHost() {
        return exports2.unstable_now() - startTime < frameInterval ? false : true;
      }
      function performWorkUntilDeadline() {
        if (isMessageLoopRunning) {
          var currentTime = exports2.unstable_now();
          startTime = currentTime;
          var hasMoreWork = true;
          try {
            a: {
              isHostCallbackScheduled = false;
              isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
              isPerformingWork = true;
              var previousPriorityLevel = currentPriorityLevel;
              try {
                b: {
                  advanceTimers(currentTime);
                  for (currentTask = peek2(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
                    var callback = currentTask.callback;
                    if ("function" === typeof callback) {
                      currentTask.callback = null;
                      currentPriorityLevel = currentTask.priorityLevel;
                      var continuationCallback = callback(
                        currentTask.expirationTime <= currentTime
                      );
                      currentTime = exports2.unstable_now();
                      if ("function" === typeof continuationCallback) {
                        currentTask.callback = continuationCallback;
                        advanceTimers(currentTime);
                        hasMoreWork = true;
                        break b;
                      }
                      currentTask === peek2(taskQueue) && pop2(taskQueue);
                      advanceTimers(currentTime);
                    } else pop2(taskQueue);
                    currentTask = peek2(taskQueue);
                  }
                  if (null !== currentTask) hasMoreWork = true;
                  else {
                    var firstTimer = peek2(timerQueue);
                    null !== firstTimer && requestHostTimeout(
                      handleTimeout,
                      firstTimer.startTime - currentTime
                    );
                    hasMoreWork = false;
                  }
                }
                break a;
              } finally {
                currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
              }
              hasMoreWork = void 0;
            }
          } finally {
            hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
          }
        }
      }
      var schedulePerformWorkUntilDeadline;
      if ("function" === typeof localSetImmediate)
        schedulePerformWorkUntilDeadline = function() {
          localSetImmediate(performWorkUntilDeadline);
        };
      else if ("undefined" !== typeof MessageChannel) {
        var channel = new MessageChannel(), port = channel.port2;
        channel.port1.onmessage = performWorkUntilDeadline;
        schedulePerformWorkUntilDeadline = function() {
          port.postMessage(null);
        };
      } else
        schedulePerformWorkUntilDeadline = function() {
          localSetTimeout(performWorkUntilDeadline, 0);
        };
      function requestHostCallback() {
        isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
      }
      function requestHostTimeout(callback, ms) {
        taskTimeoutID = localSetTimeout(function() {
          callback(exports2.unstable_now());
        }, ms);
      }
      exports2.unstable_IdlePriority = 5;
      exports2.unstable_ImmediatePriority = 1;
      exports2.unstable_LowPriority = 4;
      exports2.unstable_NormalPriority = 3;
      exports2.unstable_Profiling = null;
      exports2.unstable_UserBlockingPriority = 2;
      exports2.unstable_cancelCallback = function(task2) {
        task2.callback = null;
      };
      exports2.unstable_continueExecution = function() {
        isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, requestHostCallback());
      };
      exports2.unstable_forceFrameRate = function(fps) {
        0 > fps || 125 < fps ? console.error(
          "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
        ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
      };
      exports2.unstable_getCurrentPriorityLevel = function() {
        return currentPriorityLevel;
      };
      exports2.unstable_getFirstCallbackNode = function() {
        return peek2(taskQueue);
      };
      exports2.unstable_next = function(eventHandler2) {
        switch (currentPriorityLevel) {
          case 1:
          case 2:
          case 3:
            var priorityLevel = 3;
            break;
          default:
            priorityLevel = currentPriorityLevel;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler2();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports2.unstable_pauseExecution = function() {
      };
      exports2.unstable_requestPaint = function() {
      };
      exports2.unstable_runWithPriority = function(priorityLevel, eventHandler2) {
        switch (priorityLevel) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
            break;
          default:
            priorityLevel = 3;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler2();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports2.unstable_scheduleCallback = function(priorityLevel, callback, options2) {
        var currentTime = exports2.unstable_now();
        "object" === typeof options2 && null !== options2 ? (options2 = options2.delay, options2 = "number" === typeof options2 && 0 < options2 ? currentTime + options2 : currentTime) : options2 = currentTime;
        switch (priorityLevel) {
          case 1:
            var timeout = -1;
            break;
          case 2:
            timeout = 250;
            break;
          case 5:
            timeout = 1073741823;
            break;
          case 4:
            timeout = 1e4;
            break;
          default:
            timeout = 5e3;
        }
        timeout = options2 + timeout;
        priorityLevel = {
          id: taskIdCounter++,
          callback,
          priorityLevel,
          startTime: options2,
          expirationTime: timeout,
          sortIndex: -1
        };
        options2 > currentTime ? (priorityLevel.sortIndex = options2, push2(timerQueue, priorityLevel), null === peek2(taskQueue) && priorityLevel === peek2(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options2 - currentTime))) : (priorityLevel.sortIndex = timeout, push2(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, requestHostCallback()));
        return priorityLevel;
      };
      exports2.unstable_shouldYield = shouldYieldToHost;
      exports2.unstable_wrapCallback = function(callback) {
        var parentPriorityLevel = currentPriorityLevel;
        return function() {
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = parentPriorityLevel;
          try {
            return callback.apply(this, arguments);
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        };
      };
    })(scheduler_production);
    {
      scheduler.exports = scheduler_production;
    }
    var schedulerExports = scheduler.exports;
    var react = { exports: {} };
    var react_production = {};
    /**
     * @license React
     * react.production.js
     *
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    var REACT_ELEMENT_TYPE$1 = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE$2 = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE$1 = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE$1 = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE$1 = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE$1 = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE$1 = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE$1 = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE$1 = Symbol.for("react.suspense"), REACT_MEMO_TYPE$1 = Symbol.for("react.memo"), REACT_LAZY_TYPE$1 = Symbol.for("react.lazy"), MAYBE_ITERATOR_SYMBOL$1 = Symbol.iterator;
    function getIteratorFn$1(maybeIterable) {
      if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
      maybeIterable = MAYBE_ITERATOR_SYMBOL$1 && maybeIterable[MAYBE_ITERATOR_SYMBOL$1] || maybeIterable["@@iterator"];
      return "function" === typeof maybeIterable ? maybeIterable : null;
    }
    var ReactNoopUpdateQueue = {
      isMounted: function() {
        return false;
      },
      enqueueForceUpdate: function() {
      },
      enqueueReplaceState: function() {
      },
      enqueueSetState: function() {
      }
    }, assign$3 = Object.assign, emptyObject = {};
    function Component(props, context, updater) {
      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }
    Component.prototype.isReactComponent = {};
    Component.prototype.setState = function(partialState, callback) {
      if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
        throw Error(
          "takes an object of state variables to update or a function which returns an object of state variables."
        );
      this.updater.enqueueSetState(this, partialState, callback, "setState");
    };
    Component.prototype.forceUpdate = function(callback) {
      this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
    };
    function ComponentDummy() {
    }
    ComponentDummy.prototype = Component.prototype;
    function PureComponent(props, context, updater) {
      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }
    var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
    pureComponentPrototype.constructor = PureComponent;
    assign$3(pureComponentPrototype, Component.prototype);
    pureComponentPrototype.isPureReactComponent = true;
    var isArrayImpl$1 = Array.isArray, ReactSharedInternals$2 = { H: null, A: null, T: null, S: null }, hasOwnProperty$2 = Object.prototype.hasOwnProperty;
    function ReactElement(type, key2, self2, source2, owner, props) {
      self2 = props.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE$1,
        type,
        key: key2,
        ref: void 0 !== self2 ? self2 : null,
        props
      };
    }
    function cloneAndReplaceKey(oldElement, newKey) {
      return ReactElement(
        oldElement.type,
        newKey,
        void 0,
        void 0,
        void 0,
        oldElement.props
      );
    }
    function isValidElement(object) {
      return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE$1;
    }
    function escape$3(key2) {
      var escaperLookup = { "=": "=0", ":": "=2" };
      return "$" + key2.replace(/[=:]/g, function(match) {
        return escaperLookup[match];
      });
    }
    var userProvidedKeyEscapeRegex = /\/+/g;
    function getElementKey(element, index2) {
      return "object" === typeof element && null !== element && null != element.key ? escape$3("" + element.key) : index2.toString(36);
    }
    function noop$1$1() {
    }
    function resolveThenable(thenable) {
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenable.reason;
        default:
          switch ("string" === typeof thenable.status ? thenable.then(noop$1$1, noop$1$1) : (thenable.status = "pending", thenable.then(
            function(fulfilledValue) {
              "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
            },
            function(error2) {
              "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
            }
          )), thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenable.reason;
          }
      }
      throw thenable;
    }
    function mapIntoArray(children2, array, escapedPrefix, nameSoFar, callback) {
      var type = typeof children2;
      if ("undefined" === type || "boolean" === type) children2 = null;
      var invokeCallback = false;
      if (null === children2) invokeCallback = true;
      else
        switch (type) {
          case "bigint":
          case "string":
          case "number":
            invokeCallback = true;
            break;
          case "object":
            switch (children2.$$typeof) {
              case REACT_ELEMENT_TYPE$1:
              case REACT_PORTAL_TYPE$2:
                invokeCallback = true;
                break;
              case REACT_LAZY_TYPE$1:
                return invokeCallback = children2._init, mapIntoArray(
                  invokeCallback(children2._payload),
                  array,
                  escapedPrefix,
                  nameSoFar,
                  callback
                );
            }
        }
      if (invokeCallback)
        return callback = callback(children2), invokeCallback = "" === nameSoFar ? "." + getElementKey(children2, 0) : nameSoFar, isArrayImpl$1(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c2) {
          return c2;
        })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey(
          callback,
          escapedPrefix + (null == callback.key || children2 && children2.key === callback.key ? "" : ("" + callback.key).replace(
            userProvidedKeyEscapeRegex,
            "$&/"
          ) + "/") + invokeCallback
        )), array.push(callback)), 1;
      invokeCallback = 0;
      var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
      if (isArrayImpl$1(children2))
        for (var i2 = 0; i2 < children2.length; i2++)
          nameSoFar = children2[i2], type = nextNamePrefix + getElementKey(nameSoFar, i2), invokeCallback += mapIntoArray(
            nameSoFar,
            array,
            escapedPrefix,
            type,
            callback
          );
      else if (i2 = getIteratorFn$1(children2), "function" === typeof i2)
        for (children2 = i2.call(children2), i2 = 0; !(nameSoFar = children2.next()).done; )
          nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i2++), invokeCallback += mapIntoArray(
            nameSoFar,
            array,
            escapedPrefix,
            type,
            callback
          );
      else if ("object" === type) {
        if ("function" === typeof children2.then)
          return mapIntoArray(
            resolveThenable(children2),
            array,
            escapedPrefix,
            nameSoFar,
            callback
          );
        array = String(children2);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children2).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      return invokeCallback;
    }
    function mapChildren(children2, func, context) {
      if (null == children2) return children2;
      var result2 = [], count = 0;
      mapIntoArray(children2, result2, "", "", function(child) {
        return func.call(context, child, count++);
      });
      return result2;
    }
    function lazyInitializer(payload) {
      if (-1 === payload._status) {
        var ctor = payload._result;
        ctor = ctor();
        ctor.then(
          function(moduleObject) {
            if (0 === payload._status || -1 === payload._status)
              payload._status = 1, payload._result = moduleObject;
          },
          function(error2) {
            if (0 === payload._status || -1 === payload._status)
              payload._status = 2, payload._result = error2;
          }
        );
        -1 === payload._status && (payload._status = 0, payload._result = ctor);
      }
      if (1 === payload._status) return payload._result.default;
      throw payload._result;
    }
    var reportGlobalError$1 = "function" === typeof reportError ? reportError : function(error2) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
          error: error2
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process && "function" === typeof process.emit) {
        process.emit("uncaughtException", error2);
        return;
      }
      console.error(error2);
    };
    function noop$5() {
    }
    react_production.Children = {
      map: mapChildren,
      forEach: function(children2, forEachFunc, forEachContext) {
        mapChildren(
          children2,
          function() {
            forEachFunc.apply(this, arguments);
          },
          forEachContext
        );
      },
      count: function(children2) {
        var n = 0;
        mapChildren(children2, function() {
          n++;
        });
        return n;
      },
      toArray: function(children2) {
        return mapChildren(children2, function(child) {
          return child;
        }) || [];
      },
      only: function(children2) {
        if (!isValidElement(children2))
          throw Error(
            "React.Children.only expected to receive a single React element child."
          );
        return children2;
      }
    };
    react_production.Component = Component;
    react_production.Fragment = REACT_FRAGMENT_TYPE$1;
    react_production.Profiler = REACT_PROFILER_TYPE$1;
    react_production.PureComponent = PureComponent;
    react_production.StrictMode = REACT_STRICT_MODE_TYPE$1;
    react_production.Suspense = REACT_SUSPENSE_TYPE$1;
    react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals$2;
    react_production.act = function() {
      throw Error("act(...) is not supported in production builds of React.");
    };
    react_production.cache = function(fn2) {
      return function() {
        return fn2.apply(null, arguments);
      };
    };
    react_production.cloneElement = function(element, config2, children2) {
      if (null === element || void 0 === element)
        throw Error(
          "The argument must be a React element, but you passed " + element + "."
        );
      var props = assign$3({}, element.props), key2 = element.key, owner = void 0;
      if (null != config2)
        for (propName in void 0 !== config2.ref && (owner = void 0), void 0 !== config2.key && (key2 = "" + config2.key), config2)
          !hasOwnProperty$2.call(config2, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config2.ref || (props[propName] = config2[propName]);
      var propName = arguments.length - 2;
      if (1 === propName) props.children = children2;
      else if (1 < propName) {
        for (var childArray = Array(propName), i2 = 0; i2 < propName; i2++)
          childArray[i2] = arguments[i2 + 2];
        props.children = childArray;
      }
      return ReactElement(element.type, key2, void 0, void 0, owner, props);
    };
    react_production.createContext = function(defaultValue) {
      defaultValue = {
        $$typeof: REACT_CONTEXT_TYPE$1,
        _currentValue: defaultValue,
        _currentValue2: defaultValue,
        _threadCount: 0,
        Provider: null,
        Consumer: null
      };
      defaultValue.Provider = defaultValue;
      defaultValue.Consumer = {
        $$typeof: REACT_CONSUMER_TYPE$1,
        _context: defaultValue
      };
      return defaultValue;
    };
    react_production.createElement = function(type, config2, children2) {
      var propName, props = {}, key2 = null;
      if (null != config2)
        for (propName in void 0 !== config2.key && (key2 = "" + config2.key), config2)
          hasOwnProperty$2.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config2[propName]);
      var childrenLength = arguments.length - 2;
      if (1 === childrenLength) props.children = children2;
      else if (1 < childrenLength) {
        for (var childArray = Array(childrenLength), i2 = 0; i2 < childrenLength; i2++)
          childArray[i2] = arguments[i2 + 2];
        props.children = childArray;
      }
      if (type && type.defaultProps)
        for (propName in childrenLength = type.defaultProps, childrenLength)
          void 0 === props[propName] && (props[propName] = childrenLength[propName]);
      return ReactElement(type, key2, void 0, void 0, null, props);
    };
    react_production.createRef = function() {
      return { current: null };
    };
    react_production.forwardRef = function(render2) {
      return { $$typeof: REACT_FORWARD_REF_TYPE$1, render: render2 };
    };
    react_production.isValidElement = isValidElement;
    react_production.lazy = function(ctor) {
      return {
        $$typeof: REACT_LAZY_TYPE$1,
        _payload: { _status: -1, _result: ctor },
        _init: lazyInitializer
      };
    };
    react_production.memo = function(type, compare2) {
      return {
        $$typeof: REACT_MEMO_TYPE$1,
        type,
        compare: void 0 === compare2 ? null : compare2
      };
    };
    react_production.startTransition = function(scope) {
      var prevTransition = ReactSharedInternals$2.T, currentTransition = {};
      ReactSharedInternals$2.T = currentTransition;
      try {
        var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals$2.S;
        null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
        "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop$5, reportGlobalError$1);
      } catch (error2) {
        reportGlobalError$1(error2);
      } finally {
        ReactSharedInternals$2.T = prevTransition;
      }
    };
    react_production.unstable_useCacheRefresh = function() {
      return ReactSharedInternals$2.H.useCacheRefresh();
    };
    react_production.use = function(usable) {
      return ReactSharedInternals$2.H.use(usable);
    };
    react_production.useActionState = function(action, initialState2, permalink) {
      return ReactSharedInternals$2.H.useActionState(action, initialState2, permalink);
    };
    react_production.useCallback = function(callback, deps) {
      return ReactSharedInternals$2.H.useCallback(callback, deps);
    };
    react_production.useContext = function(Context2) {
      return ReactSharedInternals$2.H.useContext(Context2);
    };
    react_production.useDebugValue = function() {
    };
    react_production.useDeferredValue = function(value2, initialValue) {
      return ReactSharedInternals$2.H.useDeferredValue(value2, initialValue);
    };
    react_production.useEffect = function(create2, deps) {
      return ReactSharedInternals$2.H.useEffect(create2, deps);
    };
    react_production.useId = function() {
      return ReactSharedInternals$2.H.useId();
    };
    react_production.useImperativeHandle = function(ref, create2, deps) {
      return ReactSharedInternals$2.H.useImperativeHandle(ref, create2, deps);
    };
    react_production.useInsertionEffect = function(create2, deps) {
      return ReactSharedInternals$2.H.useInsertionEffect(create2, deps);
    };
    react_production.useLayoutEffect = function(create2, deps) {
      return ReactSharedInternals$2.H.useLayoutEffect(create2, deps);
    };
    react_production.useMemo = function(create2, deps) {
      return ReactSharedInternals$2.H.useMemo(create2, deps);
    };
    react_production.useOptimistic = function(passthrough, reducer) {
      return ReactSharedInternals$2.H.useOptimistic(passthrough, reducer);
    };
    react_production.useReducer = function(reducer, initialArg, init) {
      return ReactSharedInternals$2.H.useReducer(reducer, initialArg, init);
    };
    react_production.useRef = function(initialValue) {
      return ReactSharedInternals$2.H.useRef(initialValue);
    };
    react_production.useState = function(initialState2) {
      return ReactSharedInternals$2.H.useState(initialState2);
    };
    react_production.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
      return ReactSharedInternals$2.H.useSyncExternalStore(
        subscribe,
        getSnapshot,
        getServerSnapshot
      );
    };
    react_production.useTransition = function() {
      return ReactSharedInternals$2.H.useTransition();
    };
    react_production.version = "19.0.0";
    {
      react.exports = react_production;
    }
    var reactExports = react.exports;
    const React$2 = /* @__PURE__ */ getDefaultExportFromCjs(reactExports);
    var reactDom = { exports: {} };
    var reactDom_production = {};
    /**
     * @license React
     * react-dom.production.js
     *
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    var React$1 = reactExports;
    function formatProdErrorMessage$1(code2) {
      var url = "https://react.dev/errors/" + code2;
      if (1 < arguments.length) {
        url += "?args[]=" + encodeURIComponent(arguments[1]);
        for (var i2 = 2; i2 < arguments.length; i2++)
          url += "&args[]=" + encodeURIComponent(arguments[i2]);
      }
      return "Minified React error #" + code2 + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
    }
    function noop$4() {
    }
    var Internals = {
      d: {
        f: noop$4,
        r: function() {
          throw Error(formatProdErrorMessage$1(522));
        },
        D: noop$4,
        C: noop$4,
        L: noop$4,
        m: noop$4,
        X: noop$4,
        S: noop$4,
        M: noop$4
      },
      p: 0,
      findDOMNode: null
    }, REACT_PORTAL_TYPE$1 = Symbol.for("react.portal");
    function createPortal$1(children2, containerInfo, implementation) {
      var key2 = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
      return {
        $$typeof: REACT_PORTAL_TYPE$1,
        key: null == key2 ? null : "" + key2,
        children: children2,
        containerInfo,
        implementation
      };
    }
    var ReactSharedInternals$1 = React$1.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
    function getCrossOriginStringAs(as, input2) {
      if ("font" === as) return "";
      if ("string" === typeof input2)
        return "use-credentials" === input2 ? input2 : "";
    }
    reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals;
    reactDom_production.createPortal = function(children2, container2) {
      var key2 = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
      if (!container2 || 1 !== container2.nodeType && 9 !== container2.nodeType && 11 !== container2.nodeType)
        throw Error(formatProdErrorMessage$1(299));
      return createPortal$1(children2, container2, null, key2);
    };
    reactDom_production.flushSync = function(fn2) {
      var previousTransition = ReactSharedInternals$1.T, previousUpdatePriority = Internals.p;
      try {
        if (ReactSharedInternals$1.T = null, Internals.p = 2, fn2) return fn2();
      } finally {
        ReactSharedInternals$1.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f();
      }
    };
    reactDom_production.preconnect = function(href, options2) {
      "string" === typeof href && (options2 ? (options2 = options2.crossOrigin, options2 = "string" === typeof options2 ? "use-credentials" === options2 ? options2 : "" : void 0) : options2 = null, Internals.d.C(href, options2));
    };
    reactDom_production.prefetchDNS = function(href) {
      "string" === typeof href && Internals.d.D(href);
    };
    reactDom_production.preinit = function(href, options2) {
      if ("string" === typeof href && options2 && "string" === typeof options2.as) {
        var as = options2.as, crossOrigin = getCrossOriginStringAs(as, options2.crossOrigin), integrity = "string" === typeof options2.integrity ? options2.integrity : void 0, fetchPriority = "string" === typeof options2.fetchPriority ? options2.fetchPriority : void 0;
        "style" === as ? Internals.d.S(
          href,
          "string" === typeof options2.precedence ? options2.precedence : void 0,
          {
            crossOrigin,
            integrity,
            fetchPriority
          }
        ) : "script" === as && Internals.d.X(href, {
          crossOrigin,
          integrity,
          fetchPriority,
          nonce: "string" === typeof options2.nonce ? options2.nonce : void 0
        });
      }
    };
    reactDom_production.preinitModule = function(href, options2) {
      if ("string" === typeof href)
        if ("object" === typeof options2 && null !== options2) {
          if (null == options2.as || "script" === options2.as) {
            var crossOrigin = getCrossOriginStringAs(
              options2.as,
              options2.crossOrigin
            );
            Internals.d.M(href, {
              crossOrigin,
              integrity: "string" === typeof options2.integrity ? options2.integrity : void 0,
              nonce: "string" === typeof options2.nonce ? options2.nonce : void 0
            });
          }
        } else null == options2 && Internals.d.M(href);
    };
    reactDom_production.preload = function(href, options2) {
      if ("string" === typeof href && "object" === typeof options2 && null !== options2 && "string" === typeof options2.as) {
        var as = options2.as, crossOrigin = getCrossOriginStringAs(as, options2.crossOrigin);
        Internals.d.L(href, as, {
          crossOrigin,
          integrity: "string" === typeof options2.integrity ? options2.integrity : void 0,
          nonce: "string" === typeof options2.nonce ? options2.nonce : void 0,
          type: "string" === typeof options2.type ? options2.type : void 0,
          fetchPriority: "string" === typeof options2.fetchPriority ? options2.fetchPriority : void 0,
          referrerPolicy: "string" === typeof options2.referrerPolicy ? options2.referrerPolicy : void 0,
          imageSrcSet: "string" === typeof options2.imageSrcSet ? options2.imageSrcSet : void 0,
          imageSizes: "string" === typeof options2.imageSizes ? options2.imageSizes : void 0,
          media: "string" === typeof options2.media ? options2.media : void 0
        });
      }
    };
    reactDom_production.preloadModule = function(href, options2) {
      if ("string" === typeof href)
        if (options2) {
          var crossOrigin = getCrossOriginStringAs(options2.as, options2.crossOrigin);
          Internals.d.m(href, {
            as: "string" === typeof options2.as && "script" !== options2.as ? options2.as : void 0,
            crossOrigin,
            integrity: "string" === typeof options2.integrity ? options2.integrity : void 0
          });
        } else Internals.d.m(href);
    };
    reactDom_production.requestFormReset = function(form) {
      Internals.d.r(form);
    };
    reactDom_production.unstable_batchedUpdates = function(fn2, a) {
      return fn2(a);
    };
    reactDom_production.useFormState = function(action, initialState2, permalink) {
      return ReactSharedInternals$1.H.useFormState(action, initialState2, permalink);
    };
    reactDom_production.useFormStatus = function() {
      return ReactSharedInternals$1.H.useHostTransitionStatus();
    };
    reactDom_production.version = "19.0.0";
    function checkDCE$1() {
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
        return;
      }
      try {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE$1);
      } catch (err2) {
        console.error(err2);
      }
    }
    {
      checkDCE$1();
      reactDom.exports = reactDom_production;
    }
    var reactDomExports = reactDom.exports;
    const io = /* @__PURE__ */ getDefaultExportFromCjs(reactDomExports);
    /**
     * @license React
     * react-dom-client.production.js
     *
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    var Scheduler = schedulerExports, React = reactExports, ReactDOM = reactDomExports;
    function formatProdErrorMessage(code2) {
      var url = "https://react.dev/errors/" + code2;
      if (1 < arguments.length) {
        url += "?args[]=" + encodeURIComponent(arguments[1]);
        for (var i2 = 2; i2 < arguments.length; i2++)
          url += "&args[]=" + encodeURIComponent(arguments[i2]);
      }
      return "Minified React error #" + code2 + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
    }
    function isValidContainer(node2) {
      return !(!node2 || 1 !== node2.nodeType && 9 !== node2.nodeType && 11 !== node2.nodeType);
    }
    var REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_PROVIDER_TYPE = Symbol.for("react.provider"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy");
    var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
    var REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
    function getIteratorFn(maybeIterable) {
      if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
      maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
      return "function" === typeof maybeIterable ? maybeIterable : null;
    }
    var REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference");
    function getComponentNameFromType(type) {
      if (null == type) return null;
      if ("function" === typeof type)
        return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
      if ("string" === typeof type) return type;
      switch (type) {
        case REACT_FRAGMENT_TYPE:
          return "Fragment";
        case REACT_PORTAL_TYPE:
          return "Portal";
        case REACT_PROFILER_TYPE:
          return "Profiler";
        case REACT_STRICT_MODE_TYPE:
          return "StrictMode";
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
      }
      if ("object" === typeof type)
        switch (type.$$typeof) {
          case REACT_CONTEXT_TYPE:
            return (type.displayName || "Context") + ".Provider";
          case REACT_CONSUMER_TYPE:
            return (type._context.displayName || "Context") + ".Consumer";
          case REACT_FORWARD_REF_TYPE:
            var innerType = type.render;
            type = type.displayName;
            type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
            return type;
          case REACT_MEMO_TYPE:
            return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
          case REACT_LAZY_TYPE:
            innerType = type._payload;
            type = type._init;
            try {
              return getComponentNameFromType(type(innerType));
            } catch (x2) {
            }
        }
      return null;
    }
    var ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, assign$2 = Object.assign, prefix, suffix;
    function describeBuiltInComponentFrame(name2) {
      if (void 0 === prefix)
        try {
          throw Error();
        } catch (x2) {
          var match = x2.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || "";
          suffix = -1 < x2.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x2.stack.indexOf("@") ? "@unknown:0:0" : "";
        }
      return "\n" + prefix + name2 + suffix;
    }
    var reentry = false;
    function describeNativeComponentFrame(fn2, construct) {
      if (!fn2 || reentry) return "";
      reentry = true;
      var previousPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      try {
        var RunInRootFrame = {
          DetermineComponentFrameRoot: function() {
            try {
              if (construct) {
                var Fake = function() {
                  throw Error();
                };
                Object.defineProperty(Fake.prototype, "props", {
                  set: function() {
                    throw Error();
                  }
                });
                if ("object" === typeof Reflect && Reflect.construct) {
                  try {
                    Reflect.construct(Fake, []);
                  } catch (x2) {
                    var control = x2;
                  }
                  Reflect.construct(fn2, [], Fake);
                } else {
                  try {
                    Fake.call();
                  } catch (x$0) {
                    control = x$0;
                  }
                  fn2.call(Fake.prototype);
                }
              } else {
                try {
                  throw Error();
                } catch (x$12) {
                  control = x$12;
                }
                (Fake = fn2()) && "function" === typeof Fake.catch && Fake.catch(function() {
                });
              }
            } catch (sample2) {
              if (sample2 && control && "string" === typeof sample2.stack)
                return [sample2.stack, control.stack];
            }
            return [null, null];
          }
        };
        RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
        var namePropDescriptor = Object.getOwnPropertyDescriptor(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name"
        );
        namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name",
          { value: "DetermineComponentFrameRoot" }
        );
        var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
        if (sampleStack && controlStack) {
          var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
          for (namePropDescriptor = RunInRootFrame = 0; RunInRootFrame < sampleLines.length && !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); )
            RunInRootFrame++;
          for (; namePropDescriptor < controlLines.length && !controlLines[namePropDescriptor].includes(
            "DetermineComponentFrameRoot"
          ); )
            namePropDescriptor++;
          if (RunInRootFrame === sampleLines.length || namePropDescriptor === controlLines.length)
            for (RunInRootFrame = sampleLines.length - 1, namePropDescriptor = controlLines.length - 1; 1 <= RunInRootFrame && 0 <= namePropDescriptor && sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; )
              namePropDescriptor--;
          for (; 1 <= RunInRootFrame && 0 <= namePropDescriptor; RunInRootFrame--, namePropDescriptor--)
            if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
              if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {
                do
                  if (RunInRootFrame--, namePropDescriptor--, 0 > namePropDescriptor || sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
                    var frame = "\n" + sampleLines[RunInRootFrame].replace(" at new ", " at ");
                    fn2.displayName && frame.includes("<anonymous>") && (frame = frame.replace("<anonymous>", fn2.displayName));
                    return frame;
                  }
                while (1 <= RunInRootFrame && 0 <= namePropDescriptor);
              }
              break;
            }
        }
      } finally {
        reentry = false, Error.prepareStackTrace = previousPrepareStackTrace;
      }
      return (previousPrepareStackTrace = fn2 ? fn2.displayName || fn2.name : "") ? describeBuiltInComponentFrame(previousPrepareStackTrace) : "";
    }
    function describeFiber(fiber) {
      switch (fiber.tag) {
        case 26:
        case 27:
        case 5:
          return describeBuiltInComponentFrame(fiber.type);
        case 16:
          return describeBuiltInComponentFrame("Lazy");
        case 13:
          return describeBuiltInComponentFrame("Suspense");
        case 19:
          return describeBuiltInComponentFrame("SuspenseList");
        case 0:
        case 15:
          return fiber = describeNativeComponentFrame(fiber.type, false), fiber;
        case 11:
          return fiber = describeNativeComponentFrame(fiber.type.render, false), fiber;
        case 1:
          return fiber = describeNativeComponentFrame(fiber.type, true), fiber;
        default:
          return "";
      }
    }
    function getStackByFiberInDevAndProd(workInProgress2) {
      try {
        var info = "";
        do
          info += describeFiber(workInProgress2), workInProgress2 = workInProgress2.return;
        while (workInProgress2);
        return info;
      } catch (x2) {
        return "\nError generating stack: " + x2.message + "\n" + x2.stack;
      }
    }
    function getNearestMountedFiber(fiber) {
      var node2 = fiber, nearestMounted = fiber;
      if (fiber.alternate) for (; node2.return; ) node2 = node2.return;
      else {
        fiber = node2;
        do
          node2 = fiber, 0 !== (node2.flags & 4098) && (nearestMounted = node2.return), fiber = node2.return;
        while (fiber);
      }
      return 3 === node2.tag ? nearestMounted : null;
    }
    function getSuspenseInstanceFromFiber(fiber) {
      if (13 === fiber.tag) {
        var suspenseState = fiber.memoizedState;
        null === suspenseState && (fiber = fiber.alternate, null !== fiber && (suspenseState = fiber.memoizedState));
        if (null !== suspenseState) return suspenseState.dehydrated;
      }
      return null;
    }
    function assertIsMounted(fiber) {
      if (getNearestMountedFiber(fiber) !== fiber)
        throw Error(formatProdErrorMessage(188));
    }
    function findCurrentFiberUsingSlowPath(fiber) {
      var alternate = fiber.alternate;
      if (!alternate) {
        alternate = getNearestMountedFiber(fiber);
        if (null === alternate) throw Error(formatProdErrorMessage(188));
        return alternate !== fiber ? null : fiber;
      }
      for (var a = fiber, b = alternate; ; ) {
        var parentA = a.return;
        if (null === parentA) break;
        var parentB = parentA.alternate;
        if (null === parentB) {
          b = parentA.return;
          if (null !== b) {
            a = b;
            continue;
          }
          break;
        }
        if (parentA.child === parentB.child) {
          for (parentB = parentA.child; parentB; ) {
            if (parentB === a) return assertIsMounted(parentA), fiber;
            if (parentB === b) return assertIsMounted(parentA), alternate;
            parentB = parentB.sibling;
          }
          throw Error(formatProdErrorMessage(188));
        }
        if (a.return !== b.return) a = parentA, b = parentB;
        else {
          for (var didFindChild = false, child$2 = parentA.child; child$2; ) {
            if (child$2 === a) {
              didFindChild = true;
              a = parentA;
              b = parentB;
              break;
            }
            if (child$2 === b) {
              didFindChild = true;
              b = parentA;
              a = parentB;
              break;
            }
            child$2 = child$2.sibling;
          }
          if (!didFindChild) {
            for (child$2 = parentB.child; child$2; ) {
              if (child$2 === a) {
                didFindChild = true;
                a = parentB;
                b = parentA;
                break;
              }
              if (child$2 === b) {
                didFindChild = true;
                b = parentB;
                a = parentA;
                break;
              }
              child$2 = child$2.sibling;
            }
            if (!didFindChild) throw Error(formatProdErrorMessage(189));
          }
        }
        if (a.alternate !== b) throw Error(formatProdErrorMessage(190));
      }
      if (3 !== a.tag) throw Error(formatProdErrorMessage(188));
      return a.stateNode.current === a ? fiber : alternate;
    }
    function findCurrentHostFiberImpl(node2) {
      var tag = node2.tag;
      if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node2;
      for (node2 = node2.child; null !== node2; ) {
        tag = findCurrentHostFiberImpl(node2);
        if (null !== tag) return tag;
        node2 = node2.sibling;
      }
      return null;
    }
    var isArrayImpl = Array.isArray, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, sharedNotPendingObject = {
      pending: false,
      data: null,
      method: null,
      action: null
    }, valueStack = [], index = -1;
    function createCursor(defaultValue) {
      return { current: defaultValue };
    }
    function pop$1(cursor) {
      0 > index || (cursor.current = valueStack[index], valueStack[index] = null, index--);
    }
    function push$1(cursor, value2) {
      index++;
      valueStack[index] = cursor.current;
      cursor.current = value2;
    }
    var contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null);
    function pushHostContainer(fiber, nextRootInstance) {
      push$1(rootInstanceStackCursor, nextRootInstance);
      push$1(contextFiberStackCursor, fiber);
      push$1(contextStackCursor, null);
      fiber = nextRootInstance.nodeType;
      switch (fiber) {
        case 9:
        case 11:
          nextRootInstance = (nextRootInstance = nextRootInstance.documentElement) ? (nextRootInstance = nextRootInstance.namespaceURI) ? getOwnHostContext(nextRootInstance) : 0 : 0;
          break;
        default:
          if (fiber = 8 === fiber ? nextRootInstance.parentNode : nextRootInstance, nextRootInstance = fiber.tagName, fiber = fiber.namespaceURI)
            fiber = getOwnHostContext(fiber), nextRootInstance = getChildHostContextProd(fiber, nextRootInstance);
          else
            switch (nextRootInstance) {
              case "svg":
                nextRootInstance = 1;
                break;
              case "math":
                nextRootInstance = 2;
                break;
              default:
                nextRootInstance = 0;
            }
      }
      pop$1(contextStackCursor);
      push$1(contextStackCursor, nextRootInstance);
    }
    function popHostContainer() {
      pop$1(contextStackCursor);
      pop$1(contextFiberStackCursor);
      pop$1(rootInstanceStackCursor);
    }
    function pushHostContext(fiber) {
      null !== fiber.memoizedState && push$1(hostTransitionProviderCursor, fiber);
      var context = contextStackCursor.current;
      var JSCompiler_inline_result = getChildHostContextProd(context, fiber.type);
      context !== JSCompiler_inline_result && (push$1(contextFiberStackCursor, fiber), push$1(contextStackCursor, JSCompiler_inline_result));
    }
    function popHostContext(fiber) {
      contextFiberStackCursor.current === fiber && (pop$1(contextStackCursor), pop$1(contextFiberStackCursor));
      hostTransitionProviderCursor.current === fiber && (pop$1(hostTransitionProviderCursor), HostTransitionContext._currentValue = sharedNotPendingObject);
    }
    var hasOwnProperty$1 = Object.prototype.hasOwnProperty, scheduleCallback$3 = Scheduler.unstable_scheduleCallback, cancelCallback$1 = Scheduler.unstable_cancelCallback, shouldYield = Scheduler.unstable_shouldYield, requestPaint = Scheduler.unstable_requestPaint, now = Scheduler.unstable_now, getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel, ImmediatePriority = Scheduler.unstable_ImmediatePriority, UserBlockingPriority = Scheduler.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler.unstable_NormalPriority, LowPriority = Scheduler.unstable_LowPriority, IdlePriority = Scheduler.unstable_IdlePriority, log$1 = Scheduler.log, unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue, rendererID = null, injectedHook = null;
    function onCommitRoot(root2) {
      if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
        try {
          injectedHook.onCommitFiberRoot(
            rendererID,
            root2,
            void 0,
            128 === (root2.current.flags & 128)
          );
        } catch (err2) {
        }
    }
    function setIsStrictModeForDevtools(newIsStrictMode) {
      "function" === typeof log$1 && unstable_setDisableYieldValue(newIsStrictMode);
      if (injectedHook && "function" === typeof injectedHook.setStrictMode)
        try {
          injectedHook.setStrictMode(rendererID, newIsStrictMode);
        } catch (err2) {
        }
    }
    var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2;
    function clz32Fallback(x2) {
      x2 >>>= 0;
      return 0 === x2 ? 32 : 31 - (log(x2) / LN2 | 0) | 0;
    }
    var nextTransitionLane = 128, nextRetryLane = 4194304;
    function getHighestPriorityLanes(lanes) {
      var pendingSyncLanes = lanes & 42;
      if (0 !== pendingSyncLanes) return pendingSyncLanes;
      switch (lanes & -lanes) {
        case 1:
          return 1;
        case 2:
          return 2;
        case 4:
          return 4;
        case 8:
          return 8;
        case 16:
          return 16;
        case 32:
          return 32;
        case 64:
          return 64;
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return lanes & 4194176;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
          return lanes & 62914560;
        case 67108864:
          return 67108864;
        case 134217728:
          return 134217728;
        case 268435456:
          return 268435456;
        case 536870912:
          return 536870912;
        case 1073741824:
          return 0;
        default:
          return lanes;
      }
    }
    function getNextLanes(root2, wipLanes) {
      var pendingLanes = root2.pendingLanes;
      if (0 === pendingLanes) return 0;
      var nextLanes = 0, suspendedLanes = root2.suspendedLanes, pingedLanes = root2.pingedLanes, warmLanes = root2.warmLanes;
      root2 = 0 !== root2.finishedLanes;
      var nonIdlePendingLanes = pendingLanes & 134217727;
      0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : root2 || (warmLanes = nonIdlePendingLanes & ~warmLanes, 0 !== warmLanes && (nextLanes = getHighestPriorityLanes(warmLanes))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : root2 || (warmLanes = pendingLanes & ~warmLanes, 0 !== warmLanes && (nextLanes = getHighestPriorityLanes(warmLanes))));
      return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, warmLanes = wipLanes & -wipLanes, suspendedLanes >= warmLanes || 32 === suspendedLanes && 0 !== (warmLanes & 4194176)) ? wipLanes : nextLanes;
    }
    function checkIfRootIsPrerendering(root2, renderLanes2) {
      return 0 === (root2.pendingLanes & ~(root2.suspendedLanes & ~root2.pingedLanes) & renderLanes2);
    }
    function computeExpirationTime(lane, currentTime) {
      switch (lane) {
        case 1:
        case 2:
        case 4:
        case 8:
          return currentTime + 250;
        case 16:
        case 32:
        case 64:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return currentTime + 5e3;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
          return -1;
        case 67108864:
        case 134217728:
        case 268435456:
        case 536870912:
        case 1073741824:
          return -1;
        default:
          return -1;
      }
    }
    function claimNextTransitionLane() {
      var lane = nextTransitionLane;
      nextTransitionLane <<= 1;
      0 === (nextTransitionLane & 4194176) && (nextTransitionLane = 128);
      return lane;
    }
    function claimNextRetryLane() {
      var lane = nextRetryLane;
      nextRetryLane <<= 1;
      0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
      return lane;
    }
    function createLaneMap(initial) {
      for (var laneMap = [], i2 = 0; 31 > i2; i2++) laneMap.push(initial);
      return laneMap;
    }
    function markRootUpdated$1(root2, updateLane) {
      root2.pendingLanes |= updateLane;
      268435456 !== updateLane && (root2.suspendedLanes = 0, root2.pingedLanes = 0, root2.warmLanes = 0);
    }
    function markRootFinished(root2, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
      var previouslyPendingLanes = root2.pendingLanes;
      root2.pendingLanes = remainingLanes;
      root2.suspendedLanes = 0;
      root2.pingedLanes = 0;
      root2.warmLanes = 0;
      root2.expiredLanes &= remainingLanes;
      root2.entangledLanes &= remainingLanes;
      root2.errorRecoveryDisabledLanes &= remainingLanes;
      root2.shellSuspendCounter = 0;
      var entanglements = root2.entanglements, expirationTimes = root2.expirationTimes, hiddenUpdates = root2.hiddenUpdates;
      for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
        var index$7 = 31 - clz32(remainingLanes), lane = 1 << index$7;
        entanglements[index$7] = 0;
        expirationTimes[index$7] = -1;
        var hiddenUpdatesForLane = hiddenUpdates[index$7];
        if (null !== hiddenUpdatesForLane)
          for (hiddenUpdates[index$7] = null, index$7 = 0; index$7 < hiddenUpdatesForLane.length; index$7++) {
            var update = hiddenUpdatesForLane[index$7];
            null !== update && (update.lane &= -536870913);
          }
        remainingLanes &= ~lane;
      }
      0 !== spawnedLane && markSpawnedDeferredLane(root2, spawnedLane, 0);
      0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root2.tag && (root2.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
    }
    function markSpawnedDeferredLane(root2, spawnedLane, entangledLanes) {
      root2.pendingLanes |= spawnedLane;
      root2.suspendedLanes &= ~spawnedLane;
      var spawnedLaneIndex = 31 - clz32(spawnedLane);
      root2.entangledLanes |= spawnedLane;
      root2.entanglements[spawnedLaneIndex] = root2.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 4194218;
    }
    function markRootEntangled(root2, entangledLanes) {
      var rootEntangledLanes = root2.entangledLanes |= entangledLanes;
      for (root2 = root2.entanglements; rootEntangledLanes; ) {
        var index$8 = 31 - clz32(rootEntangledLanes), lane = 1 << index$8;
        lane & entangledLanes | root2[index$8] & entangledLanes && (root2[index$8] |= entangledLanes);
        rootEntangledLanes &= ~lane;
      }
    }
    function lanesToEventPriority(lanes) {
      lanes &= -lanes;
      return 2 < lanes ? 8 < lanes ? 0 !== (lanes & 134217727) ? 32 : 268435456 : 8 : 2;
    }
    function resolveUpdatePriority() {
      var updatePriority = ReactDOMSharedInternals.p;
      if (0 !== updatePriority) return updatePriority;
      updatePriority = window.event;
      return void 0 === updatePriority ? 32 : getEventPriority(updatePriority.type);
    }
    function runWithPriority(priority, fn2) {
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        return ReactDOMSharedInternals.p = priority, fn2();
      } finally {
        ReactDOMSharedInternals.p = previousPriority;
      }
    }
    var randomKey = Math.random().toString(36).slice(2), internalInstanceKey = "__reactFiber$" + randomKey, internalPropsKey = "__reactProps$" + randomKey, internalContainerInstanceKey = "__reactContainer$" + randomKey, internalEventHandlersKey = "__reactEvents$" + randomKey, internalEventHandlerListenersKey = "__reactListeners$" + randomKey, internalEventHandlesSetKey = "__reactHandles$" + randomKey, internalRootNodeResourcesKey = "__reactResources$" + randomKey, internalHoistableMarker = "__reactMarker$" + randomKey;
    function detachDeletedInstance(node2) {
      delete node2[internalInstanceKey];
      delete node2[internalPropsKey];
      delete node2[internalEventHandlersKey];
      delete node2[internalEventHandlerListenersKey];
      delete node2[internalEventHandlesSetKey];
    }
    function getClosestInstanceFromNode(targetNode) {
      var targetInst = targetNode[internalInstanceKey];
      if (targetInst) return targetInst;
      for (var parentNode = targetNode.parentNode; parentNode; ) {
        if (targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey]) {
          parentNode = targetInst.alternate;
          if (null !== targetInst.child || null !== parentNode && null !== parentNode.child)
            for (targetNode = getParentSuspenseInstance(targetNode); null !== targetNode; ) {
              if (parentNode = targetNode[internalInstanceKey]) return parentNode;
              targetNode = getParentSuspenseInstance(targetNode);
            }
          return targetInst;
        }
        targetNode = parentNode;
        parentNode = targetNode.parentNode;
      }
      return null;
    }
    function getInstanceFromNode(node2) {
      if (node2 = node2[internalInstanceKey] || node2[internalContainerInstanceKey]) {
        var tag = node2.tag;
        if (5 === tag || 6 === tag || 13 === tag || 26 === tag || 27 === tag || 3 === tag)
          return node2;
      }
      return null;
    }
    function getNodeFromInstance(inst) {
      var tag = inst.tag;
      if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return inst.stateNode;
      throw Error(formatProdErrorMessage(33));
    }
    function getResourcesFromRoot(root2) {
      var resources = root2[internalRootNodeResourcesKey];
      resources || (resources = root2[internalRootNodeResourcesKey] = { hoistableStyles: /* @__PURE__ */ new Map(), hoistableScripts: /* @__PURE__ */ new Map() });
      return resources;
    }
    function markNodeAsHoistable(node2) {
      node2[internalHoistableMarker] = true;
    }
    var allNativeEvents = /* @__PURE__ */ new Set(), registrationNameDependencies = {};
    function registerTwoPhaseEvent(registrationName, dependencies) {
      registerDirectEvent(registrationName, dependencies);
      registerDirectEvent(registrationName + "Capture", dependencies);
    }
    function registerDirectEvent(registrationName, dependencies) {
      registrationNameDependencies[registrationName] = dependencies;
      for (registrationName = 0; registrationName < dependencies.length; registrationName++)
        allNativeEvents.add(dependencies[registrationName]);
    }
    var canUseDOM = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), VALID_ATTRIBUTE_NAME_REGEX = RegExp(
      "^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
    ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {};
    function isAttributeNameSafe(attributeName) {
      if (hasOwnProperty$1.call(validatedAttributeNameCache, attributeName))
        return true;
      if (hasOwnProperty$1.call(illegalAttributeNameCache, attributeName)) return false;
      if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
        return validatedAttributeNameCache[attributeName] = true;
      illegalAttributeNameCache[attributeName] = true;
      return false;
    }
    function setValueForAttribute(node2, name2, value2) {
      if (isAttributeNameSafe(name2))
        if (null === value2) node2.removeAttribute(name2);
        else {
          switch (typeof value2) {
            case "undefined":
            case "function":
            case "symbol":
              node2.removeAttribute(name2);
              return;
            case "boolean":
              var prefix$10 = name2.toLowerCase().slice(0, 5);
              if ("data-" !== prefix$10 && "aria-" !== prefix$10) {
                node2.removeAttribute(name2);
                return;
              }
          }
          node2.setAttribute(name2, "" + value2);
        }
    }
    function setValueForKnownAttribute(node2, name2, value2) {
      if (null === value2) node2.removeAttribute(name2);
      else {
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            node2.removeAttribute(name2);
            return;
        }
        node2.setAttribute(name2, "" + value2);
      }
    }
    function setValueForNamespacedAttribute(node2, namespace, name2, value2) {
      if (null === value2) node2.removeAttribute(name2);
      else {
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            node2.removeAttribute(name2);
            return;
        }
        node2.setAttributeNS(namespace, name2, "" + value2);
      }
    }
    function getToStringValue(value2) {
      switch (typeof value2) {
        case "bigint":
        case "boolean":
        case "number":
        case "string":
        case "undefined":
          return value2;
        case "object":
          return value2;
        default:
          return "";
      }
    }
    function isCheckable(elem) {
      var type = elem.type;
      return (elem = elem.nodeName) && "input" === elem.toLowerCase() && ("checkbox" === type || "radio" === type);
    }
    function trackValueOnNode(node2) {
      var valueField = isCheckable(node2) ? "checked" : "value", descriptor = Object.getOwnPropertyDescriptor(
        node2.constructor.prototype,
        valueField
      ), currentValue = "" + node2[valueField];
      if (!node2.hasOwnProperty(valueField) && "undefined" !== typeof descriptor && "function" === typeof descriptor.get && "function" === typeof descriptor.set) {
        var get2 = descriptor.get, set = descriptor.set;
        Object.defineProperty(node2, valueField, {
          configurable: true,
          get: function() {
            return get2.call(this);
          },
          set: function(value2) {
            currentValue = "" + value2;
            set.call(this, value2);
          }
        });
        Object.defineProperty(node2, valueField, {
          enumerable: descriptor.enumerable
        });
        return {
          getValue: function() {
            return currentValue;
          },
          setValue: function(value2) {
            currentValue = "" + value2;
          },
          stopTracking: function() {
            node2._valueTracker = null;
            delete node2[valueField];
          }
        };
      }
    }
    function track(node2) {
      node2._valueTracker || (node2._valueTracker = trackValueOnNode(node2));
    }
    function updateValueIfChanged(node2) {
      if (!node2) return false;
      var tracker = node2._valueTracker;
      if (!tracker) return true;
      var lastValue = tracker.getValue();
      var value2 = "";
      node2 && (value2 = isCheckable(node2) ? node2.checked ? "true" : "false" : node2.value);
      node2 = value2;
      return node2 !== lastValue ? (tracker.setValue(node2), true) : false;
    }
    function getActiveElement(doc2) {
      doc2 = doc2 || ("undefined" !== typeof document ? document : void 0);
      if ("undefined" === typeof doc2) return null;
      try {
        return doc2.activeElement || doc2.body;
      } catch (e) {
        return doc2.body;
      }
    }
    var escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\n"\\]/g;
    function escapeSelectorAttributeValueInsideDoubleQuotes(value2) {
      return value2.replace(
        escapeSelectorAttributeValueInsideDoubleQuotesRegex,
        function(ch3) {
          return "\\" + ch3.charCodeAt(0).toString(16) + " ";
        }
      );
    }
    function updateInput(element, value2, defaultValue, lastDefaultValue, checked, defaultChecked, type, name2) {
      element.name = "";
      null != type && "function" !== typeof type && "symbol" !== typeof type && "boolean" !== typeof type ? element.type = type : element.removeAttribute("type");
      if (null != value2)
        if ("number" === type) {
          if (0 === value2 && "" === element.value || element.value != value2)
            element.value = "" + getToStringValue(value2);
        } else
          element.value !== "" + getToStringValue(value2) && (element.value = "" + getToStringValue(value2));
      else
        "submit" !== type && "reset" !== type || element.removeAttribute("value");
      null != value2 ? setDefaultValue(element, type, getToStringValue(value2)) : null != defaultValue ? setDefaultValue(element, type, getToStringValue(defaultValue)) : null != lastDefaultValue && element.removeAttribute("value");
      null == checked && null != defaultChecked && (element.defaultChecked = !!defaultChecked);
      null != checked && (element.checked = checked && "function" !== typeof checked && "symbol" !== typeof checked);
      null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 ? element.name = "" + getToStringValue(name2) : element.removeAttribute("name");
    }
    function initInput(element, value2, defaultValue, checked, defaultChecked, type, name2, isHydrating2) {
      null != type && "function" !== typeof type && "symbol" !== typeof type && "boolean" !== typeof type && (element.type = type);
      if (null != value2 || null != defaultValue) {
        if (!("submit" !== type && "reset" !== type || void 0 !== value2 && null !== value2))
          return;
        defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
        value2 = null != value2 ? "" + getToStringValue(value2) : defaultValue;
        isHydrating2 || value2 === element.value || (element.value = value2);
        element.defaultValue = value2;
      }
      checked = null != checked ? checked : defaultChecked;
      checked = "function" !== typeof checked && "symbol" !== typeof checked && !!checked;
      element.checked = isHydrating2 ? element.checked : !!checked;
      element.defaultChecked = !!checked;
      null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 && (element.name = name2);
    }
    function setDefaultValue(node2, type, value2) {
      "number" === type && getActiveElement(node2.ownerDocument) === node2 || node2.defaultValue === "" + value2 || (node2.defaultValue = "" + value2);
    }
    function updateOptions(node2, multiple, propValue, setDefaultSelected) {
      node2 = node2.options;
      if (multiple) {
        multiple = {};
        for (var i2 = 0; i2 < propValue.length; i2++)
          multiple["$" + propValue[i2]] = true;
        for (propValue = 0; propValue < node2.length; propValue++)
          i2 = multiple.hasOwnProperty("$" + node2[propValue].value), node2[propValue].selected !== i2 && (node2[propValue].selected = i2), i2 && setDefaultSelected && (node2[propValue].defaultSelected = true);
      } else {
        propValue = "" + getToStringValue(propValue);
        multiple = null;
        for (i2 = 0; i2 < node2.length; i2++) {
          if (node2[i2].value === propValue) {
            node2[i2].selected = true;
            setDefaultSelected && (node2[i2].defaultSelected = true);
            return;
          }
          null !== multiple || node2[i2].disabled || (multiple = node2[i2]);
        }
        null !== multiple && (multiple.selected = true);
      }
    }
    function updateTextarea(element, value2, defaultValue) {
      if (null != value2 && (value2 = "" + getToStringValue(value2), value2 !== element.value && (element.value = value2), null == defaultValue)) {
        element.defaultValue !== value2 && (element.defaultValue = value2);
        return;
      }
      element.defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
    }
    function initTextarea(element, value2, defaultValue, children2) {
      if (null == value2) {
        if (null != children2) {
          if (null != defaultValue) throw Error(formatProdErrorMessage(92));
          if (isArrayImpl(children2)) {
            if (1 < children2.length) throw Error(formatProdErrorMessage(93));
            children2 = children2[0];
          }
          defaultValue = children2;
        }
        null == defaultValue && (defaultValue = "");
        value2 = defaultValue;
      }
      defaultValue = getToStringValue(value2);
      element.defaultValue = defaultValue;
      children2 = element.textContent;
      children2 === defaultValue && "" !== children2 && null !== children2 && (element.value = children2);
    }
    function setTextContent(node2, text2) {
      if (text2) {
        var firstChild = node2.firstChild;
        if (firstChild && firstChild === node2.lastChild && 3 === firstChild.nodeType) {
          firstChild.nodeValue = text2;
          return;
        }
      }
      node2.textContent = text2;
    }
    var unitlessNumbers = new Set(
      "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
        " "
      )
    );
    function setValueForStyle(style2, styleName, value2) {
      var isCustomProperty = 0 === styleName.indexOf("--");
      null == value2 || "boolean" === typeof value2 || "" === value2 ? isCustomProperty ? style2.setProperty(styleName, "") : "float" === styleName ? style2.cssFloat = "" : style2[styleName] = "" : isCustomProperty ? style2.setProperty(styleName, value2) : "number" !== typeof value2 || 0 === value2 || unitlessNumbers.has(styleName) ? "float" === styleName ? style2.cssFloat = value2 : style2[styleName] = ("" + value2).trim() : style2[styleName] = value2 + "px";
    }
    function setValueForStyles(node2, styles2, prevStyles) {
      if (null != styles2 && "object" !== typeof styles2)
        throw Error(formatProdErrorMessage(62));
      node2 = node2.style;
      if (null != prevStyles) {
        for (var styleName in prevStyles)
          !prevStyles.hasOwnProperty(styleName) || null != styles2 && styles2.hasOwnProperty(styleName) || (0 === styleName.indexOf("--") ? node2.setProperty(styleName, "") : "float" === styleName ? node2.cssFloat = "" : node2[styleName] = "");
        for (var styleName$16 in styles2)
          styleName = styles2[styleName$16], styles2.hasOwnProperty(styleName$16) && prevStyles[styleName$16] !== styleName && setValueForStyle(node2, styleName$16, styleName);
      } else
        for (var styleName$17 in styles2)
          styles2.hasOwnProperty(styleName$17) && setValueForStyle(node2, styleName$17, styles2[styleName$17]);
    }
    function isCustomElement(tagName) {
      if (-1 === tagName.indexOf("-")) return false;
      switch (tagName) {
        case "annotation-xml":
        case "color-profile":
        case "font-face":
        case "font-face-src":
        case "font-face-uri":
        case "font-face-format":
        case "font-face-name":
        case "missing-glyph":
          return false;
        default:
          return true;
      }
    }
    var aliases = /* @__PURE__ */ new Map([
      ["acceptCharset", "accept-charset"],
      ["htmlFor", "for"],
      ["httpEquiv", "http-equiv"],
      ["crossOrigin", "crossorigin"],
      ["accentHeight", "accent-height"],
      ["alignmentBaseline", "alignment-baseline"],
      ["arabicForm", "arabic-form"],
      ["baselineShift", "baseline-shift"],
      ["capHeight", "cap-height"],
      ["clipPath", "clip-path"],
      ["clipRule", "clip-rule"],
      ["colorInterpolation", "color-interpolation"],
      ["colorInterpolationFilters", "color-interpolation-filters"],
      ["colorProfile", "color-profile"],
      ["colorRendering", "color-rendering"],
      ["dominantBaseline", "dominant-baseline"],
      ["enableBackground", "enable-background"],
      ["fillOpacity", "fill-opacity"],
      ["fillRule", "fill-rule"],
      ["floodColor", "flood-color"],
      ["floodOpacity", "flood-opacity"],
      ["fontFamily", "font-family"],
      ["fontSize", "font-size"],
      ["fontSizeAdjust", "font-size-adjust"],
      ["fontStretch", "font-stretch"],
      ["fontStyle", "font-style"],
      ["fontVariant", "font-variant"],
      ["fontWeight", "font-weight"],
      ["glyphName", "glyph-name"],
      ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
      ["glyphOrientationVertical", "glyph-orientation-vertical"],
      ["horizAdvX", "horiz-adv-x"],
      ["horizOriginX", "horiz-origin-x"],
      ["imageRendering", "image-rendering"],
      ["letterSpacing", "letter-spacing"],
      ["lightingColor", "lighting-color"],
      ["markerEnd", "marker-end"],
      ["markerMid", "marker-mid"],
      ["markerStart", "marker-start"],
      ["overlinePosition", "overline-position"],
      ["overlineThickness", "overline-thickness"],
      ["paintOrder", "paint-order"],
      ["panose-1", "panose-1"],
      ["pointerEvents", "pointer-events"],
      ["renderingIntent", "rendering-intent"],
      ["shapeRendering", "shape-rendering"],
      ["stopColor", "stop-color"],
      ["stopOpacity", "stop-opacity"],
      ["strikethroughPosition", "strikethrough-position"],
      ["strikethroughThickness", "strikethrough-thickness"],
      ["strokeDasharray", "stroke-dasharray"],
      ["strokeDashoffset", "stroke-dashoffset"],
      ["strokeLinecap", "stroke-linecap"],
      ["strokeLinejoin", "stroke-linejoin"],
      ["strokeMiterlimit", "stroke-miterlimit"],
      ["strokeOpacity", "stroke-opacity"],
      ["strokeWidth", "stroke-width"],
      ["textAnchor", "text-anchor"],
      ["textDecoration", "text-decoration"],
      ["textRendering", "text-rendering"],
      ["transformOrigin", "transform-origin"],
      ["underlinePosition", "underline-position"],
      ["underlineThickness", "underline-thickness"],
      ["unicodeBidi", "unicode-bidi"],
      ["unicodeRange", "unicode-range"],
      ["unitsPerEm", "units-per-em"],
      ["vAlphabetic", "v-alphabetic"],
      ["vHanging", "v-hanging"],
      ["vIdeographic", "v-ideographic"],
      ["vMathematical", "v-mathematical"],
      ["vectorEffect", "vector-effect"],
      ["vertAdvY", "vert-adv-y"],
      ["vertOriginX", "vert-origin-x"],
      ["vertOriginY", "vert-origin-y"],
      ["wordSpacing", "word-spacing"],
      ["writingMode", "writing-mode"],
      ["xmlnsXlink", "xmlns:xlink"],
      ["xHeight", "x-height"]
    ]), isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
    function sanitizeURL(url) {
      return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
    }
    var currentReplayingEvent = null;
    function getEventTarget(nativeEvent) {
      nativeEvent = nativeEvent.target || nativeEvent.srcElement || window;
      nativeEvent.correspondingUseElement && (nativeEvent = nativeEvent.correspondingUseElement);
      return 3 === nativeEvent.nodeType ? nativeEvent.parentNode : nativeEvent;
    }
    var restoreTarget = null, restoreQueue = null;
    function restoreStateOfTarget(target2) {
      var internalInstance = getInstanceFromNode(target2);
      if (internalInstance && (target2 = internalInstance.stateNode)) {
        var props = target2[internalPropsKey] || null;
        a: switch (target2 = internalInstance.stateNode, internalInstance.type) {
          case "input":
            updateInput(
              target2,
              props.value,
              props.defaultValue,
              props.defaultValue,
              props.checked,
              props.defaultChecked,
              props.type,
              props.name
            );
            internalInstance = props.name;
            if ("radio" === props.type && null != internalInstance) {
              for (props = target2; props.parentNode; ) props = props.parentNode;
              props = props.querySelectorAll(
                'input[name="' + escapeSelectorAttributeValueInsideDoubleQuotes(
                  "" + internalInstance
                ) + '"][type="radio"]'
              );
              for (internalInstance = 0; internalInstance < props.length; internalInstance++) {
                var otherNode = props[internalInstance];
                if (otherNode !== target2 && otherNode.form === target2.form) {
                  var otherProps = otherNode[internalPropsKey] || null;
                  if (!otherProps) throw Error(formatProdErrorMessage(90));
                  updateInput(
                    otherNode,
                    otherProps.value,
                    otherProps.defaultValue,
                    otherProps.defaultValue,
                    otherProps.checked,
                    otherProps.defaultChecked,
                    otherProps.type,
                    otherProps.name
                  );
                }
              }
              for (internalInstance = 0; internalInstance < props.length; internalInstance++)
                otherNode = props[internalInstance], otherNode.form === target2.form && updateValueIfChanged(otherNode);
            }
            break a;
          case "textarea":
            updateTextarea(target2, props.value, props.defaultValue);
            break a;
          case "select":
            internalInstance = props.value, null != internalInstance && updateOptions(target2, !!props.multiple, internalInstance, false);
        }
      }
    }
    var isInsideEventHandler = false;
    function batchedUpdates$1(fn2, a, b) {
      if (isInsideEventHandler) return fn2(a, b);
      isInsideEventHandler = true;
      try {
        var JSCompiler_inline_result = fn2(a);
        return JSCompiler_inline_result;
      } finally {
        if (isInsideEventHandler = false, null !== restoreTarget || null !== restoreQueue) {
          if (flushSyncWork$1(), restoreTarget && (a = restoreTarget, fn2 = restoreQueue, restoreQueue = restoreTarget = null, restoreStateOfTarget(a), fn2))
            for (a = 0; a < fn2.length; a++) restoreStateOfTarget(fn2[a]);
        }
      }
    }
    function getListener$1(inst, registrationName) {
      var stateNode = inst.stateNode;
      if (null === stateNode) return null;
      var props = stateNode[internalPropsKey] || null;
      if (null === props) return null;
      stateNode = props[registrationName];
      a: switch (registrationName) {
        case "onClick":
        case "onClickCapture":
        case "onDoubleClick":
        case "onDoubleClickCapture":
        case "onMouseDown":
        case "onMouseDownCapture":
        case "onMouseMove":
        case "onMouseMoveCapture":
        case "onMouseUp":
        case "onMouseUpCapture":
        case "onMouseEnter":
          (props = !props.disabled) || (inst = inst.type, props = !("button" === inst || "input" === inst || "select" === inst || "textarea" === inst));
          inst = !props;
          break a;
        default:
          inst = false;
      }
      if (inst) return null;
      if (stateNode && "function" !== typeof stateNode)
        throw Error(
          formatProdErrorMessage(231, registrationName, typeof stateNode)
        );
      return stateNode;
    }
    var passiveBrowserEventsSupported = false;
    if (canUseDOM)
      try {
        var options = {};
        Object.defineProperty(options, "passive", {
          get: function() {
            passiveBrowserEventsSupported = true;
          }
        });
        window.addEventListener("test", options, options);
        window.removeEventListener("test", options, options);
      } catch (e) {
        passiveBrowserEventsSupported = false;
      }
    var root$2 = null, startText = null, fallbackText = null;
    function getData() {
      if (fallbackText) return fallbackText;
      var start, startValue = startText, startLength = startValue.length, end, endValue = "value" in root$2 ? root$2.value : root$2.textContent, endLength = endValue.length;
      for (start = 0; start < startLength && startValue[start] === endValue[start]; start++) ;
      var minEnd = startLength - start;
      for (end = 1; end <= minEnd && startValue[startLength - end] === endValue[endLength - end]; end++) ;
      return fallbackText = endValue.slice(start, 1 < end ? 1 - end : void 0);
    }
    function getEventCharCode(nativeEvent) {
      var keyCode = nativeEvent.keyCode;
      "charCode" in nativeEvent ? (nativeEvent = nativeEvent.charCode, 0 === nativeEvent && 13 === keyCode && (nativeEvent = 13)) : nativeEvent = keyCode;
      10 === nativeEvent && (nativeEvent = 13);
      return 32 <= nativeEvent || 13 === nativeEvent ? nativeEvent : 0;
    }
    function functionThatReturnsTrue() {
      return true;
    }
    function functionThatReturnsFalse() {
      return false;
    }
    function createSyntheticEvent(Interface) {
      function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
        this._reactName = reactName;
        this._targetInst = targetInst;
        this.type = reactEventType;
        this.nativeEvent = nativeEvent;
        this.target = nativeEventTarget;
        this.currentTarget = null;
        for (var propName in Interface)
          Interface.hasOwnProperty(propName) && (reactName = Interface[propName], this[propName] = reactName ? reactName(nativeEvent) : nativeEvent[propName]);
        this.isDefaultPrevented = (null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : false === nativeEvent.returnValue) ? functionThatReturnsTrue : functionThatReturnsFalse;
        this.isPropagationStopped = functionThatReturnsFalse;
        return this;
      }
      assign$2(SyntheticBaseEvent.prototype, {
        preventDefault: function() {
          this.defaultPrevented = true;
          var event = this.nativeEvent;
          event && (event.preventDefault ? event.preventDefault() : "unknown" !== typeof event.returnValue && (event.returnValue = false), this.isDefaultPrevented = functionThatReturnsTrue);
        },
        stopPropagation: function() {
          var event = this.nativeEvent;
          event && (event.stopPropagation ? event.stopPropagation() : "unknown" !== typeof event.cancelBubble && (event.cancelBubble = true), this.isPropagationStopped = functionThatReturnsTrue);
        },
        persist: function() {
        },
        isPersistent: functionThatReturnsTrue
      });
      return SyntheticBaseEvent;
    }
    var EventInterface = {
      eventPhase: 0,
      bubbles: 0,
      cancelable: 0,
      timeStamp: function(event) {
        return event.timeStamp || Date.now();
      },
      defaultPrevented: 0,
      isTrusted: 0
    }, SyntheticEvent = createSyntheticEvent(EventInterface), UIEventInterface = assign$2({}, EventInterface, { view: 0, detail: 0 }), SyntheticUIEvent = createSyntheticEvent(UIEventInterface), lastMovementX, lastMovementY, lastMouseEvent, MouseEventInterface = assign$2({}, UIEventInterface, {
      screenX: 0,
      screenY: 0,
      clientX: 0,
      clientY: 0,
      pageX: 0,
      pageY: 0,
      ctrlKey: 0,
      shiftKey: 0,
      altKey: 0,
      metaKey: 0,
      getModifierState: getEventModifierState,
      button: 0,
      buttons: 0,
      relatedTarget: function(event) {
        return void 0 === event.relatedTarget ? event.fromElement === event.srcElement ? event.toElement : event.fromElement : event.relatedTarget;
      },
      movementX: function(event) {
        if ("movementX" in event) return event.movementX;
        event !== lastMouseEvent && (lastMouseEvent && "mousemove" === event.type ? (lastMovementX = event.screenX - lastMouseEvent.screenX, lastMovementY = event.screenY - lastMouseEvent.screenY) : lastMovementY = lastMovementX = 0, lastMouseEvent = event);
        return lastMovementX;
      },
      movementY: function(event) {
        return "movementY" in event ? event.movementY : lastMovementY;
      }
    }), SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface), DragEventInterface = assign$2({}, MouseEventInterface, { dataTransfer: 0 }), SyntheticDragEvent = createSyntheticEvent(DragEventInterface), FocusEventInterface = assign$2({}, UIEventInterface, { relatedTarget: 0 }), SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface), AnimationEventInterface = assign$2({}, EventInterface, {
      animationName: 0,
      elapsedTime: 0,
      pseudoElement: 0
    }), SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface), ClipboardEventInterface = assign$2({}, EventInterface, {
      clipboardData: function(event) {
        return "clipboardData" in event ? event.clipboardData : window.clipboardData;
      }
    }), SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface), CompositionEventInterface = assign$2({}, EventInterface, { data: 0 }), SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface), normalizeKey = {
      Esc: "Escape",
      Spacebar: " ",
      Left: "ArrowLeft",
      Up: "ArrowUp",
      Right: "ArrowRight",
      Down: "ArrowDown",
      Del: "Delete",
      Win: "OS",
      Menu: "ContextMenu",
      Apps: "ContextMenu",
      Scroll: "ScrollLock",
      MozPrintableKey: "Unidentified"
    }, translateToKey = {
      8: "Backspace",
      9: "Tab",
      12: "Clear",
      13: "Enter",
      16: "Shift",
      17: "Control",
      18: "Alt",
      19: "Pause",
      20: "CapsLock",
      27: "Escape",
      32: " ",
      33: "PageUp",
      34: "PageDown",
      35: "End",
      36: "Home",
      37: "ArrowLeft",
      38: "ArrowUp",
      39: "ArrowRight",
      40: "ArrowDown",
      45: "Insert",
      46: "Delete",
      112: "F1",
      113: "F2",
      114: "F3",
      115: "F4",
      116: "F5",
      117: "F6",
      118: "F7",
      119: "F8",
      120: "F9",
      121: "F10",
      122: "F11",
      123: "F12",
      144: "NumLock",
      145: "ScrollLock",
      224: "Meta"
    }, modifierKeyToProp = {
      Alt: "altKey",
      Control: "ctrlKey",
      Meta: "metaKey",
      Shift: "shiftKey"
    };
    function modifierStateGetter(keyArg) {
      var nativeEvent = this.nativeEvent;
      return nativeEvent.getModifierState ? nativeEvent.getModifierState(keyArg) : (keyArg = modifierKeyToProp[keyArg]) ? !!nativeEvent[keyArg] : false;
    }
    function getEventModifierState() {
      return modifierStateGetter;
    }
    var KeyboardEventInterface = assign$2({}, UIEventInterface, {
      key: function(nativeEvent) {
        if (nativeEvent.key) {
          var key2 = normalizeKey[nativeEvent.key] || nativeEvent.key;
          if ("Unidentified" !== key2) return key2;
        }
        return "keypress" === nativeEvent.type ? (nativeEvent = getEventCharCode(nativeEvent), 13 === nativeEvent ? "Enter" : String.fromCharCode(nativeEvent)) : "keydown" === nativeEvent.type || "keyup" === nativeEvent.type ? translateToKey[nativeEvent.keyCode] || "Unidentified" : "";
      },
      code: 0,
      location: 0,
      ctrlKey: 0,
      shiftKey: 0,
      altKey: 0,
      metaKey: 0,
      repeat: 0,
      locale: 0,
      getModifierState: getEventModifierState,
      charCode: function(event) {
        return "keypress" === event.type ? getEventCharCode(event) : 0;
      },
      keyCode: function(event) {
        return "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
      },
      which: function(event) {
        return "keypress" === event.type ? getEventCharCode(event) : "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
      }
    }), SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface), PointerEventInterface = assign$2({}, MouseEventInterface, {
      pointerId: 0,
      width: 0,
      height: 0,
      pressure: 0,
      tangentialPressure: 0,
      tiltX: 0,
      tiltY: 0,
      twist: 0,
      pointerType: 0,
      isPrimary: 0
    }), SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface), TouchEventInterface = assign$2({}, UIEventInterface, {
      touches: 0,
      targetTouches: 0,
      changedTouches: 0,
      altKey: 0,
      metaKey: 0,
      ctrlKey: 0,
      shiftKey: 0,
      getModifierState: getEventModifierState
    }), SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface), TransitionEventInterface = assign$2({}, EventInterface, {
      propertyName: 0,
      elapsedTime: 0,
      pseudoElement: 0
    }), SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface), WheelEventInterface = assign$2({}, MouseEventInterface, {
      deltaX: function(event) {
        return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0;
      },
      deltaY: function(event) {
        return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0;
      },
      deltaZ: 0,
      deltaMode: 0
    }), SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface), ToggleEventInterface = assign$2({}, EventInterface, {
      newState: 0,
      oldState: 0
    }), SyntheticToggleEvent = createSyntheticEvent(ToggleEventInterface), END_KEYCODES = [9, 13, 27, 32], canUseCompositionEvent = canUseDOM && "CompositionEvent" in window, documentMode = null;
    canUseDOM && "documentMode" in document && (documentMode = document.documentMode);
    var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode, useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && 8 < documentMode && 11 >= documentMode), SPACEBAR_CHAR = String.fromCharCode(32), hasSpaceKeypress = false;
    function isFallbackCompositionEnd(domEventName, nativeEvent) {
      switch (domEventName) {
        case "keyup":
          return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);
        case "keydown":
          return 229 !== nativeEvent.keyCode;
        case "keypress":
        case "mousedown":
        case "focusout":
          return true;
        default:
          return false;
      }
    }
    function getDataFromCustomEvent(nativeEvent) {
      nativeEvent = nativeEvent.detail;
      return "object" === typeof nativeEvent && "data" in nativeEvent ? nativeEvent.data : null;
    }
    var isComposing = false;
    function getNativeBeforeInputChars(domEventName, nativeEvent) {
      switch (domEventName) {
        case "compositionend":
          return getDataFromCustomEvent(nativeEvent);
        case "keypress":
          if (32 !== nativeEvent.which) return null;
          hasSpaceKeypress = true;
          return SPACEBAR_CHAR;
        case "textInput":
          return domEventName = nativeEvent.data, domEventName === SPACEBAR_CHAR && hasSpaceKeypress ? null : domEventName;
        default:
          return null;
      }
    }
    function getFallbackBeforeInputChars(domEventName, nativeEvent) {
      if (isComposing)
        return "compositionend" === domEventName || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent) ? (domEventName = getData(), fallbackText = startText = root$2 = null, isComposing = false, domEventName) : null;
      switch (domEventName) {
        case "paste":
          return null;
        case "keypress":
          if (!(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) || nativeEvent.ctrlKey && nativeEvent.altKey) {
            if (nativeEvent.char && 1 < nativeEvent.char.length)
              return nativeEvent.char;
            if (nativeEvent.which) return String.fromCharCode(nativeEvent.which);
          }
          return null;
        case "compositionend":
          return useFallbackCompositionData && "ko" !== nativeEvent.locale ? null : nativeEvent.data;
        default:
          return null;
      }
    }
    var supportedInputTypes = {
      color: true,
      date: true,
      datetime: true,
      "datetime-local": true,
      email: true,
      month: true,
      number: true,
      password: true,
      range: true,
      search: true,
      tel: true,
      text: true,
      time: true,
      url: true,
      week: true
    };
    function isTextInputElement(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
      return "input" === nodeName ? !!supportedInputTypes[elem.type] : "textarea" === nodeName ? true : false;
    }
    function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target2) {
      restoreTarget ? restoreQueue ? restoreQueue.push(target2) : restoreQueue = [target2] : restoreTarget = target2;
      inst = accumulateTwoPhaseListeners(inst, "onChange");
      0 < inst.length && (nativeEvent = new SyntheticEvent(
        "onChange",
        "change",
        null,
        nativeEvent,
        target2
      ), dispatchQueue.push({ event: nativeEvent, listeners: inst }));
    }
    var activeElement$1 = null, activeElementInst$1 = null;
    function runEventInBatch(dispatchQueue) {
      processDispatchQueue(dispatchQueue, 0);
    }
    function getInstIfValueChanged(targetInst) {
      var targetNode = getNodeFromInstance(targetInst);
      if (updateValueIfChanged(targetNode)) return targetInst;
    }
    function getTargetInstForChangeEvent(domEventName, targetInst) {
      if ("change" === domEventName) return targetInst;
    }
    var isInputEventSupported = false;
    if (canUseDOM) {
      var JSCompiler_inline_result$jscomp$283;
      if (canUseDOM) {
        var isSupported$jscomp$inline_418 = "oninput" in document;
        if (!isSupported$jscomp$inline_418) {
          var element$jscomp$inline_419 = document.createElement("div");
          element$jscomp$inline_419.setAttribute("oninput", "return;");
          isSupported$jscomp$inline_418 = "function" === typeof element$jscomp$inline_419.oninput;
        }
        JSCompiler_inline_result$jscomp$283 = isSupported$jscomp$inline_418;
      } else JSCompiler_inline_result$jscomp$283 = false;
      isInputEventSupported = JSCompiler_inline_result$jscomp$283 && (!document.documentMode || 9 < document.documentMode);
    }
    function stopWatchingForValueChange() {
      activeElement$1 && (activeElement$1.detachEvent("onpropertychange", handlePropertyChange), activeElementInst$1 = activeElement$1 = null);
    }
    function handlePropertyChange(nativeEvent) {
      if ("value" === nativeEvent.propertyName && getInstIfValueChanged(activeElementInst$1)) {
        var dispatchQueue = [];
        createAndAccumulateChangeEvent(
          dispatchQueue,
          activeElementInst$1,
          nativeEvent,
          getEventTarget(nativeEvent)
        );
        batchedUpdates$1(runEventInBatch, dispatchQueue);
      }
    }
    function handleEventsForInputEventPolyfill(domEventName, target2, targetInst) {
      "focusin" === domEventName ? (stopWatchingForValueChange(), activeElement$1 = target2, activeElementInst$1 = targetInst, activeElement$1.attachEvent("onpropertychange", handlePropertyChange)) : "focusout" === domEventName && stopWatchingForValueChange();
    }
    function getTargetInstForInputEventPolyfill(domEventName) {
      if ("selectionchange" === domEventName || "keyup" === domEventName || "keydown" === domEventName)
        return getInstIfValueChanged(activeElementInst$1);
    }
    function getTargetInstForClickEvent(domEventName, targetInst) {
      if ("click" === domEventName) return getInstIfValueChanged(targetInst);
    }
    function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
      if ("input" === domEventName || "change" === domEventName)
        return getInstIfValueChanged(targetInst);
    }
    function is(x2, y) {
      return x2 === y && (0 !== x2 || 1 / x2 === 1 / y) || x2 !== x2 && y !== y;
    }
    var objectIs = "function" === typeof Object.is ? Object.is : is;
    function shallowEqual(objA, objB) {
      if (objectIs(objA, objB)) return true;
      if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
        return false;
      var keysA = Object.keys(objA), keysB = Object.keys(objB);
      if (keysA.length !== keysB.length) return false;
      for (keysB = 0; keysB < keysA.length; keysB++) {
        var currentKey = keysA[keysB];
        if (!hasOwnProperty$1.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
          return false;
      }
      return true;
    }
    function getLeafNode(node2) {
      for (; node2 && node2.firstChild; ) node2 = node2.firstChild;
      return node2;
    }
    function getNodeForCharacterOffset(root2, offset) {
      var node2 = getLeafNode(root2);
      root2 = 0;
      for (var nodeEnd; node2; ) {
        if (3 === node2.nodeType) {
          nodeEnd = root2 + node2.textContent.length;
          if (root2 <= offset && nodeEnd >= offset)
            return { node: node2, offset: offset - root2 };
          root2 = nodeEnd;
        }
        a: {
          for (; node2; ) {
            if (node2.nextSibling) {
              node2 = node2.nextSibling;
              break a;
            }
            node2 = node2.parentNode;
          }
          node2 = void 0;
        }
        node2 = getLeafNode(node2);
      }
    }
    function containsNode(outerNode, innerNode) {
      return outerNode && innerNode ? outerNode === innerNode ? true : outerNode && 3 === outerNode.nodeType ? false : innerNode && 3 === innerNode.nodeType ? containsNode(outerNode, innerNode.parentNode) : "contains" in outerNode ? outerNode.contains(innerNode) : outerNode.compareDocumentPosition ? !!(outerNode.compareDocumentPosition(innerNode) & 16) : false : false;
    }
    function getActiveElementDeep(containerInfo) {
      containerInfo = null != containerInfo && null != containerInfo.ownerDocument && null != containerInfo.ownerDocument.defaultView ? containerInfo.ownerDocument.defaultView : window;
      for (var element = getActiveElement(containerInfo.document); element instanceof containerInfo.HTMLIFrameElement; ) {
        try {
          var JSCompiler_inline_result = "string" === typeof element.contentWindow.location.href;
        } catch (err2) {
          JSCompiler_inline_result = false;
        }
        if (JSCompiler_inline_result) containerInfo = element.contentWindow;
        else break;
        element = getActiveElement(containerInfo.document);
      }
      return element;
    }
    function hasSelectionCapabilities(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
      return nodeName && ("input" === nodeName && ("text" === elem.type || "search" === elem.type || "tel" === elem.type || "url" === elem.type || "password" === elem.type) || "textarea" === nodeName || "true" === elem.contentEditable);
    }
    function restoreSelection(priorSelectionInformation, containerInfo) {
      var curFocusedElem = getActiveElementDeep(containerInfo);
      containerInfo = priorSelectionInformation.focusedElem;
      var priorSelectionRange = priorSelectionInformation.selectionRange;
      if (curFocusedElem !== containerInfo && containerInfo && containerInfo.ownerDocument && containsNode(containerInfo.ownerDocument.documentElement, containerInfo)) {
        if (null !== priorSelectionRange && hasSelectionCapabilities(containerInfo)) {
          if (priorSelectionInformation = priorSelectionRange.start, curFocusedElem = priorSelectionRange.end, void 0 === curFocusedElem && (curFocusedElem = priorSelectionInformation), "selectionStart" in containerInfo)
            containerInfo.selectionStart = priorSelectionInformation, containerInfo.selectionEnd = Math.min(
              curFocusedElem,
              containerInfo.value.length
            );
          else if (curFocusedElem = (priorSelectionInformation = containerInfo.ownerDocument || document) && priorSelectionInformation.defaultView || window, curFocusedElem.getSelection) {
            curFocusedElem = curFocusedElem.getSelection();
            var length = containerInfo.textContent.length, start = Math.min(priorSelectionRange.start, length);
            priorSelectionRange = void 0 === priorSelectionRange.end ? start : Math.min(priorSelectionRange.end, length);
            !curFocusedElem.extend && start > priorSelectionRange && (length = priorSelectionRange, priorSelectionRange = start, start = length);
            length = getNodeForCharacterOffset(containerInfo, start);
            var endMarker = getNodeForCharacterOffset(
              containerInfo,
              priorSelectionRange
            );
            length && endMarker && (1 !== curFocusedElem.rangeCount || curFocusedElem.anchorNode !== length.node || curFocusedElem.anchorOffset !== length.offset || curFocusedElem.focusNode !== endMarker.node || curFocusedElem.focusOffset !== endMarker.offset) && (priorSelectionInformation = priorSelectionInformation.createRange(), priorSelectionInformation.setStart(length.node, length.offset), curFocusedElem.removeAllRanges(), start > priorSelectionRange ? (curFocusedElem.addRange(priorSelectionInformation), curFocusedElem.extend(endMarker.node, endMarker.offset)) : (priorSelectionInformation.setEnd(
              endMarker.node,
              endMarker.offset
            ), curFocusedElem.addRange(priorSelectionInformation)));
          }
        }
        priorSelectionInformation = [];
        for (curFocusedElem = containerInfo; curFocusedElem = curFocusedElem.parentNode; )
          1 === curFocusedElem.nodeType && priorSelectionInformation.push({
            element: curFocusedElem,
            left: curFocusedElem.scrollLeft,
            top: curFocusedElem.scrollTop
          });
        "function" === typeof containerInfo.focus && containerInfo.focus();
        for (containerInfo = 0; containerInfo < priorSelectionInformation.length; containerInfo++)
          curFocusedElem = priorSelectionInformation[containerInfo], curFocusedElem.element.scrollLeft = curFocusedElem.left, curFocusedElem.element.scrollTop = curFocusedElem.top;
      }
    }
    var skipSelectionChangeEvent = canUseDOM && "documentMode" in document && 11 >= document.documentMode, activeElement = null, activeElementInst = null, lastSelection = null, mouseDown = false;
    function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
      var doc2 = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : 9 === nativeEventTarget.nodeType ? nativeEventTarget : nativeEventTarget.ownerDocument;
      mouseDown || null == activeElement || activeElement !== getActiveElement(doc2) || (doc2 = activeElement, "selectionStart" in doc2 && hasSelectionCapabilities(doc2) ? doc2 = { start: doc2.selectionStart, end: doc2.selectionEnd } : (doc2 = (doc2.ownerDocument && doc2.ownerDocument.defaultView || window).getSelection(), doc2 = {
        anchorNode: doc2.anchorNode,
        anchorOffset: doc2.anchorOffset,
        focusNode: doc2.focusNode,
        focusOffset: doc2.focusOffset
      }), lastSelection && shallowEqual(lastSelection, doc2) || (lastSelection = doc2, doc2 = accumulateTwoPhaseListeners(activeElementInst, "onSelect"), 0 < doc2.length && (nativeEvent = new SyntheticEvent(
        "onSelect",
        "select",
        null,
        nativeEvent,
        nativeEventTarget
      ), dispatchQueue.push({ event: nativeEvent, listeners: doc2 }), nativeEvent.target = activeElement)));
    }
    function makePrefixMap(styleProp, eventName) {
      var prefixes = {};
      prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
      prefixes["Webkit" + styleProp] = "webkit" + eventName;
      prefixes["Moz" + styleProp] = "moz" + eventName;
      return prefixes;
    }
    var vendorPrefixes = {
      animationend: makePrefixMap("Animation", "AnimationEnd"),
      animationiteration: makePrefixMap("Animation", "AnimationIteration"),
      animationstart: makePrefixMap("Animation", "AnimationStart"),
      transitionrun: makePrefixMap("Transition", "TransitionRun"),
      transitionstart: makePrefixMap("Transition", "TransitionStart"),
      transitioncancel: makePrefixMap("Transition", "TransitionCancel"),
      transitionend: makePrefixMap("Transition", "TransitionEnd")
    }, prefixedEventNames = {}, style$1 = {};
    canUseDOM && (style$1 = document.createElement("div").style, "AnimationEvent" in window || (delete vendorPrefixes.animationend.animation, delete vendorPrefixes.animationiteration.animation, delete vendorPrefixes.animationstart.animation), "TransitionEvent" in window || delete vendorPrefixes.transitionend.transition);
    function getVendorPrefixedEventName(eventName) {
      if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];
      if (!vendorPrefixes[eventName]) return eventName;
      var prefixMap = vendorPrefixes[eventName], styleProp;
      for (styleProp in prefixMap)
        if (prefixMap.hasOwnProperty(styleProp) && styleProp in style$1)
          return prefixedEventNames[eventName] = prefixMap[styleProp];
      return eventName;
    }
    var ANIMATION_END = getVendorPrefixedEventName("animationend"), ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration"), ANIMATION_START = getVendorPrefixedEventName("animationstart"), TRANSITION_RUN = getVendorPrefixedEventName("transitionrun"), TRANSITION_START = getVendorPrefixedEventName("transitionstart"), TRANSITION_CANCEL = getVendorPrefixedEventName("transitioncancel"), TRANSITION_END = getVendorPrefixedEventName("transitionend"), topLevelEventsToReactNames = /* @__PURE__ */ new Map(), simpleEventPluginEvents = "abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll scrollEnd toggle touchMove waiting wheel".split(
      " "
    );
    function registerSimpleEvent(domEventName, reactName) {
      topLevelEventsToReactNames.set(domEventName, reactName);
      registerTwoPhaseEvent(reactName, [domEventName]);
    }
    var concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0;
    function finishQueueingConcurrentUpdates() {
      for (var endIndex = concurrentQueuesIndex, i2 = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i2 < endIndex; ) {
        var fiber = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        var queue = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        var update = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        var lane = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        if (null !== queue && null !== update) {
          var pending = queue.pending;
          null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
          queue.pending = update;
        }
        0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update, lane);
      }
    }
    function enqueueUpdate$1(fiber, queue, update, lane) {
      concurrentQueues[concurrentQueuesIndex++] = fiber;
      concurrentQueues[concurrentQueuesIndex++] = queue;
      concurrentQueues[concurrentQueuesIndex++] = update;
      concurrentQueues[concurrentQueuesIndex++] = lane;
      concurrentlyUpdatedLanes |= lane;
      fiber.lanes |= lane;
      fiber = fiber.alternate;
      null !== fiber && (fiber.lanes |= lane);
    }
    function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
      enqueueUpdate$1(fiber, queue, update, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function enqueueConcurrentRenderForLane(fiber, lane) {
      enqueueUpdate$1(fiber, null, null, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
      sourceFiber.lanes |= lane;
      var alternate = sourceFiber.alternate;
      null !== alternate && (alternate.lanes |= lane);
      for (var isHidden = false, parent = sourceFiber.return; null !== parent; )
        parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & 1 || (isHidden = true)), sourceFiber = parent, parent = parent.return;
      isHidden && null !== update && 3 === sourceFiber.tag && (parent = sourceFiber.stateNode, isHidden = 31 - clz32(lane), parent = parent.hiddenUpdates, sourceFiber = parent[isHidden], null === sourceFiber ? parent[isHidden] = [update] : sourceFiber.push(update), update.lane = lane | 536870912);
    }
    function getRootForUpdatedFiber(sourceFiber) {
      if (50 < nestedUpdateCount)
        throw nestedUpdateCount = 0, rootWithNestedUpdates = null, Error(formatProdErrorMessage(185));
      for (var parent = sourceFiber.return; null !== parent; )
        sourceFiber = parent, parent = sourceFiber.return;
      return 3 === sourceFiber.tag ? sourceFiber.stateNode : null;
    }
    var emptyContextObject = {}, CapturedStacks = /* @__PURE__ */ new WeakMap();
    function createCapturedValueAtFiber(value2, source2) {
      if ("object" === typeof value2 && null !== value2) {
        var existing = CapturedStacks.get(value2);
        if (void 0 !== existing) return existing;
        source2 = {
          value: value2,
          source: source2,
          stack: getStackByFiberInDevAndProd(source2)
        };
        CapturedStacks.set(value2, source2);
        return source2;
      }
      return {
        value: value2,
        source: source2,
        stack: getStackByFiberInDevAndProd(source2)
      };
    }
    var forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "";
    function pushTreeFork(workInProgress2, totalChildren) {
      forkStack[forkStackIndex++] = treeForkCount;
      forkStack[forkStackIndex++] = treeForkProvider;
      treeForkProvider = workInProgress2;
      treeForkCount = totalChildren;
    }
    function pushTreeId(workInProgress2, totalChildren, index2) {
      idStack[idStackIndex++] = treeContextId;
      idStack[idStackIndex++] = treeContextOverflow;
      idStack[idStackIndex++] = treeContextProvider;
      treeContextProvider = workInProgress2;
      var baseIdWithLeadingBit = treeContextId;
      workInProgress2 = treeContextOverflow;
      var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
      baseIdWithLeadingBit &= ~(1 << baseLength);
      index2 += 1;
      var length = 32 - clz32(totalChildren) + baseLength;
      if (30 < length) {
        var numberOfOverflowBits = baseLength - baseLength % 5;
        length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
        baseIdWithLeadingBit >>= numberOfOverflowBits;
        baseLength -= numberOfOverflowBits;
        treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index2 << baseLength | baseIdWithLeadingBit;
        treeContextOverflow = length + workInProgress2;
      } else
        treeContextId = 1 << length | index2 << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
    }
    function pushMaterializedTreeId(workInProgress2) {
      null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
    }
    function popTreeContext(workInProgress2) {
      for (; workInProgress2 === treeForkProvider; )
        treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
      for (; workInProgress2 === treeContextProvider; )
        treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
    }
    var hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(formatProdErrorMessage(519));
    function throwOnHydrationMismatch(fiber) {
      var error2 = Error(formatProdErrorMessage(418, ""));
      queueHydrationError(createCapturedValueAtFiber(error2, fiber));
      throw HydrationMismatchException;
    }
    function prepareToHydrateHostInstance(fiber) {
      var instance = fiber.stateNode, type = fiber.type, props = fiber.memoizedProps;
      instance[internalInstanceKey] = fiber;
      instance[internalPropsKey] = props;
      switch (type) {
        case "dialog":
          listenToNonDelegatedEvent("cancel", instance);
          listenToNonDelegatedEvent("close", instance);
          break;
        case "iframe":
        case "object":
        case "embed":
          listenToNonDelegatedEvent("load", instance);
          break;
        case "video":
        case "audio":
          for (type = 0; type < mediaEventTypes.length; type++)
            listenToNonDelegatedEvent(mediaEventTypes[type], instance);
          break;
        case "source":
          listenToNonDelegatedEvent("error", instance);
          break;
        case "img":
        case "image":
        case "link":
          listenToNonDelegatedEvent("error", instance);
          listenToNonDelegatedEvent("load", instance);
          break;
        case "details":
          listenToNonDelegatedEvent("toggle", instance);
          break;
        case "input":
          listenToNonDelegatedEvent("invalid", instance);
          initInput(
            instance,
            props.value,
            props.defaultValue,
            props.checked,
            props.defaultChecked,
            props.type,
            props.name,
            true
          );
          track(instance);
          break;
        case "select":
          listenToNonDelegatedEvent("invalid", instance);
          break;
        case "textarea":
          listenToNonDelegatedEvent("invalid", instance), initTextarea(instance, props.value, props.defaultValue, props.children), track(instance);
      }
      type = props.children;
      "string" !== typeof type && "number" !== typeof type && "bigint" !== typeof type || instance.textContent === "" + type || true === props.suppressHydrationWarning || checkForUnmatchedText(instance.textContent, type) ? (null != props.popover && (listenToNonDelegatedEvent("beforetoggle", instance), listenToNonDelegatedEvent("toggle", instance)), null != props.onScroll && listenToNonDelegatedEvent("scroll", instance), null != props.onScrollEnd && listenToNonDelegatedEvent("scrollend", instance), null != props.onClick && (instance.onclick = noop$1), instance = true) : instance = false;
      instance || throwOnHydrationMismatch(fiber);
    }
    function popToNextHostParent(fiber) {
      for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
        switch (hydrationParentFiber.tag) {
          case 3:
          case 27:
            rootOrSingletonContext = true;
            return;
          case 5:
          case 13:
            rootOrSingletonContext = false;
            return;
          default:
            hydrationParentFiber = hydrationParentFiber.return;
        }
    }
    function popHydrationState(fiber) {
      if (fiber !== hydrationParentFiber) return false;
      if (!isHydrating) return popToNextHostParent(fiber), isHydrating = true, false;
      var shouldClear = false, JSCompiler_temp;
      if (JSCompiler_temp = 3 !== fiber.tag && 27 !== fiber.tag) {
        if (JSCompiler_temp = 5 === fiber.tag)
          JSCompiler_temp = fiber.type, JSCompiler_temp = !("form" !== JSCompiler_temp && "button" !== JSCompiler_temp) || shouldSetTextContent(fiber.type, fiber.memoizedProps);
        JSCompiler_temp = !JSCompiler_temp;
      }
      JSCompiler_temp && (shouldClear = true);
      shouldClear && nextHydratableInstance && throwOnHydrationMismatch(fiber);
      popToNextHostParent(fiber);
      if (13 === fiber.tag) {
        fiber = fiber.memoizedState;
        fiber = null !== fiber ? fiber.dehydrated : null;
        if (!fiber) throw Error(formatProdErrorMessage(317));
        a: {
          fiber = fiber.nextSibling;
          for (shouldClear = 0; fiber; ) {
            if (8 === fiber.nodeType)
              if (JSCompiler_temp = fiber.data, "/$" === JSCompiler_temp) {
                if (0 === shouldClear) {
                  nextHydratableInstance = getNextHydratable(fiber.nextSibling);
                  break a;
                }
                shouldClear--;
              } else
                "$" !== JSCompiler_temp && "$!" !== JSCompiler_temp && "$?" !== JSCompiler_temp || shouldClear++;
            fiber = fiber.nextSibling;
          }
          nextHydratableInstance = null;
        }
      } else
        nextHydratableInstance = hydrationParentFiber ? getNextHydratable(fiber.stateNode.nextSibling) : null;
      return true;
    }
    function resetHydrationState() {
      nextHydratableInstance = hydrationParentFiber = null;
      isHydrating = false;
    }
    function queueHydrationError(error2) {
      null === hydrationErrors ? hydrationErrors = [error2] : hydrationErrors.push(error2);
    }
    var SuspenseException = Error(formatProdErrorMessage(460)), SuspenseyCommitException = Error(formatProdErrorMessage(474)), noopSuspenseyCommitThenable = { then: function() {
    } };
    function isThenableResolved(thenable) {
      thenable = thenable.status;
      return "fulfilled" === thenable || "rejected" === thenable;
    }
    function noop$3() {
    }
    function trackUsedThenable(thenableState2, thenable, index2) {
      index2 = thenableState2[index2];
      void 0 === index2 ? thenableState2.push(thenable) : index2 !== thenable && (thenable.then(noop$3, noop$3), thenable = index2);
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          thenableState2 = thenable.reason;
          if (thenableState2 === SuspenseException)
            throw Error(formatProdErrorMessage(483));
          throw thenableState2;
        default:
          if ("string" === typeof thenable.status) thenable.then(noop$3, noop$3);
          else {
            thenableState2 = workInProgressRoot;
            if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
              throw Error(formatProdErrorMessage(482));
            thenableState2 = thenable;
            thenableState2.status = "pending";
            thenableState2.then(
              function(fulfilledValue) {
                if ("pending" === thenable.status) {
                  var fulfilledThenable = thenable;
                  fulfilledThenable.status = "fulfilled";
                  fulfilledThenable.value = fulfilledValue;
                }
              },
              function(error2) {
                if ("pending" === thenable.status) {
                  var rejectedThenable = thenable;
                  rejectedThenable.status = "rejected";
                  rejectedThenable.reason = error2;
                }
              }
            );
          }
          switch (thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              thenableState2 = thenable.reason;
              if (thenableState2 === SuspenseException)
                throw Error(formatProdErrorMessage(483));
              throw thenableState2;
          }
          suspendedThenable = thenable;
          throw SuspenseException;
      }
    }
    var suspendedThenable = null;
    function getSuspendedThenable() {
      if (null === suspendedThenable) throw Error(formatProdErrorMessage(459));
      var thenable = suspendedThenable;
      suspendedThenable = null;
      return thenable;
    }
    var thenableState$1 = null, thenableIndexCounter$1 = 0;
    function unwrapThenable(thenable) {
      var index2 = thenableIndexCounter$1;
      thenableIndexCounter$1 += 1;
      null === thenableState$1 && (thenableState$1 = []);
      return trackUsedThenable(thenableState$1, thenable, index2);
    }
    function coerceRef(workInProgress2, element) {
      element = element.props.ref;
      workInProgress2.ref = void 0 !== element ? element : null;
    }
    function throwOnInvalidObjectType(returnFiber, newChild) {
      if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
        throw Error(formatProdErrorMessage(525));
      returnFiber = Object.prototype.toString.call(newChild);
      throw Error(
        formatProdErrorMessage(
          31,
          "[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber
        )
      );
    }
    function resolveLazy(lazyType) {
      var init = lazyType._init;
      return init(lazyType._payload);
    }
    function createChildReconciler(shouldTrackSideEffects) {
      function deleteChild(returnFiber, childToDelete) {
        if (shouldTrackSideEffects) {
          var deletions = returnFiber.deletions;
          null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
        }
      }
      function deleteRemainingChildren(returnFiber, currentFirstChild) {
        if (!shouldTrackSideEffects) return null;
        for (; null !== currentFirstChild; )
          deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
        return null;
      }
      function mapRemainingChildren(currentFirstChild) {
        for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
          null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
        return existingChildren;
      }
      function useFiber(fiber, pendingProps) {
        fiber = createWorkInProgress(fiber, pendingProps);
        fiber.index = 0;
        fiber.sibling = null;
        return fiber;
      }
      function placeChild(newFiber, lastPlacedIndex, newIndex) {
        newFiber.index = newIndex;
        if (!shouldTrackSideEffects)
          return newFiber.flags |= 1048576, lastPlacedIndex;
        newIndex = newFiber.alternate;
        if (null !== newIndex)
          return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 33554434, lastPlacedIndex) : newIndex;
        newFiber.flags |= 33554434;
        return lastPlacedIndex;
      }
      function placeSingleChild(newFiber) {
        shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 33554434);
        return newFiber;
      }
      function updateTextNode(returnFiber, current, textContent, lanes) {
        if (null === current || 6 !== current.tag)
          return current = createFiberFromText(textContent, returnFiber.mode, lanes), current.return = returnFiber, current;
        current = useFiber(current, textContent);
        current.return = returnFiber;
        return current;
      }
      function updateElement(returnFiber, current, element, lanes) {
        var elementType = element.type;
        if (elementType === REACT_FRAGMENT_TYPE)
          return updateFragment(
            returnFiber,
            current,
            element.props.children,
            lanes,
            element.key
          );
        if (null !== current && (current.elementType === elementType || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type))
          return current = useFiber(current, element.props), coerceRef(current, element), current.return = returnFiber, current;
        current = createFiberFromTypeAndProps(
          element.type,
          element.key,
          element.props,
          null,
          returnFiber.mode,
          lanes
        );
        coerceRef(current, element);
        current.return = returnFiber;
        return current;
      }
      function updatePortal(returnFiber, current, portal, lanes) {
        if (null === current || 4 !== current.tag || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation)
          return current = createFiberFromPortal(portal, returnFiber.mode, lanes), current.return = returnFiber, current;
        current = useFiber(current, portal.children || []);
        current.return = returnFiber;
        return current;
      }
      function updateFragment(returnFiber, current, fragment, lanes, key2) {
        if (null === current || 7 !== current.tag)
          return current = createFiberFromFragment(
            fragment,
            returnFiber.mode,
            lanes,
            key2
          ), current.return = returnFiber, current;
        current = useFiber(current, fragment);
        current.return = returnFiber;
        return current;
      }
      function createChild(returnFiber, newChild, lanes) {
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return newChild = createFiberFromText(
            "" + newChild,
            returnFiber.mode,
            lanes
          ), newChild.return = returnFiber, newChild;
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return lanes = createFiberFromTypeAndProps(
                newChild.type,
                newChild.key,
                newChild.props,
                null,
                returnFiber.mode,
                lanes
              ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes;
            case REACT_PORTAL_TYPE:
              return newChild = createFiberFromPortal(
                newChild,
                returnFiber.mode,
                lanes
              ), newChild.return = returnFiber, newChild;
            case REACT_LAZY_TYPE:
              var init = newChild._init;
              newChild = init(newChild._payload);
              return createChild(returnFiber, newChild, lanes);
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild))
            return newChild = createFiberFromFragment(
              newChild,
              returnFiber.mode,
              lanes,
              null
            ), newChild.return = returnFiber, newChild;
          if ("function" === typeof newChild.then)
            return createChild(returnFiber, unwrapThenable(newChild), lanes);
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return createChild(
              returnFiber,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        return null;
      }
      function updateSlot(returnFiber, oldFiber, newChild, lanes) {
        var key2 = null !== oldFiber ? oldFiber.key : null;
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return null !== key2 ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return newChild.key === key2 ? updateElement(returnFiber, oldFiber, newChild, lanes) : null;
            case REACT_PORTAL_TYPE:
              return newChild.key === key2 ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
            case REACT_LAZY_TYPE:
              return key2 = newChild._init, newChild = key2(newChild._payload), updateSlot(returnFiber, oldFiber, newChild, lanes);
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild))
            return null !== key2 ? null : updateFragment(returnFiber, oldFiber, newChild, lanes, null);
          if ("function" === typeof newChild.then)
            return updateSlot(
              returnFiber,
              oldFiber,
              unwrapThenable(newChild),
              lanes
            );
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return updateSlot(
              returnFiber,
              oldFiber,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        return null;
      }
      function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return existingChildren = existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null, updateElement(returnFiber, existingChildren, newChild, lanes);
            case REACT_PORTAL_TYPE:
              return existingChildren = existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
            case REACT_LAZY_TYPE:
              var init = newChild._init;
              newChild = init(newChild._payload);
              return updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                newChild,
                lanes
              );
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild))
            return existingChildren = existingChildren.get(newIdx) || null, updateFragment(returnFiber, existingChildren, newChild, lanes, null);
          if ("function" === typeof newChild.then)
            return updateFromMap(
              existingChildren,
              returnFiber,
              newIdx,
              unwrapThenable(newChild),
              lanes
            );
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return updateFromMap(
              existingChildren,
              returnFiber,
              newIdx,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        return null;
      }
      function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
        for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
          oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
          var newFiber = updateSlot(
            returnFiber,
            oldFiber,
            newChildren[newIdx],
            lanes
          );
          if (null === newFiber) {
            null === oldFiber && (oldFiber = nextOldFiber);
            break;
          }
          shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
          currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
          null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }
        if (newIdx === newChildren.length)
          return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
        if (null === oldFiber) {
          for (; newIdx < newChildren.length; newIdx++)
            oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (currentFirstChild = placeChild(
              oldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
          nextOldFiber = updateFromMap(
            oldFiber,
            returnFiber,
            newIdx,
            newChildren[newIdx],
            lanes
          ), null !== nextOldFiber && (shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
            null === nextOldFiber.key ? newIdx : nextOldFiber.key
          ), currentFirstChild = placeChild(
            nextOldFiber,
            currentFirstChild,
            newIdx
          ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
        shouldTrackSideEffects && oldFiber.forEach(function(child) {
          return deleteChild(returnFiber, child);
        });
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
        if (null == newChildren) throw Error(formatProdErrorMessage(151));
        for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
          oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
          var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
          if (null === newFiber) {
            null === oldFiber && (oldFiber = nextOldFiber);
            break;
          }
          shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
          currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
          null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }
        if (step.done)
          return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
        if (null === oldFiber) {
          for (; !step.done; newIdx++, step = newChildren.next())
            step = createChild(returnFiber, step.value, lanes), null !== step && (currentFirstChild = placeChild(step, currentFirstChild, newIdx), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
          step = updateFromMap(oldFiber, returnFiber, newIdx, step.value, lanes), null !== step && (shouldTrackSideEffects && null !== step.alternate && oldFiber.delete(null === step.key ? newIdx : step.key), currentFirstChild = placeChild(step, currentFirstChild, newIdx), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
        shouldTrackSideEffects && oldFiber.forEach(function(child) {
          return deleteChild(returnFiber, child);
        });
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
        "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (newChild = newChild.props.children);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              a: {
                for (var key2 = newChild.key; null !== currentFirstChild; ) {
                  if (currentFirstChild.key === key2) {
                    key2 = newChild.type;
                    if (key2 === REACT_FRAGMENT_TYPE) {
                      if (7 === currentFirstChild.tag) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(
                          currentFirstChild,
                          newChild.props.children
                        );
                        lanes.return = returnFiber;
                        returnFiber = lanes;
                        break a;
                      }
                    } else if (currentFirstChild.elementType === key2 || "object" === typeof key2 && null !== key2 && key2.$$typeof === REACT_LAZY_TYPE && resolveLazy(key2) === currentFirstChild.type) {
                      deleteRemainingChildren(
                        returnFiber,
                        currentFirstChild.sibling
                      );
                      lanes = useFiber(currentFirstChild, newChild.props);
                      coerceRef(lanes, newChild);
                      lanes.return = returnFiber;
                      returnFiber = lanes;
                      break a;
                    }
                    deleteRemainingChildren(returnFiber, currentFirstChild);
                    break;
                  } else deleteChild(returnFiber, currentFirstChild);
                  currentFirstChild = currentFirstChild.sibling;
                }
                newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
                  newChild.props.children,
                  returnFiber.mode,
                  lanes,
                  newChild.key
                ), lanes.return = returnFiber, returnFiber = lanes) : (lanes = createFiberFromTypeAndProps(
                  newChild.type,
                  newChild.key,
                  newChild.props,
                  null,
                  returnFiber.mode,
                  lanes
                ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = lanes);
              }
              return placeSingleChild(returnFiber);
            case REACT_PORTAL_TYPE:
              a: {
                for (key2 = newChild.key; null !== currentFirstChild; ) {
                  if (currentFirstChild.key === key2)
                    if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === newChild.containerInfo && currentFirstChild.stateNode.implementation === newChild.implementation) {
                      deleteRemainingChildren(
                        returnFiber,
                        currentFirstChild.sibling
                      );
                      lanes = useFiber(currentFirstChild, newChild.children || []);
                      lanes.return = returnFiber;
                      returnFiber = lanes;
                      break a;
                    } else {
                      deleteRemainingChildren(returnFiber, currentFirstChild);
                      break;
                    }
                  else deleteChild(returnFiber, currentFirstChild);
                  currentFirstChild = currentFirstChild.sibling;
                }
                lanes = createFiberFromPortal(newChild, returnFiber.mode, lanes);
                lanes.return = returnFiber;
                returnFiber = lanes;
              }
              return placeSingleChild(returnFiber);
            case REACT_LAZY_TYPE:
              return key2 = newChild._init, newChild = key2(newChild._payload), reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                newChild,
                lanes
              );
          }
          if (isArrayImpl(newChild))
            return reconcileChildrenArray(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            );
          if (getIteratorFn(newChild)) {
            key2 = getIteratorFn(newChild);
            if ("function" !== typeof key2) throw Error(formatProdErrorMessage(150));
            newChild = key2.call(newChild);
            return reconcileChildrenIterator(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            );
          }
          if ("function" === typeof newChild.then)
            return reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              unwrapThenable(newChild),
              lanes
            );
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        return "string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild ? (newChild = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(returnFiber, currentFirstChild.sibling), lanes = useFiber(currentFirstChild, newChild), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(newChild, returnFiber.mode, lanes), lanes.return = returnFiber, returnFiber = lanes), placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild);
      }
      return function(returnFiber, currentFirstChild, newChild, lanes) {
        try {
          thenableIndexCounter$1 = 0;
          var firstChildFiber = reconcileChildFibersImpl(
            returnFiber,
            currentFirstChild,
            newChild,
            lanes
          );
          thenableState$1 = null;
          return firstChildFiber;
        } catch (x2) {
          if (x2 === SuspenseException) throw x2;
          var fiber = createFiberImplClass(29, x2, null, returnFiber.mode);
          fiber.lanes = lanes;
          fiber.return = returnFiber;
          return fiber;
        } finally {
        }
      };
    }
    var reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0);
    function pushHiddenContext(fiber, context) {
      fiber = entangledRenderLanes;
      push$1(prevEntangledRenderLanesCursor, fiber);
      push$1(currentTreeHiddenStackCursor, context);
      entangledRenderLanes = fiber | context.baseLanes;
    }
    function reuseHiddenContextOnStack() {
      push$1(prevEntangledRenderLanesCursor, entangledRenderLanes);
      push$1(currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current);
    }
    function popHiddenContext() {
      entangledRenderLanes = prevEntangledRenderLanesCursor.current;
      pop$1(currentTreeHiddenStackCursor);
      pop$1(prevEntangledRenderLanesCursor);
    }
    var suspenseHandlerStackCursor = createCursor(null), shellBoundary = null;
    function pushPrimaryTreeSuspenseHandler(handler) {
      var current = handler.alternate;
      push$1(suspenseStackCursor, suspenseStackCursor.current & 1);
      push$1(suspenseHandlerStackCursor, handler);
      null === shellBoundary && (null === current || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current.memoizedState && (shellBoundary = handler));
    }
    function pushOffscreenSuspenseHandler(fiber) {
      if (22 === fiber.tag) {
        if (push$1(suspenseStackCursor, suspenseStackCursor.current), push$1(suspenseHandlerStackCursor, fiber), null === shellBoundary) {
          var current = fiber.alternate;
          null !== current && null !== current.memoizedState && (shellBoundary = fiber);
        }
      } else reuseSuspenseHandlerOnStack();
    }
    function reuseSuspenseHandlerOnStack() {
      push$1(suspenseStackCursor, suspenseStackCursor.current);
      push$1(suspenseHandlerStackCursor, suspenseHandlerStackCursor.current);
    }
    function popSuspenseHandler(fiber) {
      pop$1(suspenseHandlerStackCursor);
      shellBoundary === fiber && (shellBoundary = null);
      pop$1(suspenseStackCursor);
    }
    var suspenseStackCursor = createCursor(0);
    function findFirstSuspended(row2) {
      for (var node2 = row2; null !== node2; ) {
        if (13 === node2.tag) {
          var state = node2.memoizedState;
          if (null !== state && (state = state.dehydrated, null === state || "$?" === state.data || "$!" === state.data))
            return node2;
        } else if (19 === node2.tag && void 0 !== node2.memoizedProps.revealOrder) {
          if (0 !== (node2.flags & 128)) return node2;
        } else if (null !== node2.child) {
          node2.child.return = node2;
          node2 = node2.child;
          continue;
        }
        if (node2 === row2) break;
        for (; null === node2.sibling; ) {
          if (null === node2.return || node2.return === row2) return null;
          node2 = node2.return;
        }
        node2.sibling.return = node2.return;
        node2 = node2.sibling;
      }
      return null;
    }
    var AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
      var listeners = [], signal = this.signal = {
        aborted: false,
        addEventListener: function(type, listener) {
          listeners.push(listener);
        }
      };
      this.abort = function() {
        signal.aborted = true;
        listeners.forEach(function(listener) {
          return listener();
        });
      };
    }, scheduleCallback$2 = Scheduler.unstable_scheduleCallback, NormalPriority = Scheduler.unstable_NormalPriority, CacheContext = {
      $$typeof: REACT_CONTEXT_TYPE,
      Consumer: null,
      Provider: null,
      _currentValue: null,
      _currentValue2: null,
      _threadCount: 0
    };
    function createCache() {
      return {
        controller: new AbortControllerLocal(),
        data: /* @__PURE__ */ new Map(),
        refCount: 0
      };
    }
    function releaseCache(cache) {
      cache.refCount--;
      0 === cache.refCount && scheduleCallback$2(NormalPriority, function() {
        cache.controller.abort();
      });
    }
    var currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null;
    function entangleAsyncAction(transition, thenable) {
      if (null === currentEntangledListeners) {
        var entangledListeners = currentEntangledListeners = [];
        currentEntangledPendingCount = 0;
        currentEntangledLane = requestTransitionLane();
        currentEntangledActionThenable = {
          status: "pending",
          value: void 0,
          then: function(resolve) {
            entangledListeners.push(resolve);
          }
        };
      }
      currentEntangledPendingCount++;
      thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
      return thenable;
    }
    function pingEngtangledActionScope() {
      if (0 === --currentEntangledPendingCount && null !== currentEntangledListeners) {
        null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
        var listeners = currentEntangledListeners;
        currentEntangledListeners = null;
        currentEntangledLane = 0;
        currentEntangledActionThenable = null;
        for (var i2 = 0; i2 < listeners.length; i2++) (0, listeners[i2])();
      }
    }
    function chainThenableValue(thenable, result2) {
      var listeners = [], thenableWithOverride = {
        status: "pending",
        value: null,
        reason: null,
        then: function(resolve) {
          listeners.push(resolve);
        }
      };
      thenable.then(
        function() {
          thenableWithOverride.status = "fulfilled";
          thenableWithOverride.value = result2;
          for (var i2 = 0; i2 < listeners.length; i2++) (0, listeners[i2])(result2);
        },
        function(error2) {
          thenableWithOverride.status = "rejected";
          thenableWithOverride.reason = error2;
          for (error2 = 0; error2 < listeners.length; error2++)
            (0, listeners[error2])(void 0);
        }
      );
      return thenableWithOverride;
    }
    var prevOnStartTransitionFinish = ReactSharedInternals.S;
    ReactSharedInternals.S = function(transition, returnValue) {
      "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && entangleAsyncAction(transition, returnValue);
      null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
    };
    var resumedCache = createCursor(null);
    function peekCacheFromPool() {
      var cacheResumedFromPreviousRender = resumedCache.current;
      return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
    }
    function pushTransition(offscreenWorkInProgress, prevCachePool) {
      null === prevCachePool ? push$1(resumedCache, resumedCache.current) : push$1(resumedCache, prevCachePool.pool);
    }
    function getSuspendedCache() {
      var cacheFromPool = peekCacheFromPool();
      return null === cacheFromPool ? null : { parent: CacheContext._currentValue, pool: cacheFromPool };
    }
    var renderLanes = 0, currentlyRenderingFiber$1 = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter = 0, thenableState = null, globalClientIdCounter = 0;
    function throwInvalidHookError() {
      throw Error(formatProdErrorMessage(321));
    }
    function areHookInputsEqual(nextDeps, prevDeps) {
      if (null === prevDeps) return false;
      for (var i2 = 0; i2 < prevDeps.length && i2 < nextDeps.length; i2++)
        if (!objectIs(nextDeps[i2], prevDeps[i2])) return false;
      return true;
    }
    function renderWithHooks(current, workInProgress2, Component2, props, secondArg, nextRenderLanes) {
      renderLanes = nextRenderLanes;
      currentlyRenderingFiber$1 = workInProgress2;
      workInProgress2.memoizedState = null;
      workInProgress2.updateQueue = null;
      workInProgress2.lanes = 0;
      ReactSharedInternals.H = null === current || null === current.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate;
      shouldDoubleInvokeUserFnsInHooksDEV = false;
      nextRenderLanes = Component2(props, secondArg);
      shouldDoubleInvokeUserFnsInHooksDEV = false;
      didScheduleRenderPhaseUpdateDuringThisPass && (nextRenderLanes = renderWithHooksAgain(
        workInProgress2,
        Component2,
        props,
        secondArg
      ));
      finishRenderingHooks(current);
      return nextRenderLanes;
    }
    function finishRenderingHooks(current) {
      ReactSharedInternals.H = ContextOnlyDispatcher;
      var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
      renderLanes = 0;
      workInProgressHook = currentHook = currentlyRenderingFiber$1 = null;
      didScheduleRenderPhaseUpdate = false;
      thenableIndexCounter = 0;
      thenableState = null;
      if (didRenderTooFewHooks) throw Error(formatProdErrorMessage(300));
      null === current || didReceiveUpdate || (current = current.dependencies, null !== current && checkIfContextChanged(current) && (didReceiveUpdate = true));
    }
    function renderWithHooksAgain(workInProgress2, Component2, props, secondArg) {
      currentlyRenderingFiber$1 = workInProgress2;
      var numberOfReRenders = 0;
      do {
        didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
        thenableIndexCounter = 0;
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        if (25 <= numberOfReRenders) throw Error(formatProdErrorMessage(301));
        numberOfReRenders += 1;
        workInProgressHook = currentHook = null;
        if (null != workInProgress2.updateQueue) {
          var children2 = workInProgress2.updateQueue;
          children2.lastEffect = null;
          children2.events = null;
          children2.stores = null;
          null != children2.memoCache && (children2.memoCache.index = 0);
        }
        ReactSharedInternals.H = HooksDispatcherOnRerender;
        children2 = Component2(props, secondArg);
      } while (didScheduleRenderPhaseUpdateDuringThisPass);
      return children2;
    }
    function TransitionAwareHostComponent() {
      var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
      maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
      dispatcher = dispatcher.useState()[0];
      (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber$1.flags |= 1024);
      return maybeThenable;
    }
    function checkDidRenderIdHook() {
      var didRenderIdHook = 0 !== localIdCounter;
      localIdCounter = 0;
      return didRenderIdHook;
    }
    function bailoutHooks(current, workInProgress2, lanes) {
      workInProgress2.updateQueue = current.updateQueue;
      workInProgress2.flags &= -2053;
      current.lanes &= ~lanes;
    }
    function resetHooksOnUnwind(workInProgress2) {
      if (didScheduleRenderPhaseUpdate) {
        for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
          var queue = workInProgress2.queue;
          null !== queue && (queue.pending = null);
          workInProgress2 = workInProgress2.next;
        }
        didScheduleRenderPhaseUpdate = false;
      }
      renderLanes = 0;
      workInProgressHook = currentHook = currentlyRenderingFiber$1 = null;
      didScheduleRenderPhaseUpdateDuringThisPass = false;
      thenableIndexCounter = localIdCounter = 0;
      thenableState = null;
    }
    function mountWorkInProgressHook() {
      var hook = {
        memoizedState: null,
        baseState: null,
        baseQueue: null,
        queue: null,
        next: null
      };
      null === workInProgressHook ? currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
      return workInProgressHook;
    }
    function updateWorkInProgressHook() {
      if (null === currentHook) {
        var nextCurrentHook = currentlyRenderingFiber$1.alternate;
        nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
      } else nextCurrentHook = currentHook.next;
      var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber$1.memoizedState : workInProgressHook.next;
      if (null !== nextWorkInProgressHook)
        workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
      else {
        if (null === nextCurrentHook) {
          if (null === currentlyRenderingFiber$1.alternate)
            throw Error(formatProdErrorMessage(467));
          throw Error(formatProdErrorMessage(310));
        }
        currentHook = nextCurrentHook;
        nextCurrentHook = {
          memoizedState: currentHook.memoizedState,
          baseState: currentHook.baseState,
          baseQueue: currentHook.baseQueue,
          queue: currentHook.queue,
          next: null
        };
        null === workInProgressHook ? currentlyRenderingFiber$1.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
      }
      return workInProgressHook;
    }
    var createFunctionComponentUpdateQueue;
    createFunctionComponentUpdateQueue = function() {
      return { lastEffect: null, events: null, stores: null, memoCache: null };
    };
    function useThenable(thenable) {
      var index2 = thenableIndexCounter;
      thenableIndexCounter += 1;
      null === thenableState && (thenableState = []);
      thenable = trackUsedThenable(thenableState, thenable, index2);
      index2 = currentlyRenderingFiber$1;
      null === (null === workInProgressHook ? index2.memoizedState : workInProgressHook.next) && (index2 = index2.alternate, ReactSharedInternals.H = null === index2 || null === index2.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate);
      return thenable;
    }
    function use$1(usable) {
      if (null !== usable && "object" === typeof usable) {
        if ("function" === typeof usable.then) return useThenable(usable);
        if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
      }
      throw Error(formatProdErrorMessage(438, String(usable)));
    }
    function useMemoCache(size) {
      var memoCache = null, updateQueue = currentlyRenderingFiber$1.updateQueue;
      null !== updateQueue && (memoCache = updateQueue.memoCache);
      if (null == memoCache) {
        var current = currentlyRenderingFiber$1.alternate;
        null !== current && (current = current.updateQueue, null !== current && (current = current.memoCache, null != current && (memoCache = {
          data: current.data.map(function(array) {
            return array.slice();
          }),
          index: 0
        })));
      }
      null == memoCache && (memoCache = { data: [], index: 0 });
      null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber$1.updateQueue = updateQueue);
      updateQueue.memoCache = memoCache;
      updateQueue = memoCache.data[memoCache.index];
      if (void 0 === updateQueue)
        for (updateQueue = memoCache.data[memoCache.index] = Array(size), current = 0; current < size; current++)
          updateQueue[current] = REACT_MEMO_CACHE_SENTINEL;
      memoCache.index++;
      return updateQueue;
    }
    function basicStateReducer(state, action) {
      return "function" === typeof action ? action(state) : action;
    }
    function updateReducer(reducer) {
      var hook = updateWorkInProgressHook();
      return updateReducerImpl(hook, currentHook, reducer);
    }
    function updateReducerImpl(hook, current, reducer) {
      var queue = hook.queue;
      if (null === queue) throw Error(formatProdErrorMessage(311));
      queue.lastRenderedReducer = reducer;
      var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
      if (null !== pendingQueue) {
        if (null !== baseQueue) {
          var baseFirst = baseQueue.next;
          baseQueue.next = pendingQueue.next;
          pendingQueue.next = baseFirst;
        }
        current.baseQueue = baseQueue = pendingQueue;
        queue.pending = null;
      }
      pendingQueue = hook.baseState;
      if (null === baseQueue) hook.memoizedState = pendingQueue;
      else {
        current = baseQueue.next;
        var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update = current, didReadFromEntangledAsyncAction$54 = false;
        do {
          var updateLane = update.lane & -536870913;
          if (updateLane !== update.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
            var revertLane = update.revertLane;
            if (0 === revertLane)
              null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
                lane: 0,
                revertLane: 0,
                action: update.action,
                hasEagerState: update.hasEagerState,
                eagerState: update.eagerState,
                next: null
              }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction$54 = true);
            else if ((renderLanes & revertLane) === revertLane) {
              update = update.next;
              revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction$54 = true);
              continue;
            } else
              updateLane = {
                lane: 0,
                revertLane: update.revertLane,
                action: update.action,
                hasEagerState: update.hasEagerState,
                eagerState: update.eagerState,
                next: null
              }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber$1.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
            updateLane = update.action;
            shouldDoubleInvokeUserFnsInHooksDEV && reducer(pendingQueue, updateLane);
            pendingQueue = update.hasEagerState ? update.eagerState : reducer(pendingQueue, updateLane);
          } else
            revertLane = {
              lane: updateLane,
              revertLane: update.revertLane,
              action: update.action,
              hasEagerState: update.hasEagerState,
              eagerState: update.eagerState,
              next: null
            }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber$1.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
          update = update.next;
        } while (null !== update && update !== current);
        null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
        if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction$54 && (reducer = currentEntangledActionThenable, null !== reducer)))
          throw reducer;
        hook.memoizedState = pendingQueue;
        hook.baseState = baseFirst;
        hook.baseQueue = newBaseQueueLast;
        queue.lastRenderedState = pendingQueue;
      }
      null === baseQueue && (queue.lanes = 0);
      return [hook.memoizedState, queue.dispatch];
    }
    function rerenderReducer(reducer) {
      var hook = updateWorkInProgressHook(), queue = hook.queue;
      if (null === queue) throw Error(formatProdErrorMessage(311));
      queue.lastRenderedReducer = reducer;
      var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
      if (null !== lastRenderPhaseUpdate) {
        queue.pending = null;
        var update = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
        do
          newState = reducer(newState, update.action), update = update.next;
        while (update !== lastRenderPhaseUpdate);
        objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
        hook.memoizedState = newState;
        null === hook.baseQueue && (hook.baseState = newState);
        queue.lastRenderedState = newState;
      }
      return [newState, dispatch];
    }
    function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      var fiber = currentlyRenderingFiber$1, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
      if (isHydrating$jscomp$0) {
        if (void 0 === getServerSnapshot) throw Error(formatProdErrorMessage(407));
        getServerSnapshot = getServerSnapshot();
      } else getServerSnapshot = getSnapshot();
      var snapshotChanged = !objectIs(
        (currentHook || hook).memoizedState,
        getServerSnapshot
      );
      snapshotChanged && (hook.memoizedState = getServerSnapshot, didReceiveUpdate = true);
      hook = hook.queue;
      updateEffect(subscribeToStore.bind(null, fiber, hook, subscribe), [
        subscribe
      ]);
      if (hook.getSnapshot !== getSnapshot || snapshotChanged || null !== workInProgressHook && workInProgressHook.memoizedState.tag & 1) {
        fiber.flags |= 2048;
        pushEffect(
          9,
          updateStoreInstance.bind(
            null,
            fiber,
            hook,
            getServerSnapshot,
            getSnapshot
          ),
          { destroy: void 0 },
          null
        );
        if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));
        isHydrating$jscomp$0 || 0 !== (renderLanes & 60) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
      }
      return getServerSnapshot;
    }
    function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
      fiber.flags |= 16384;
      fiber = { getSnapshot, value: renderedSnapshot };
      getSnapshot = currentlyRenderingFiber$1.updateQueue;
      null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber$1.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
    }
    function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
      inst.value = nextSnapshot;
      inst.getSnapshot = getSnapshot;
      checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
    }
    function subscribeToStore(fiber, inst, subscribe) {
      return subscribe(function() {
        checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
      });
    }
    function checkIfSnapshotChanged(inst) {
      var latestGetSnapshot = inst.getSnapshot;
      inst = inst.value;
      try {
        var nextValue = latestGetSnapshot();
        return !objectIs(inst, nextValue);
      } catch (error2) {
        return true;
      }
    }
    function forceStoreRerender(fiber) {
      var root2 = enqueueConcurrentRenderForLane(fiber, 2);
      null !== root2 && scheduleUpdateOnFiber(root2, fiber, 2);
    }
    function mountStateImpl(initialState2) {
      var hook = mountWorkInProgressHook();
      if ("function" === typeof initialState2) {
        var initialStateInitializer = initialState2;
        initialState2 = initialStateInitializer();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            initialStateInitializer();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
      }
      hook.memoizedState = hook.baseState = initialState2;
      hook.queue = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: basicStateReducer,
        lastRenderedState: initialState2
      };
      return hook;
    }
    function updateOptimisticImpl(hook, current, passthrough, reducer) {
      hook.baseState = passthrough;
      return updateReducerImpl(
        hook,
        currentHook,
        "function" === typeof reducer ? reducer : basicStateReducer
      );
    }
    function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
      if (isRenderPhaseUpdate(fiber)) throw Error(formatProdErrorMessage(485));
      fiber = actionQueue.action;
      if (null !== fiber) {
        var actionNode = {
          payload,
          action: fiber,
          next: null,
          isTransition: true,
          status: "pending",
          value: null,
          reason: null,
          listeners: [],
          then: function(listener) {
            actionNode.listeners.push(listener);
          }
        };
        null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
        setState(actionNode);
        setPendingState = actionQueue.pending;
        null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
      }
    }
    function runActionStateAction(actionQueue, node2) {
      var action = node2.action, payload = node2.payload, prevState = actionQueue.state;
      if (node2.isTransition) {
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        ReactSharedInternals.T = currentTransition;
        try {
          var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          handleActionReturnValue(actionQueue, node2, returnValue);
        } catch (error2) {
          onActionError(actionQueue, node2, error2);
        } finally {
          ReactSharedInternals.T = prevTransition;
        }
      } else
        try {
          prevTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node2, prevTransition);
        } catch (error$60) {
          onActionError(actionQueue, node2, error$60);
        }
    }
    function handleActionReturnValue(actionQueue, node2, returnValue) {
      null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? returnValue.then(
        function(nextState) {
          onActionSuccess(actionQueue, node2, nextState);
        },
        function(error2) {
          return onActionError(actionQueue, node2, error2);
        }
      ) : onActionSuccess(actionQueue, node2, returnValue);
    }
    function onActionSuccess(actionQueue, actionNode, nextState) {
      actionNode.status = "fulfilled";
      actionNode.value = nextState;
      notifyActionListeners(actionNode);
      actionQueue.state = nextState;
      actionNode = actionQueue.pending;
      null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
    }
    function onActionError(actionQueue, actionNode, error2) {
      var last = actionQueue.pending;
      actionQueue.pending = null;
      if (null !== last) {
        last = last.next;
        do
          actionNode.status = "rejected", actionNode.reason = error2, notifyActionListeners(actionNode), actionNode = actionNode.next;
        while (actionNode !== last);
      }
      actionQueue.action = null;
    }
    function notifyActionListeners(actionNode) {
      actionNode = actionNode.listeners;
      for (var i2 = 0; i2 < actionNode.length; i2++) (0, actionNode[i2])();
    }
    function actionStateReducer(oldState, newState) {
      return newState;
    }
    function mountActionState(action, initialStateProp) {
      if (isHydrating) {
        var ssrFormState = workInProgressRoot.formState;
        if (null !== ssrFormState) {
          a: {
            var JSCompiler_inline_result = currentlyRenderingFiber$1;
            if (isHydrating) {
              if (nextHydratableInstance) {
                b: {
                  var JSCompiler_inline_result$jscomp$0 = nextHydratableInstance;
                  for (var inRootOrSingleton = rootOrSingletonContext; 8 !== JSCompiler_inline_result$jscomp$0.nodeType; ) {
                    if (!inRootOrSingleton) {
                      JSCompiler_inline_result$jscomp$0 = null;
                      break b;
                    }
                    JSCompiler_inline_result$jscomp$0 = getNextHydratable(
                      JSCompiler_inline_result$jscomp$0.nextSibling
                    );
                    if (null === JSCompiler_inline_result$jscomp$0) {
                      JSCompiler_inline_result$jscomp$0 = null;
                      break b;
                    }
                  }
                  inRootOrSingleton = JSCompiler_inline_result$jscomp$0.data;
                  JSCompiler_inline_result$jscomp$0 = "F!" === inRootOrSingleton || "F" === inRootOrSingleton ? JSCompiler_inline_result$jscomp$0 : null;
                }
                if (JSCompiler_inline_result$jscomp$0) {
                  nextHydratableInstance = getNextHydratable(
                    JSCompiler_inline_result$jscomp$0.nextSibling
                  );
                  JSCompiler_inline_result = "F!" === JSCompiler_inline_result$jscomp$0.data;
                  break a;
                }
              }
              throwOnHydrationMismatch(JSCompiler_inline_result);
            }
            JSCompiler_inline_result = false;
          }
          JSCompiler_inline_result && (initialStateProp = ssrFormState[0]);
        }
      }
      ssrFormState = mountWorkInProgressHook();
      ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
      JSCompiler_inline_result = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: actionStateReducer,
        lastRenderedState: initialStateProp
      };
      ssrFormState.queue = JSCompiler_inline_result;
      ssrFormState = dispatchSetState.bind(
        null,
        currentlyRenderingFiber$1,
        JSCompiler_inline_result
      );
      JSCompiler_inline_result.dispatch = ssrFormState;
      JSCompiler_inline_result = mountStateImpl(false);
      inRootOrSingleton = dispatchOptimisticSetState.bind(
        null,
        currentlyRenderingFiber$1,
        false,
        JSCompiler_inline_result.queue
      );
      JSCompiler_inline_result = mountWorkInProgressHook();
      JSCompiler_inline_result$jscomp$0 = {
        state: initialStateProp,
        dispatch: null,
        action,
        pending: null
      };
      JSCompiler_inline_result.queue = JSCompiler_inline_result$jscomp$0;
      ssrFormState = dispatchActionState.bind(
        null,
        currentlyRenderingFiber$1,
        JSCompiler_inline_result$jscomp$0,
        inRootOrSingleton,
        ssrFormState
      );
      JSCompiler_inline_result$jscomp$0.dispatch = ssrFormState;
      JSCompiler_inline_result.memoizedState = action;
      return [initialStateProp, ssrFormState, false];
    }
    function updateActionState(action) {
      var stateHook = updateWorkInProgressHook();
      return updateActionStateImpl(stateHook, currentHook, action);
    }
    function updateActionStateImpl(stateHook, currentStateHook, action) {
      currentStateHook = updateReducerImpl(
        stateHook,
        currentStateHook,
        actionStateReducer
      )[0];
      stateHook = updateReducer(basicStateReducer)[0];
      currentStateHook = "object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then ? useThenable(currentStateHook) : currentStateHook;
      var actionQueueHook = updateWorkInProgressHook(), actionQueue = actionQueueHook.queue, dispatch = actionQueue.dispatch;
      action !== actionQueueHook.memoizedState && (currentlyRenderingFiber$1.flags |= 2048, pushEffect(
        9,
        actionStateActionEffect.bind(null, actionQueue, action),
        { destroy: void 0 },
        null
      ));
      return [currentStateHook, dispatch, stateHook];
    }
    function actionStateActionEffect(actionQueue, action) {
      actionQueue.action = action;
    }
    function rerenderActionState(action) {
      var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
      if (null !== currentStateHook)
        return updateActionStateImpl(stateHook, currentStateHook, action);
      updateWorkInProgressHook();
      stateHook = stateHook.memoizedState;
      currentStateHook = updateWorkInProgressHook();
      var dispatch = currentStateHook.queue.dispatch;
      currentStateHook.memoizedState = action;
      return [stateHook, dispatch, false];
    }
    function pushEffect(tag, create2, inst, deps) {
      tag = { tag, create: create2, inst, deps, next: null };
      create2 = currentlyRenderingFiber$1.updateQueue;
      null === create2 && (create2 = createFunctionComponentUpdateQueue(), currentlyRenderingFiber$1.updateQueue = create2);
      inst = create2.lastEffect;
      null === inst ? create2.lastEffect = tag.next = tag : (deps = inst.next, inst.next = tag, tag.next = deps, create2.lastEffect = tag);
      return tag;
    }
    function updateRef() {
      return updateWorkInProgressHook().memoizedState;
    }
    function mountEffectImpl(fiberFlags, hookFlags, create2, deps) {
      var hook = mountWorkInProgressHook();
      currentlyRenderingFiber$1.flags |= fiberFlags;
      hook.memoizedState = pushEffect(
        1 | hookFlags,
        create2,
        { destroy: void 0 },
        void 0 === deps ? null : deps
      );
    }
    function updateEffectImpl(fiberFlags, hookFlags, create2, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var inst = hook.memoizedState.inst;
      null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushEffect(hookFlags, create2, inst, deps) : (currentlyRenderingFiber$1.flags |= fiberFlags, hook.memoizedState = pushEffect(1 | hookFlags, create2, inst, deps));
    }
    function mountEffect(create2, deps) {
      mountEffectImpl(8390656, 8, create2, deps);
    }
    function updateEffect(create2, deps) {
      updateEffectImpl(2048, 8, create2, deps);
    }
    function updateInsertionEffect(create2, deps) {
      return updateEffectImpl(4, 2, create2, deps);
    }
    function updateLayoutEffect(create2, deps) {
      return updateEffectImpl(4, 4, create2, deps);
    }
    function imperativeHandleEffect(create2, ref) {
      if ("function" === typeof ref) {
        create2 = create2();
        var refCleanup = ref(create2);
        return function() {
          "function" === typeof refCleanup ? refCleanup() : ref(null);
        };
      }
      if (null !== ref && void 0 !== ref)
        return create2 = create2(), ref.current = create2, function() {
          ref.current = null;
        };
    }
    function updateImperativeHandle(ref, create2, deps) {
      deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
      updateEffectImpl(4, 4, imperativeHandleEffect.bind(null, create2, ref), deps);
    }
    function mountDebugValue() {
    }
    function updateCallback(callback, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var prevState = hook.memoizedState;
      if (null !== deps && areHookInputsEqual(deps, prevState[1]))
        return prevState[0];
      hook.memoizedState = [callback, deps];
      return callback;
    }
    function updateMemo(nextCreate, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var prevState = hook.memoizedState;
      if (null !== deps && areHookInputsEqual(deps, prevState[1]))
        return prevState[0];
      prevState = nextCreate();
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(true);
        try {
          nextCreate();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      hook.memoizedState = [prevState, deps];
      return prevState;
    }
    function mountDeferredValueImpl(hook, value2, initialValue) {
      if (void 0 === initialValue || 0 !== (renderLanes & 1073741824))
        return hook.memoizedState = value2;
      hook.memoizedState = initialValue;
      hook = requestDeferredLane();
      currentlyRenderingFiber$1.lanes |= hook;
      workInProgressRootSkippedLanes |= hook;
      return initialValue;
    }
    function updateDeferredValueImpl(hook, prevValue, value2, initialValue) {
      if (objectIs(value2, prevValue)) return value2;
      if (null !== currentTreeHiddenStackCursor.current)
        return hook = mountDeferredValueImpl(hook, value2, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
      if (0 === (renderLanes & 42))
        return didReceiveUpdate = true, hook.memoizedState = value2;
      hook = requestDeferredLane();
      currentlyRenderingFiber$1.lanes |= hook;
      workInProgressRootSkippedLanes |= hook;
      return prevValue;
    }
    function startTransition(fiber, queue, pendingState, finishedState, callback) {
      var previousPriority = ReactDOMSharedInternals.p;
      ReactDOMSharedInternals.p = 0 !== previousPriority && 8 > previousPriority ? previousPriority : 8;
      var prevTransition = ReactSharedInternals.T, currentTransition = {};
      ReactSharedInternals.T = currentTransition;
      dispatchOptimisticSetState(fiber, false, queue, pendingState);
      try {
        var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
        null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
        if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
          var thenableForFinishedState = chainThenableValue(
            returnValue,
            finishedState
          );
          dispatchSetStateInternal(
            fiber,
            queue,
            thenableForFinishedState,
            requestUpdateLane(fiber)
          );
        } else
          dispatchSetStateInternal(
            fiber,
            queue,
            finishedState,
            requestUpdateLane(fiber)
          );
      } catch (error2) {
        dispatchSetStateInternal(
          fiber,
          queue,
          { then: function() {
          }, status: "rejected", reason: error2 },
          requestUpdateLane()
        );
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
      }
    }
    function noop$2() {
    }
    function startHostTransition(formFiber, pendingState, action, formData) {
      if (5 !== formFiber.tag) throw Error(formatProdErrorMessage(476));
      var queue = ensureFormComponentIsStateful(formFiber).queue;
      startTransition(
        formFiber,
        queue,
        pendingState,
        sharedNotPendingObject,
        null === action ? noop$2 : function() {
          requestFormReset$1(formFiber);
          return action(formData);
        }
      );
    }
    function ensureFormComponentIsStateful(formFiber) {
      var existingStateHook = formFiber.memoizedState;
      if (null !== existingStateHook) return existingStateHook;
      existingStateHook = {
        memoizedState: sharedNotPendingObject,
        baseState: sharedNotPendingObject,
        baseQueue: null,
        queue: {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: sharedNotPendingObject
        },
        next: null
      };
      var initialResetState = {};
      existingStateHook.next = {
        memoizedState: initialResetState,
        baseState: initialResetState,
        baseQueue: null,
        queue: {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: initialResetState
        },
        next: null
      };
      formFiber.memoizedState = existingStateHook;
      formFiber = formFiber.alternate;
      null !== formFiber && (formFiber.memoizedState = existingStateHook);
      return existingStateHook;
    }
    function requestFormReset$1(formFiber) {
      var resetStateQueue = ensureFormComponentIsStateful(formFiber).next.queue;
      dispatchSetStateInternal(formFiber, resetStateQueue, {}, requestUpdateLane());
    }
    function useHostTransitionStatus() {
      return readContext(HostTransitionContext);
    }
    function updateId() {
      return updateWorkInProgressHook().memoizedState;
    }
    function updateRefresh() {
      return updateWorkInProgressHook().memoizedState;
    }
    function refreshCache(fiber) {
      for (var provider = fiber.return; null !== provider; ) {
        switch (provider.tag) {
          case 24:
          case 3:
            var lane = requestUpdateLane();
            fiber = createUpdate(lane);
            var root$63 = enqueueUpdate(provider, fiber, lane);
            null !== root$63 && (scheduleUpdateOnFiber(root$63, provider, lane), entangleTransitions(root$63, provider, lane));
            provider = { cache: createCache() };
            fiber.payload = provider;
            return;
        }
        provider = provider.return;
      }
    }
    function dispatchReducerAction(fiber, queue, action) {
      var lane = requestUpdateLane();
      action = {
        lane,
        revertLane: 0,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, action) : (action = enqueueConcurrentHookUpdate(fiber, queue, action, lane), null !== action && (scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane)));
    }
    function dispatchSetState(fiber, queue, action) {
      var lane = requestUpdateLane();
      dispatchSetStateInternal(fiber, queue, action, lane);
    }
    function dispatchSetStateInternal(fiber, queue, action, lane) {
      var update = {
        lane,
        revertLane: 0,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update);
      else {
        var alternate = fiber.alternate;
        if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate))
          try {
            var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
            update.hasEagerState = true;
            update.eagerState = eagerState;
            if (objectIs(eagerState, currentState))
              return enqueueUpdate$1(fiber, queue, update, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
          } catch (error2) {
          } finally {
          }
        action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
        if (null !== action)
          return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
      }
      return false;
    }
    function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
      action = {
        lane: 2,
        revertLane: requestTransitionLane(),
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      if (isRenderPhaseUpdate(fiber)) {
        if (throwIfDuringRender) throw Error(formatProdErrorMessage(479));
      } else
        throwIfDuringRender = enqueueConcurrentHookUpdate(
          fiber,
          queue,
          action,
          2
        ), null !== throwIfDuringRender && scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);
    }
    function isRenderPhaseUpdate(fiber) {
      var alternate = fiber.alternate;
      return fiber === currentlyRenderingFiber$1 || null !== alternate && alternate === currentlyRenderingFiber$1;
    }
    function enqueueRenderPhaseUpdate(queue, update) {
      didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
      var pending = queue.pending;
      null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
      queue.pending = update;
    }
    function entangleTransitionUpdate(root2, queue, lane) {
      if (0 !== (lane & 4194176)) {
        var queueLanes = queue.lanes;
        queueLanes &= root2.pendingLanes;
        lane |= queueLanes;
        queue.lanes = lane;
        markRootEntangled(root2, lane);
      }
    }
    var ContextOnlyDispatcher = {
      readContext,
      use: use$1,
      useCallback: throwInvalidHookError,
      useContext: throwInvalidHookError,
      useEffect: throwInvalidHookError,
      useImperativeHandle: throwInvalidHookError,
      useLayoutEffect: throwInvalidHookError,
      useInsertionEffect: throwInvalidHookError,
      useMemo: throwInvalidHookError,
      useReducer: throwInvalidHookError,
      useRef: throwInvalidHookError,
      useState: throwInvalidHookError,
      useDebugValue: throwInvalidHookError,
      useDeferredValue: throwInvalidHookError,
      useTransition: throwInvalidHookError,
      useSyncExternalStore: throwInvalidHookError,
      useId: throwInvalidHookError
    };
    ContextOnlyDispatcher.useCacheRefresh = throwInvalidHookError;
    ContextOnlyDispatcher.useMemoCache = throwInvalidHookError;
    ContextOnlyDispatcher.useHostTransitionStatus = throwInvalidHookError;
    ContextOnlyDispatcher.useFormState = throwInvalidHookError;
    ContextOnlyDispatcher.useActionState = throwInvalidHookError;
    ContextOnlyDispatcher.useOptimistic = throwInvalidHookError;
    var HooksDispatcherOnMount = {
      readContext,
      use: use$1,
      useCallback: function(callback, deps) {
        mountWorkInProgressHook().memoizedState = [
          callback,
          void 0 === deps ? null : deps
        ];
        return callback;
      },
      useContext: readContext,
      useEffect: mountEffect,
      useImperativeHandle: function(ref, create2, deps) {
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        mountEffectImpl(
          4194308,
          4,
          imperativeHandleEffect.bind(null, create2, ref),
          deps
        );
      },
      useLayoutEffect: function(create2, deps) {
        return mountEffectImpl(4194308, 4, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        mountEffectImpl(4, 2, create2, deps);
      },
      useMemo: function(nextCreate, deps) {
        var hook = mountWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var nextValue = nextCreate();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            nextCreate();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        hook.memoizedState = [nextValue, deps];
        return nextValue;
      },
      useReducer: function(reducer, initialArg, init) {
        var hook = mountWorkInProgressHook();
        if (void 0 !== init) {
          var initialState2 = init(initialArg);
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              init(initialArg);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
        } else initialState2 = initialArg;
        hook.memoizedState = hook.baseState = initialState2;
        reducer = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: reducer,
          lastRenderedState: initialState2
        };
        hook.queue = reducer;
        reducer = reducer.dispatch = dispatchReducerAction.bind(
          null,
          currentlyRenderingFiber$1,
          reducer
        );
        return [hook.memoizedState, reducer];
      },
      useRef: function(initialValue) {
        var hook = mountWorkInProgressHook();
        initialValue = { current: initialValue };
        return hook.memoizedState = initialValue;
      },
      useState: function(initialState2) {
        initialState2 = mountStateImpl(initialState2);
        var queue = initialState2.queue, dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
        queue.dispatch = dispatch;
        return [initialState2.memoizedState, dispatch];
      },
      useDebugValue: mountDebugValue,
      useDeferredValue: function(value2, initialValue) {
        var hook = mountWorkInProgressHook();
        return mountDeferredValueImpl(hook, value2, initialValue);
      },
      useTransition: function() {
        var stateHook = mountStateImpl(false);
        stateHook = startTransition.bind(
          null,
          currentlyRenderingFiber$1,
          stateHook.queue,
          true,
          false
        );
        mountWorkInProgressHook().memoizedState = stateHook;
        return [false, stateHook];
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber$1, hook = mountWorkInProgressHook();
        if (isHydrating) {
          if (void 0 === getServerSnapshot)
            throw Error(formatProdErrorMessage(407));
          getServerSnapshot = getServerSnapshot();
        } else {
          getServerSnapshot = getSnapshot();
          if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));
          0 !== (workInProgressRootRenderLanes & 60) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
        }
        hook.memoizedState = getServerSnapshot;
        var inst = { value: getServerSnapshot, getSnapshot };
        hook.queue = inst;
        mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
          subscribe
        ]);
        fiber.flags |= 2048;
        pushEffect(
          9,
          updateStoreInstance.bind(
            null,
            fiber,
            inst,
            getServerSnapshot,
            getSnapshot
          ),
          { destroy: void 0 },
          null
        );
        return getServerSnapshot;
      },
      useId: function() {
        var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
        if (isHydrating) {
          var JSCompiler_inline_result = treeContextOverflow;
          var idWithLeadingBit = treeContextId;
          JSCompiler_inline_result = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + JSCompiler_inline_result;
          identifierPrefix = ":" + identifierPrefix + "R" + JSCompiler_inline_result;
          JSCompiler_inline_result = localIdCounter++;
          0 < JSCompiler_inline_result && (identifierPrefix += "H" + JSCompiler_inline_result.toString(32));
          identifierPrefix += ":";
        } else
          JSCompiler_inline_result = globalClientIdCounter++, identifierPrefix = ":" + identifierPrefix + "r" + JSCompiler_inline_result.toString(32) + ":";
        return hook.memoizedState = identifierPrefix;
      },
      useCacheRefresh: function() {
        return mountWorkInProgressHook().memoizedState = refreshCache.bind(
          null,
          currentlyRenderingFiber$1
        );
      }
    };
    HooksDispatcherOnMount.useMemoCache = useMemoCache;
    HooksDispatcherOnMount.useHostTransitionStatus = useHostTransitionStatus;
    HooksDispatcherOnMount.useFormState = mountActionState;
    HooksDispatcherOnMount.useActionState = mountActionState;
    HooksDispatcherOnMount.useOptimistic = function(passthrough) {
      var hook = mountWorkInProgressHook();
      hook.memoizedState = hook.baseState = passthrough;
      var queue = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: null,
        lastRenderedState: null
      };
      hook.queue = queue;
      hook = dispatchOptimisticSetState.bind(
        null,
        currentlyRenderingFiber$1,
        true,
        queue
      );
      queue.dispatch = hook;
      return [passthrough, hook];
    };
    var HooksDispatcherOnUpdate = {
      readContext,
      use: use$1,
      useCallback: updateCallback,
      useContext: readContext,
      useEffect: updateEffect,
      useImperativeHandle: updateImperativeHandle,
      useInsertionEffect: updateInsertionEffect,
      useLayoutEffect: updateLayoutEffect,
      useMemo: updateMemo,
      useReducer: updateReducer,
      useRef: updateRef,
      useState: function() {
        return updateReducer(basicStateReducer);
      },
      useDebugValue: mountDebugValue,
      useDeferredValue: function(value2, initialValue) {
        var hook = updateWorkInProgressHook();
        return updateDeferredValueImpl(
          hook,
          currentHook.memoizedState,
          value2,
          initialValue
        );
      },
      useTransition: function() {
        var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start
        ];
      },
      useSyncExternalStore: updateSyncExternalStore,
      useId: updateId
    };
    HooksDispatcherOnUpdate.useCacheRefresh = updateRefresh;
    HooksDispatcherOnUpdate.useMemoCache = useMemoCache;
    HooksDispatcherOnUpdate.useHostTransitionStatus = useHostTransitionStatus;
    HooksDispatcherOnUpdate.useFormState = updateActionState;
    HooksDispatcherOnUpdate.useActionState = updateActionState;
    HooksDispatcherOnUpdate.useOptimistic = function(passthrough, reducer) {
      var hook = updateWorkInProgressHook();
      return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
    };
    var HooksDispatcherOnRerender = {
      readContext,
      use: use$1,
      useCallback: updateCallback,
      useContext: readContext,
      useEffect: updateEffect,
      useImperativeHandle: updateImperativeHandle,
      useInsertionEffect: updateInsertionEffect,
      useLayoutEffect: updateLayoutEffect,
      useMemo: updateMemo,
      useReducer: rerenderReducer,
      useRef: updateRef,
      useState: function() {
        return rerenderReducer(basicStateReducer);
      },
      useDebugValue: mountDebugValue,
      useDeferredValue: function(value2, initialValue) {
        var hook = updateWorkInProgressHook();
        return null === currentHook ? mountDeferredValueImpl(hook, value2, initialValue) : updateDeferredValueImpl(
          hook,
          currentHook.memoizedState,
          value2,
          initialValue
        );
      },
      useTransition: function() {
        var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start
        ];
      },
      useSyncExternalStore: updateSyncExternalStore,
      useId: updateId
    };
    HooksDispatcherOnRerender.useCacheRefresh = updateRefresh;
    HooksDispatcherOnRerender.useMemoCache = useMemoCache;
    HooksDispatcherOnRerender.useHostTransitionStatus = useHostTransitionStatus;
    HooksDispatcherOnRerender.useFormState = rerenderActionState;
    HooksDispatcherOnRerender.useActionState = rerenderActionState;
    HooksDispatcherOnRerender.useOptimistic = function(passthrough, reducer) {
      var hook = updateWorkInProgressHook();
      if (null !== currentHook)
        return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
      hook.baseState = passthrough;
      return [passthrough, hook.queue.dispatch];
    };
    function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
      ctor = workInProgress2.memoizedState;
      getDerivedStateFromProps = getDerivedStateFromProps(nextProps, ctor);
      getDerivedStateFromProps = null === getDerivedStateFromProps || void 0 === getDerivedStateFromProps ? ctor : assign$2({}, ctor, getDerivedStateFromProps);
      workInProgress2.memoizedState = getDerivedStateFromProps;
      0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = getDerivedStateFromProps);
    }
    var classComponentUpdater = {
      isMounted: function(component) {
        return (component = component._reactInternals) ? getNearestMountedFiber(component) === component : false;
      },
      enqueueSetState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(), update = createUpdate(lane);
        update.payload = payload;
        void 0 !== callback && null !== callback && (update.callback = callback);
        payload = enqueueUpdate(inst, update, lane);
        null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
      },
      enqueueReplaceState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(), update = createUpdate(lane);
        update.tag = 1;
        update.payload = payload;
        void 0 !== callback && null !== callback && (update.callback = callback);
        payload = enqueueUpdate(inst, update, lane);
        null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
      },
      enqueueForceUpdate: function(inst, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(), update = createUpdate(lane);
        update.tag = 2;
        void 0 !== callback && null !== callback && (update.callback = callback);
        callback = enqueueUpdate(inst, update, lane);
        null !== callback && (scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
      }
    };
    function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
      workInProgress2 = workInProgress2.stateNode;
      return "function" === typeof workInProgress2.shouldComponentUpdate ? workInProgress2.shouldComponentUpdate(newProps, newState, nextContext) : ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
    }
    function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
      workInProgress2 = instance.state;
      "function" === typeof instance.componentWillReceiveProps && instance.componentWillReceiveProps(newProps, nextContext);
      "function" === typeof instance.UNSAFE_componentWillReceiveProps && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
      instance.state !== workInProgress2 && classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
    }
    function resolveClassComponentProps(Component2, baseProps) {
      var newProps = baseProps;
      if ("ref" in baseProps) {
        newProps = {};
        for (var propName in baseProps)
          "ref" !== propName && (newProps[propName] = baseProps[propName]);
      }
      if (Component2 = Component2.defaultProps) {
        newProps === baseProps && (newProps = assign$2({}, newProps));
        for (var propName$67 in Component2)
          void 0 === newProps[propName$67] && (newProps[propName$67] = Component2[propName$67]);
      }
      return newProps;
    }
    var reportGlobalError = "function" === typeof reportError ? reportError : function(error2) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
          error: error2
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process && "function" === typeof process.emit) {
        process.emit("uncaughtException", error2);
        return;
      }
      console.error(error2);
    };
    function defaultOnUncaughtError(error2) {
      reportGlobalError(error2);
    }
    function defaultOnCaughtError(error2) {
      console.error(error2);
    }
    function defaultOnRecoverableError(error2) {
      reportGlobalError(error2);
    }
    function logUncaughtError(root2, errorInfo) {
      try {
        var onUncaughtError = root2.onUncaughtError;
        onUncaughtError(errorInfo.value, { componentStack: errorInfo.stack });
      } catch (e$68) {
        setTimeout(function() {
          throw e$68;
        });
      }
    }
    function logCaughtError(root2, boundary, errorInfo) {
      try {
        var onCaughtError = root2.onCaughtError;
        onCaughtError(errorInfo.value, {
          componentStack: errorInfo.stack,
          errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
        });
      } catch (e$69) {
        setTimeout(function() {
          throw e$69;
        });
      }
    }
    function createRootErrorUpdate(root2, errorInfo, lane) {
      lane = createUpdate(lane);
      lane.tag = 3;
      lane.payload = { element: null };
      lane.callback = function() {
        logUncaughtError(root2, errorInfo);
      };
      return lane;
    }
    function createClassErrorUpdate(lane) {
      lane = createUpdate(lane);
      lane.tag = 3;
      return lane;
    }
    function initializeClassErrorUpdate(update, root2, fiber, errorInfo) {
      var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
      if ("function" === typeof getDerivedStateFromError) {
        var error2 = errorInfo.value;
        update.payload = function() {
          return getDerivedStateFromError(error2);
        };
        update.callback = function() {
          logCaughtError(root2, fiber, errorInfo);
        };
      }
      var inst = fiber.stateNode;
      null !== inst && "function" === typeof inst.componentDidCatch && (update.callback = function() {
        logCaughtError(root2, fiber, errorInfo);
        "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
        var stack2 = errorInfo.stack;
        this.componentDidCatch(errorInfo.value, {
          componentStack: null !== stack2 ? stack2 : ""
        });
      });
    }
    function throwException(root2, returnFiber, sourceFiber, value2, rootRenderLanes) {
      sourceFiber.flags |= 32768;
      if (null !== value2 && "object" === typeof value2 && "function" === typeof value2.then) {
        returnFiber = sourceFiber.alternate;
        null !== returnFiber && propagateParentContextChanges(
          returnFiber,
          sourceFiber,
          rootRenderLanes,
          true
        );
        sourceFiber = suspenseHandlerStackCursor.current;
        if (null !== sourceFiber) {
          switch (sourceFiber.tag) {
            case 13:
              return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 3), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value2 === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value2]) : returnFiber.add(value2), attachPingListener(root2, value2, rootRenderLanes)), false;
            case 22:
              return sourceFiber.flags |= 65536, value2 === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
                transitions: null,
                markerInstances: null,
                retryQueue: /* @__PURE__ */ new Set([value2])
              }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value2]) : sourceFiber.add(value2)), attachPingListener(root2, value2, rootRenderLanes)), false;
          }
          throw Error(formatProdErrorMessage(435, sourceFiber.tag));
        }
        attachPingListener(root2, value2, rootRenderLanes);
        renderDidSuspendDelayIfPossible();
        return false;
      }
      if (isHydrating)
        return returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value2 !== HydrationMismatchException && (root2 = Error(formatProdErrorMessage(422), { cause: value2 }), queueHydrationError(createCapturedValueAtFiber(root2, sourceFiber)))) : (value2 !== HydrationMismatchException && (returnFiber = Error(formatProdErrorMessage(423), {
          cause: value2
        }), queueHydrationError(
          createCapturedValueAtFiber(returnFiber, sourceFiber)
        )), root2 = root2.current.alternate, root2.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root2.lanes |= rootRenderLanes, value2 = createCapturedValueAtFiber(value2, sourceFiber), rootRenderLanes = createRootErrorUpdate(
          root2.stateNode,
          value2,
          rootRenderLanes
        ), enqueueCapturedUpdate(root2, rootRenderLanes), 4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2)), false;
      var wrapperError = Error(formatProdErrorMessage(520), { cause: value2 });
      wrapperError = createCapturedValueAtFiber(wrapperError, sourceFiber);
      null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [wrapperError] : workInProgressRootConcurrentErrors.push(wrapperError);
      4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2);
      if (null === returnFiber) return true;
      value2 = createCapturedValueAtFiber(value2, sourceFiber);
      sourceFiber = returnFiber;
      do {
        switch (sourceFiber.tag) {
          case 3:
            return sourceFiber.flags |= 65536, root2 = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root2, root2 = createRootErrorUpdate(sourceFiber.stateNode, value2, root2), enqueueCapturedUpdate(sourceFiber, root2), false;
          case 1:
            if (returnFiber = sourceFiber.type, wrapperError = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== wrapperError && "function" === typeof wrapperError.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(wrapperError))))
              return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
                rootRenderLanes,
                root2,
                sourceFiber,
                value2
              ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
        }
        sourceFiber = sourceFiber.return;
      } while (null !== sourceFiber);
      return false;
    }
    var SelectiveHydrationException = Error(formatProdErrorMessage(461)), didReceiveUpdate = false;
    function reconcileChildren(current, workInProgress2, nextChildren, renderLanes2) {
      workInProgress2.child = null === current ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
        workInProgress2,
        current.child,
        nextChildren,
        renderLanes2
      );
    }
    function updateForwardRef(current, workInProgress2, Component2, nextProps, renderLanes2) {
      Component2 = Component2.render;
      var ref = workInProgress2.ref;
      if ("ref" in nextProps) {
        var propsWithoutRef = {};
        for (var key2 in nextProps)
          "ref" !== key2 && (propsWithoutRef[key2] = nextProps[key2]);
      } else propsWithoutRef = nextProps;
      prepareToReadContext(workInProgress2);
      nextProps = renderWithHooks(
        current,
        workInProgress2,
        Component2,
        propsWithoutRef,
        ref,
        renderLanes2
      );
      key2 = checkDidRenderIdHook();
      if (null !== current && !didReceiveUpdate)
        return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
      isHydrating && key2 && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
      return workInProgress2.child;
    }
    function updateMemoComponent(current, workInProgress2, Component2, nextProps, renderLanes2) {
      if (null === current) {
        var type = Component2.type;
        if ("function" === typeof type && !shouldConstruct(type) && void 0 === type.defaultProps && null === Component2.compare)
          return workInProgress2.tag = 15, workInProgress2.type = type, updateSimpleMemoComponent(
            current,
            workInProgress2,
            type,
            nextProps,
            renderLanes2
          );
        current = createFiberFromTypeAndProps(
          Component2.type,
          null,
          nextProps,
          workInProgress2,
          workInProgress2.mode,
          renderLanes2
        );
        current.ref = workInProgress2.ref;
        current.return = workInProgress2;
        return workInProgress2.child = current;
      }
      type = current.child;
      if (!checkScheduledUpdateOrContext(current, renderLanes2)) {
        var prevProps = type.memoizedProps;
        Component2 = Component2.compare;
        Component2 = null !== Component2 ? Component2 : shallowEqual;
        if (Component2(prevProps, nextProps) && current.ref === workInProgress2.ref)
          return bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
      }
      workInProgress2.flags |= 1;
      current = createWorkInProgress(type, nextProps);
      current.ref = workInProgress2.ref;
      current.return = workInProgress2;
      return workInProgress2.child = current;
    }
    function updateSimpleMemoComponent(current, workInProgress2, Component2, nextProps, renderLanes2) {
      if (null !== current) {
        var prevProps = current.memoizedProps;
        if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress2.ref)
          if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current, renderLanes2))
            0 !== (current.flags & 131072) && (didReceiveUpdate = true);
          else
            return workInProgress2.lanes = current.lanes, bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
      }
      return updateFunctionComponent(
        current,
        workInProgress2,
        Component2,
        nextProps,
        renderLanes2
      );
    }
    function updateOffscreenComponent(current, workInProgress2, renderLanes2) {
      var nextProps = workInProgress2.pendingProps, nextChildren = nextProps.children, nextIsDetached = 0 !== (workInProgress2.stateNode._pendingVisibility & 2), prevState = null !== current ? current.memoizedState : null;
      markRef(current, workInProgress2);
      if ("hidden" === nextProps.mode || nextIsDetached) {
        if (0 !== (workInProgress2.flags & 128)) {
          nextProps = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
          if (null !== current) {
            nextChildren = workInProgress2.child = current.child;
            for (nextIsDetached = 0; null !== nextChildren; )
              nextIsDetached = nextIsDetached | nextChildren.lanes | nextChildren.childLanes, nextChildren = nextChildren.sibling;
            workInProgress2.childLanes = nextIsDetached & ~nextProps;
          } else workInProgress2.childLanes = 0, workInProgress2.child = null;
          return deferHiddenOffscreenComponent(
            current,
            workInProgress2,
            nextProps,
            renderLanes2
          );
        }
        if (0 !== (renderLanes2 & 536870912))
          workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current && pushTransition(
            workInProgress2,
            null !== prevState ? prevState.cachePool : null
          ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(), pushOffscreenSuspenseHandler(workInProgress2);
        else
          return workInProgress2.lanes = workInProgress2.childLanes = 536870912, deferHiddenOffscreenComponent(
            current,
            workInProgress2,
            null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
            renderLanes2
          );
      } else
        null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(), workInProgress2.memoizedState = null) : (null !== current && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(), reuseSuspenseHandlerOnStack());
      reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
      return workInProgress2.child;
    }
    function deferHiddenOffscreenComponent(current, workInProgress2, nextBaseLanes, renderLanes2) {
      var JSCompiler_inline_result = peekCacheFromPool();
      JSCompiler_inline_result = null === JSCompiler_inline_result ? null : { parent: CacheContext._currentValue, pool: JSCompiler_inline_result };
      workInProgress2.memoizedState = {
        baseLanes: nextBaseLanes,
        cachePool: JSCompiler_inline_result
      };
      null !== current && pushTransition(workInProgress2, null);
      reuseHiddenContextOnStack();
      pushOffscreenSuspenseHandler(workInProgress2);
      null !== current && propagateParentContextChanges(current, workInProgress2, renderLanes2, true);
      return null;
    }
    function markRef(current, workInProgress2) {
      var ref = workInProgress2.ref;
      if (null === ref)
        null !== current && null !== current.ref && (workInProgress2.flags |= 2097664);
      else {
        if ("function" !== typeof ref && "object" !== typeof ref)
          throw Error(formatProdErrorMessage(284));
        if (null === current || current.ref !== ref)
          workInProgress2.flags |= 2097664;
      }
    }
    function updateFunctionComponent(current, workInProgress2, Component2, nextProps, renderLanes2) {
      prepareToReadContext(workInProgress2);
      Component2 = renderWithHooks(
        current,
        workInProgress2,
        Component2,
        nextProps,
        void 0,
        renderLanes2
      );
      nextProps = checkDidRenderIdHook();
      if (null !== current && !didReceiveUpdate)
        return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
      isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current, workInProgress2, Component2, renderLanes2);
      return workInProgress2.child;
    }
    function replayFunctionComponent(current, workInProgress2, nextProps, Component2, secondArg, renderLanes2) {
      prepareToReadContext(workInProgress2);
      workInProgress2.updateQueue = null;
      nextProps = renderWithHooksAgain(
        workInProgress2,
        Component2,
        nextProps,
        secondArg
      );
      finishRenderingHooks(current);
      Component2 = checkDidRenderIdHook();
      if (null !== current && !didReceiveUpdate)
        return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
      isHydrating && Component2 && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
      return workInProgress2.child;
    }
    function updateClassComponent(current, workInProgress2, Component2, nextProps, renderLanes2) {
      prepareToReadContext(workInProgress2);
      if (null === workInProgress2.stateNode) {
        var context = emptyContextObject, contextType = Component2.contextType;
        "object" === typeof contextType && null !== contextType && (context = readContext(contextType));
        context = new Component2(nextProps, context);
        workInProgress2.memoizedState = null !== context.state && void 0 !== context.state ? context.state : null;
        context.updater = classComponentUpdater;
        workInProgress2.stateNode = context;
        context._reactInternals = workInProgress2;
        context = workInProgress2.stateNode;
        context.props = nextProps;
        context.state = workInProgress2.memoizedState;
        context.refs = {};
        initializeUpdateQueue(workInProgress2);
        contextType = Component2.contextType;
        context.context = "object" === typeof contextType && null !== contextType ? readContext(contextType) : emptyContextObject;
        context.state = workInProgress2.memoizedState;
        contextType = Component2.getDerivedStateFromProps;
        "function" === typeof contextType && (applyDerivedStateFromProps(
          workInProgress2,
          Component2,
          contextType,
          nextProps
        ), context.state = workInProgress2.memoizedState);
        "function" === typeof Component2.getDerivedStateFromProps || "function" === typeof context.getSnapshotBeforeUpdate || "function" !== typeof context.UNSAFE_componentWillMount && "function" !== typeof context.componentWillMount || (contextType = context.state, "function" === typeof context.componentWillMount && context.componentWillMount(), "function" === typeof context.UNSAFE_componentWillMount && context.UNSAFE_componentWillMount(), contextType !== context.state && classComponentUpdater.enqueueReplaceState(context, context.state, null), processUpdateQueue(workInProgress2, nextProps, context, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), context.state = workInProgress2.memoizedState);
        "function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308);
        nextProps = true;
      } else if (null === current) {
        context = workInProgress2.stateNode;
        var unresolvedOldProps = workInProgress2.memoizedProps, oldProps = resolveClassComponentProps(Component2, unresolvedOldProps);
        context.props = oldProps;
        var oldContext = context.context, contextType$jscomp$0 = Component2.contextType;
        contextType = emptyContextObject;
        "object" === typeof contextType$jscomp$0 && null !== contextType$jscomp$0 && (contextType = readContext(contextType$jscomp$0));
        var getDerivedStateFromProps = Component2.getDerivedStateFromProps;
        contextType$jscomp$0 = "function" === typeof getDerivedStateFromProps || "function" === typeof context.getSnapshotBeforeUpdate;
        unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
        contextType$jscomp$0 || "function" !== typeof context.UNSAFE_componentWillReceiveProps && "function" !== typeof context.componentWillReceiveProps || (unresolvedOldProps || oldContext !== contextType) && callComponentWillReceiveProps(
          workInProgress2,
          context,
          nextProps,
          contextType
        );
        hasForceUpdate = false;
        var oldState = workInProgress2.memoizedState;
        context.state = oldState;
        processUpdateQueue(workInProgress2, nextProps, context, renderLanes2);
        suspendIfUpdateReadFromEntangledAsyncAction();
        oldContext = workInProgress2.memoizedState;
        unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps(
          workInProgress2,
          Component2,
          getDerivedStateFromProps,
          nextProps
        ), oldContext = workInProgress2.memoizedState), (oldProps = hasForceUpdate || checkShouldComponentUpdate(
          workInProgress2,
          Component2,
          oldProps,
          nextProps,
          oldState,
          oldContext,
          contextType
        )) ? (contextType$jscomp$0 || "function" !== typeof context.UNSAFE_componentWillMount && "function" !== typeof context.componentWillMount || ("function" === typeof context.componentWillMount && context.componentWillMount(), "function" === typeof context.UNSAFE_componentWillMount && context.UNSAFE_componentWillMount()), "function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308)) : ("function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), context.props = nextProps, context.state = oldContext, context.context = contextType, nextProps = oldProps) : ("function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308), nextProps = false);
      } else {
        context = workInProgress2.stateNode;
        cloneUpdateQueue(current, workInProgress2);
        contextType = workInProgress2.memoizedProps;
        contextType$jscomp$0 = resolveClassComponentProps(Component2, contextType);
        context.props = contextType$jscomp$0;
        getDerivedStateFromProps = workInProgress2.pendingProps;
        oldState = context.context;
        oldContext = Component2.contextType;
        oldProps = emptyContextObject;
        "object" === typeof oldContext && null !== oldContext && (oldProps = readContext(oldContext));
        unresolvedOldProps = Component2.getDerivedStateFromProps;
        (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof context.getSnapshotBeforeUpdate) || "function" !== typeof context.UNSAFE_componentWillReceiveProps && "function" !== typeof context.componentWillReceiveProps || (contextType !== getDerivedStateFromProps || oldState !== oldProps) && callComponentWillReceiveProps(
          workInProgress2,
          context,
          nextProps,
          oldProps
        );
        hasForceUpdate = false;
        oldState = workInProgress2.memoizedState;
        context.state = oldState;
        processUpdateQueue(workInProgress2, nextProps, context, renderLanes2);
        suspendIfUpdateReadFromEntangledAsyncAction();
        var newState = workInProgress2.memoizedState;
        contextType !== getDerivedStateFromProps || oldState !== newState || hasForceUpdate || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
          workInProgress2,
          Component2,
          unresolvedOldProps,
          nextProps
        ), newState = workInProgress2.memoizedState), (contextType$jscomp$0 = hasForceUpdate || checkShouldComponentUpdate(
          workInProgress2,
          Component2,
          contextType$jscomp$0,
          nextProps,
          oldState,
          newState,
          oldProps
        ) || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies)) ? (oldContext || "function" !== typeof context.UNSAFE_componentWillUpdate && "function" !== typeof context.componentWillUpdate || ("function" === typeof context.componentWillUpdate && context.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof context.UNSAFE_componentWillUpdate && context.UNSAFE_componentWillUpdate(
          nextProps,
          newState,
          oldProps
        )), "function" === typeof context.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof context.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof context.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), context.props = nextProps, context.state = newState, context.context = oldProps, nextProps = contextType$jscomp$0) : ("function" !== typeof context.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), nextProps = false);
      }
      context = nextProps;
      markRef(current, workInProgress2);
      nextProps = 0 !== (workInProgress2.flags & 128);
      context || nextProps ? (context = workInProgress2.stateNode, Component2 = nextProps && "function" !== typeof Component2.getDerivedStateFromError ? null : context.render(), workInProgress2.flags |= 1, null !== current && nextProps ? (workInProgress2.child = reconcileChildFibers(
        workInProgress2,
        current.child,
        null,
        renderLanes2
      ), workInProgress2.child = reconcileChildFibers(
        workInProgress2,
        null,
        Component2,
        renderLanes2
      )) : reconcileChildren(current, workInProgress2, Component2, renderLanes2), workInProgress2.memoizedState = context.state, current = workInProgress2.child) : current = bailoutOnAlreadyFinishedWork(
        current,
        workInProgress2,
        renderLanes2
      );
      return current;
    }
    function mountHostRootWithoutHydrating(current, workInProgress2, nextChildren, renderLanes2) {
      resetHydrationState();
      workInProgress2.flags |= 256;
      reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
      return workInProgress2.child;
    }
    var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: 0 };
    function mountSuspenseOffscreenState(renderLanes2) {
      return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
    }
    function getRemainingWorkInPrimaryTree(current, primaryTreeDidDefer, renderLanes2) {
      current = null !== current ? current.childLanes & ~renderLanes2 : 0;
      primaryTreeDidDefer && (current |= workInProgressDeferredLane);
      return current;
    }
    function updateSuspenseComponent(current, workInProgress2, renderLanes2) {
      var nextProps = workInProgress2.pendingProps, showFallback = false, didSuspend = 0 !== (workInProgress2.flags & 128), JSCompiler_temp;
      (JSCompiler_temp = didSuspend) || (JSCompiler_temp = null !== current && null === current.memoizedState ? false : 0 !== (suspenseStackCursor.current & 2));
      JSCompiler_temp && (showFallback = true, workInProgress2.flags &= -129);
      JSCompiler_temp = 0 !== (workInProgress2.flags & 32);
      workInProgress2.flags &= -33;
      if (null === current) {
        if (isHydrating) {
          showFallback ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack();
          if (isHydrating) {
            var nextInstance = nextHydratableInstance, JSCompiler_temp$jscomp$0;
            if (JSCompiler_temp$jscomp$0 = nextInstance) {
              c: {
                JSCompiler_temp$jscomp$0 = nextInstance;
                for (nextInstance = rootOrSingletonContext; 8 !== JSCompiler_temp$jscomp$0.nodeType; ) {
                  if (!nextInstance) {
                    nextInstance = null;
                    break c;
                  }
                  JSCompiler_temp$jscomp$0 = getNextHydratable(
                    JSCompiler_temp$jscomp$0.nextSibling
                  );
                  if (null === JSCompiler_temp$jscomp$0) {
                    nextInstance = null;
                    break c;
                  }
                }
                nextInstance = JSCompiler_temp$jscomp$0;
              }
              null !== nextInstance ? (workInProgress2.memoizedState = {
                dehydrated: nextInstance,
                treeContext: null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null,
                retryLane: 536870912
              }, JSCompiler_temp$jscomp$0 = createFiberImplClass(
                18,
                null,
                null,
                0
              ), JSCompiler_temp$jscomp$0.stateNode = nextInstance, JSCompiler_temp$jscomp$0.return = workInProgress2, workInProgress2.child = JSCompiler_temp$jscomp$0, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, JSCompiler_temp$jscomp$0 = true) : JSCompiler_temp$jscomp$0 = false;
            }
            JSCompiler_temp$jscomp$0 || throwOnHydrationMismatch(workInProgress2);
          }
          nextInstance = workInProgress2.memoizedState;
          if (null !== nextInstance && (nextInstance = nextInstance.dehydrated, null !== nextInstance))
            return "$!" === nextInstance.data ? workInProgress2.lanes = 16 : workInProgress2.lanes = 536870912, null;
          popSuspenseHandler(workInProgress2);
        }
        nextInstance = nextProps.children;
        nextProps = nextProps.fallback;
        if (showFallback)
          return reuseSuspenseHandlerOnStack(), showFallback = workInProgress2.mode, nextInstance = mountWorkInProgressOffscreenFiber(
            { mode: "hidden", children: nextInstance },
            showFallback
          ), nextProps = createFiberFromFragment(
            nextProps,
            showFallback,
            renderLanes2,
            null
          ), nextInstance.return = workInProgress2, nextProps.return = workInProgress2, nextInstance.sibling = nextProps, workInProgress2.child = nextInstance, showFallback = workInProgress2.child, showFallback.memoizedState = mountSuspenseOffscreenState(renderLanes2), showFallback.childLanes = getRemainingWorkInPrimaryTree(
            current,
            JSCompiler_temp,
            renderLanes2
          ), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
        pushPrimaryTreeSuspenseHandler(workInProgress2);
        return mountSuspensePrimaryChildren(workInProgress2, nextInstance);
      }
      JSCompiler_temp$jscomp$0 = current.memoizedState;
      if (null !== JSCompiler_temp$jscomp$0 && (nextInstance = JSCompiler_temp$jscomp$0.dehydrated, null !== nextInstance)) {
        if (didSuspend)
          workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
            current,
            workInProgress2,
            renderLanes2
          )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(), workInProgress2.child = current.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, nextProps = mountWorkInProgressOffscreenFiber(
            { mode: "visible", children: nextProps.children },
            nextInstance
          ), showFallback = createFiberFromFragment(
            showFallback,
            nextInstance,
            renderLanes2,
            null
          ), showFallback.flags |= 2, nextProps.return = workInProgress2, showFallback.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, reconcileChildFibers(
            workInProgress2,
            current.child,
            null,
            renderLanes2
          ), nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(
            current,
            JSCompiler_temp,
            renderLanes2
          ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = showFallback);
        else if (pushPrimaryTreeSuspenseHandler(workInProgress2), "$!" === nextInstance.data) {
          JSCompiler_temp = nextInstance.nextSibling && nextInstance.nextSibling.dataset;
          if (JSCompiler_temp) var digest = JSCompiler_temp.dgst;
          JSCompiler_temp = digest;
          nextProps = Error(formatProdErrorMessage(419));
          nextProps.stack = "";
          nextProps.digest = JSCompiler_temp;
          queueHydrationError({ value: nextProps, source: null, stack: null });
          workInProgress2 = retrySuspenseComponentWithoutHydrating(
            current,
            workInProgress2,
            renderLanes2
          );
        } else if (didReceiveUpdate || propagateParentContextChanges(current, workInProgress2, renderLanes2, false), JSCompiler_temp = 0 !== (renderLanes2 & current.childLanes), didReceiveUpdate || JSCompiler_temp) {
          JSCompiler_temp = workInProgressRoot;
          if (null !== JSCompiler_temp) {
            nextProps = renderLanes2 & -renderLanes2;
            if (0 !== (nextProps & 42)) nextProps = 1;
            else
              switch (nextProps) {
                case 2:
                  nextProps = 1;
                  break;
                case 8:
                  nextProps = 4;
                  break;
                case 32:
                  nextProps = 16;
                  break;
                case 128:
                case 256:
                case 512:
                case 1024:
                case 2048:
                case 4096:
                case 8192:
                case 16384:
                case 32768:
                case 65536:
                case 131072:
                case 262144:
                case 524288:
                case 1048576:
                case 2097152:
                case 4194304:
                case 8388608:
                case 16777216:
                case 33554432:
                  nextProps = 64;
                  break;
                case 268435456:
                  nextProps = 134217728;
                  break;
                default:
                  nextProps = 0;
              }
            nextProps = 0 !== (nextProps & (JSCompiler_temp.suspendedLanes | renderLanes2)) ? 0 : nextProps;
            if (0 !== nextProps && nextProps !== JSCompiler_temp$jscomp$0.retryLane)
              throw JSCompiler_temp$jscomp$0.retryLane = nextProps, enqueueConcurrentRenderForLane(current, nextProps), scheduleUpdateOnFiber(JSCompiler_temp, current, nextProps), SelectiveHydrationException;
          }
          "$?" === nextInstance.data || renderDidSuspendDelayIfPossible();
          workInProgress2 = retrySuspenseComponentWithoutHydrating(
            current,
            workInProgress2,
            renderLanes2
          );
        } else
          "$?" === nextInstance.data ? (workInProgress2.flags |= 128, workInProgress2.child = current.child, workInProgress2 = retryDehydratedSuspenseBoundary.bind(
            null,
            current
          ), nextInstance._reactRetry = workInProgress2, workInProgress2 = null) : (current = JSCompiler_temp$jscomp$0.treeContext, nextHydratableInstance = getNextHydratable(
            nextInstance.nextSibling
          ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = false, null !== current && (idStack[idStackIndex++] = treeContextId, idStack[idStackIndex++] = treeContextOverflow, idStack[idStackIndex++] = treeContextProvider, treeContextId = current.id, treeContextOverflow = current.overflow, treeContextProvider = workInProgress2), workInProgress2 = mountSuspensePrimaryChildren(
            workInProgress2,
            nextProps.children
          ), workInProgress2.flags |= 4096);
        return workInProgress2;
      }
      if (showFallback)
        return reuseSuspenseHandlerOnStack(), showFallback = nextProps.fallback, nextInstance = workInProgress2.mode, JSCompiler_temp$jscomp$0 = current.child, digest = JSCompiler_temp$jscomp$0.sibling, nextProps = createWorkInProgress(JSCompiler_temp$jscomp$0, {
          mode: "hidden",
          children: nextProps.children
        }), nextProps.subtreeFlags = JSCompiler_temp$jscomp$0.subtreeFlags & 31457280, null !== digest ? showFallback = createWorkInProgress(digest, showFallback) : (showFallback = createFiberFromFragment(
          showFallback,
          nextInstance,
          renderLanes2,
          null
        ), showFallback.flags |= 2), showFallback.return = workInProgress2, nextProps.return = workInProgress2, nextProps.sibling = showFallback, workInProgress2.child = nextProps, nextProps = showFallback, showFallback = workInProgress2.child, nextInstance = current.child.memoizedState, null === nextInstance ? nextInstance = mountSuspenseOffscreenState(renderLanes2) : (JSCompiler_temp$jscomp$0 = nextInstance.cachePool, null !== JSCompiler_temp$jscomp$0 ? (digest = CacheContext._currentValue, JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0.parent !== digest ? { parent: digest, pool: digest } : JSCompiler_temp$jscomp$0) : JSCompiler_temp$jscomp$0 = getSuspendedCache(), nextInstance = {
          baseLanes: nextInstance.baseLanes | renderLanes2,
          cachePool: JSCompiler_temp$jscomp$0
        }), showFallback.memoizedState = nextInstance, showFallback.childLanes = getRemainingWorkInPrimaryTree(
          current,
          JSCompiler_temp,
          renderLanes2
        ), workInProgress2.memoizedState = SUSPENDED_MARKER, nextProps;
      pushPrimaryTreeSuspenseHandler(workInProgress2);
      renderLanes2 = current.child;
      current = renderLanes2.sibling;
      renderLanes2 = createWorkInProgress(renderLanes2, {
        mode: "visible",
        children: nextProps.children
      });
      renderLanes2.return = workInProgress2;
      renderLanes2.sibling = null;
      null !== current && (JSCompiler_temp = workInProgress2.deletions, null === JSCompiler_temp ? (workInProgress2.deletions = [current], workInProgress2.flags |= 16) : JSCompiler_temp.push(current));
      workInProgress2.child = renderLanes2;
      workInProgress2.memoizedState = null;
      return renderLanes2;
    }
    function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
      primaryChildren = mountWorkInProgressOffscreenFiber(
        { mode: "visible", children: primaryChildren },
        workInProgress2.mode
      );
      primaryChildren.return = workInProgress2;
      return workInProgress2.child = primaryChildren;
    }
    function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
      return createFiberFromOffscreen(offscreenProps, mode, 0, null);
    }
    function retrySuspenseComponentWithoutHydrating(current, workInProgress2, renderLanes2) {
      reconcileChildFibers(workInProgress2, current.child, null, renderLanes2);
      current = mountSuspensePrimaryChildren(
        workInProgress2,
        workInProgress2.pendingProps.children
      );
      current.flags |= 2;
      workInProgress2.memoizedState = null;
      return current;
    }
    function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
      fiber.lanes |= renderLanes2;
      var alternate = fiber.alternate;
      null !== alternate && (alternate.lanes |= renderLanes2);
      scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot);
    }
    function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) {
      var renderState = workInProgress2.memoizedState;
      null === renderState ? workInProgress2.memoizedState = {
        isBackwards,
        rendering: null,
        renderingStartTime: 0,
        last: lastContentRow,
        tail,
        tailMode
      } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode);
    }
    function updateSuspenseListComponent(current, workInProgress2, renderLanes2) {
      var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail;
      reconcileChildren(current, workInProgress2, nextProps.children, renderLanes2);
      nextProps = suspenseStackCursor.current;
      if (0 !== (nextProps & 2))
        nextProps = nextProps & 1 | 2, workInProgress2.flags |= 128;
      else {
        if (null !== current && 0 !== (current.flags & 128))
          a: for (current = workInProgress2.child; null !== current; ) {
            if (13 === current.tag)
              null !== current.memoizedState && scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
            else if (19 === current.tag)
              scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
            else if (null !== current.child) {
              current.child.return = current;
              current = current.child;
              continue;
            }
            if (current === workInProgress2) break a;
            for (; null === current.sibling; ) {
              if (null === current.return || current.return === workInProgress2)
                break a;
              current = current.return;
            }
            current.sibling.return = current.return;
            current = current.sibling;
          }
        nextProps &= 1;
      }
      push$1(suspenseStackCursor, nextProps);
      switch (revealOrder) {
        case "forwards":
          renderLanes2 = workInProgress2.child;
          for (revealOrder = null; null !== renderLanes2; )
            current = renderLanes2.alternate, null !== current && null === findFirstSuspended(current) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
          renderLanes2 = revealOrder;
          null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
          initSuspenseListRenderState(
            workInProgress2,
            false,
            revealOrder,
            renderLanes2,
            tailMode
          );
          break;
        case "backwards":
          renderLanes2 = null;
          revealOrder = workInProgress2.child;
          for (workInProgress2.child = null; null !== revealOrder; ) {
            current = revealOrder.alternate;
            if (null !== current && null === findFirstSuspended(current)) {
              workInProgress2.child = revealOrder;
              break;
            }
            current = revealOrder.sibling;
            revealOrder.sibling = renderLanes2;
            renderLanes2 = revealOrder;
            revealOrder = current;
          }
          initSuspenseListRenderState(
            workInProgress2,
            true,
            renderLanes2,
            null,
            tailMode
          );
          break;
        case "together":
          initSuspenseListRenderState(workInProgress2, false, null, null, void 0);
          break;
        default:
          workInProgress2.memoizedState = null;
      }
      return workInProgress2.child;
    }
    function bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2) {
      null !== current && (workInProgress2.dependencies = current.dependencies);
      workInProgressRootSkippedLanes |= workInProgress2.lanes;
      if (0 === (renderLanes2 & workInProgress2.childLanes))
        if (null !== current) {
          if (propagateParentContextChanges(
            current,
            workInProgress2,
            renderLanes2,
            false
          ), 0 === (renderLanes2 & workInProgress2.childLanes))
            return null;
        } else return null;
      if (null !== current && workInProgress2.child !== current.child)
        throw Error(formatProdErrorMessage(153));
      if (null !== workInProgress2.child) {
        current = workInProgress2.child;
        renderLanes2 = createWorkInProgress(current, current.pendingProps);
        workInProgress2.child = renderLanes2;
        for (renderLanes2.return = workInProgress2; null !== current.sibling; )
          current = current.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current, current.pendingProps), renderLanes2.return = workInProgress2;
        renderLanes2.sibling = null;
      }
      return workInProgress2.child;
    }
    function checkScheduledUpdateOrContext(current, renderLanes2) {
      if (0 !== (current.lanes & renderLanes2)) return true;
      current = current.dependencies;
      return null !== current && checkIfContextChanged(current) ? true : false;
    }
    function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress2, renderLanes2) {
      switch (workInProgress2.tag) {
        case 3:
          pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
          pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
          resetHydrationState();
          break;
        case 27:
        case 5:
          pushHostContext(workInProgress2);
          break;
        case 4:
          pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
          break;
        case 10:
          pushProvider(
            workInProgress2,
            workInProgress2.type,
            workInProgress2.memoizedProps.value
          );
          break;
        case 13:
          var state = workInProgress2.memoizedState;
          if (null !== state) {
            if (null !== state.dehydrated)
              return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
            if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
              return updateSuspenseComponent(current, workInProgress2, renderLanes2);
            pushPrimaryTreeSuspenseHandler(workInProgress2);
            current = bailoutOnAlreadyFinishedWork(
              current,
              workInProgress2,
              renderLanes2
            );
            return null !== current ? current.sibling : null;
          }
          pushPrimaryTreeSuspenseHandler(workInProgress2);
          break;
        case 19:
          var didSuspendBefore = 0 !== (current.flags & 128);
          state = 0 !== (renderLanes2 & workInProgress2.childLanes);
          state || (propagateParentContextChanges(
            current,
            workInProgress2,
            renderLanes2,
            false
          ), state = 0 !== (renderLanes2 & workInProgress2.childLanes));
          if (didSuspendBefore) {
            if (state)
              return updateSuspenseListComponent(
                current,
                workInProgress2,
                renderLanes2
              );
            workInProgress2.flags |= 128;
          }
          didSuspendBefore = workInProgress2.memoizedState;
          null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
          push$1(suspenseStackCursor, suspenseStackCursor.current);
          if (state) break;
          else return null;
        case 22:
        case 23:
          return workInProgress2.lanes = 0, updateOffscreenComponent(current, workInProgress2, renderLanes2);
        case 24:
          pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
      }
      return bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
    }
    function beginWork(current, workInProgress2, renderLanes2) {
      if (null !== current)
        if (current.memoizedProps !== workInProgress2.pendingProps)
          didReceiveUpdate = true;
        else {
          if (!checkScheduledUpdateOrContext(current, renderLanes2) && 0 === (workInProgress2.flags & 128))
            return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
              current,
              workInProgress2,
              renderLanes2
            );
          didReceiveUpdate = 0 !== (current.flags & 131072) ? true : false;
        }
      else
        didReceiveUpdate = false, isHydrating && 0 !== (workInProgress2.flags & 1048576) && pushTreeId(workInProgress2, treeForkCount, workInProgress2.index);
      workInProgress2.lanes = 0;
      switch (workInProgress2.tag) {
        case 16:
          a: {
            current = workInProgress2.pendingProps;
            var lazyComponent = workInProgress2.elementType, init = lazyComponent._init;
            lazyComponent = init(lazyComponent._payload);
            workInProgress2.type = lazyComponent;
            if ("function" === typeof lazyComponent)
              shouldConstruct(lazyComponent) ? (current = resolveClassComponentProps(lazyComponent, current), workInProgress2.tag = 1, workInProgress2 = updateClassComponent(
                null,
                workInProgress2,
                lazyComponent,
                current,
                renderLanes2
              )) : (workInProgress2.tag = 0, workInProgress2 = updateFunctionComponent(
                null,
                workInProgress2,
                lazyComponent,
                current,
                renderLanes2
              ));
            else {
              if (void 0 !== lazyComponent && null !== lazyComponent) {
                if (init = lazyComponent.$$typeof, init === REACT_FORWARD_REF_TYPE) {
                  workInProgress2.tag = 11;
                  workInProgress2 = updateForwardRef(
                    null,
                    workInProgress2,
                    lazyComponent,
                    current,
                    renderLanes2
                  );
                  break a;
                } else if (init === REACT_MEMO_TYPE) {
                  workInProgress2.tag = 14;
                  workInProgress2 = updateMemoComponent(
                    null,
                    workInProgress2,
                    lazyComponent,
                    current,
                    renderLanes2
                  );
                  break a;
                }
              }
              workInProgress2 = getComponentNameFromType(lazyComponent) || lazyComponent;
              throw Error(formatProdErrorMessage(306, workInProgress2, ""));
            }
          }
          return workInProgress2;
        case 0:
          return updateFunctionComponent(
            current,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 1:
          return lazyComponent = workInProgress2.type, init = resolveClassComponentProps(
            lazyComponent,
            workInProgress2.pendingProps
          ), updateClassComponent(
            current,
            workInProgress2,
            lazyComponent,
            init,
            renderLanes2
          );
        case 3:
          a: {
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            if (null === current) throw Error(formatProdErrorMessage(387));
            var nextProps = workInProgress2.pendingProps;
            init = workInProgress2.memoizedState;
            lazyComponent = init.element;
            cloneUpdateQueue(current, workInProgress2);
            processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
            var nextState = workInProgress2.memoizedState;
            nextProps = nextState.cache;
            pushProvider(workInProgress2, CacheContext, nextProps);
            nextProps !== init.cache && propagateContextChanges(
              workInProgress2,
              [CacheContext],
              renderLanes2,
              true
            );
            suspendIfUpdateReadFromEntangledAsyncAction();
            nextProps = nextState.element;
            if (init.isDehydrated)
              if (init = {
                element: nextProps,
                isDehydrated: false,
                cache: nextState.cache
              }, workInProgress2.updateQueue.baseState = init, workInProgress2.memoizedState = init, workInProgress2.flags & 256) {
                workInProgress2 = mountHostRootWithoutHydrating(
                  current,
                  workInProgress2,
                  nextProps,
                  renderLanes2
                );
                break a;
              } else if (nextProps !== lazyComponent) {
                lazyComponent = createCapturedValueAtFiber(
                  Error(formatProdErrorMessage(424)),
                  workInProgress2
                );
                queueHydrationError(lazyComponent);
                workInProgress2 = mountHostRootWithoutHydrating(
                  current,
                  workInProgress2,
                  nextProps,
                  renderLanes2
                );
                break a;
              } else
                for (nextHydratableInstance = getNextHydratable(
                  workInProgress2.stateNode.containerInfo.firstChild
                ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = true, renderLanes2 = mountChildFibers(
                  workInProgress2,
                  null,
                  nextProps,
                  renderLanes2
                ), workInProgress2.child = renderLanes2; renderLanes2; )
                  renderLanes2.flags = renderLanes2.flags & -3 | 4096, renderLanes2 = renderLanes2.sibling;
            else {
              resetHydrationState();
              if (nextProps === lazyComponent) {
                workInProgress2 = bailoutOnAlreadyFinishedWork(
                  current,
                  workInProgress2,
                  renderLanes2
                );
                break a;
              }
              reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
            }
            workInProgress2 = workInProgress2.child;
          }
          return workInProgress2;
        case 26:
          return markRef(current, workInProgress2), null === current ? (renderLanes2 = getResource(
            workInProgress2.type,
            null,
            workInProgress2.pendingProps,
            null
          )) ? workInProgress2.memoizedState = renderLanes2 : isHydrating || (renderLanes2 = workInProgress2.type, current = workInProgress2.pendingProps, lazyComponent = getOwnerDocumentFromRootContainer(
            rootInstanceStackCursor.current
          ).createElement(renderLanes2), lazyComponent[internalInstanceKey] = workInProgress2, lazyComponent[internalPropsKey] = current, setInitialProperties(lazyComponent, renderLanes2, current), markNodeAsHoistable(lazyComponent), workInProgress2.stateNode = lazyComponent) : workInProgress2.memoizedState = getResource(
            workInProgress2.type,
            current.memoizedProps,
            workInProgress2.pendingProps,
            current.memoizedState
          ), null;
        case 27:
          return pushHostContext(workInProgress2), null === current && isHydrating && (lazyComponent = workInProgress2.stateNode = resolveSingletonInstance(
            workInProgress2.type,
            workInProgress2.pendingProps,
            rootInstanceStackCursor.current
          ), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, nextHydratableInstance = getNextHydratable(
            lazyComponent.firstChild
          )), lazyComponent = workInProgress2.pendingProps.children, null !== current || isHydrating ? reconcileChildren(
            current,
            workInProgress2,
            lazyComponent,
            renderLanes2
          ) : workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            null,
            lazyComponent,
            renderLanes2
          ), markRef(current, workInProgress2), workInProgress2.child;
        case 5:
          if (null === current && isHydrating) {
            if (init = lazyComponent = nextHydratableInstance)
              lazyComponent = canHydrateInstance(
                lazyComponent,
                workInProgress2.type,
                workInProgress2.pendingProps,
                rootOrSingletonContext
              ), null !== lazyComponent ? (workInProgress2.stateNode = lazyComponent, hydrationParentFiber = workInProgress2, nextHydratableInstance = getNextHydratable(
                lazyComponent.firstChild
              ), rootOrSingletonContext = false, init = true) : init = false;
            init || throwOnHydrationMismatch(workInProgress2);
          }
          pushHostContext(workInProgress2);
          init = workInProgress2.type;
          nextProps = workInProgress2.pendingProps;
          nextState = null !== current ? current.memoizedProps : null;
          lazyComponent = nextProps.children;
          shouldSetTextContent(init, nextProps) ? lazyComponent = null : null !== nextState && shouldSetTextContent(init, nextState) && (workInProgress2.flags |= 32);
          null !== workInProgress2.memoizedState && (init = renderWithHooks(
            current,
            workInProgress2,
            TransitionAwareHostComponent,
            null,
            null,
            renderLanes2
          ), HostTransitionContext._currentValue = init);
          markRef(current, workInProgress2);
          reconcileChildren(current, workInProgress2, lazyComponent, renderLanes2);
          return workInProgress2.child;
        case 6:
          if (null === current && isHydrating) {
            if (current = renderLanes2 = nextHydratableInstance)
              renderLanes2 = canHydrateTextInstance(
                renderLanes2,
                workInProgress2.pendingProps,
                rootOrSingletonContext
              ), null !== renderLanes2 ? (workInProgress2.stateNode = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, current = true) : current = false;
            current || throwOnHydrationMismatch(workInProgress2);
          }
          return null;
        case 13:
          return updateSuspenseComponent(current, workInProgress2, renderLanes2);
        case 4:
          return pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          ), lazyComponent = workInProgress2.pendingProps, null === current ? workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            null,
            lazyComponent,
            renderLanes2
          ) : reconcileChildren(
            current,
            workInProgress2,
            lazyComponent,
            renderLanes2
          ), workInProgress2.child;
        case 11:
          return updateForwardRef(
            current,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 7:
          return reconcileChildren(
            current,
            workInProgress2,
            workInProgress2.pendingProps,
            renderLanes2
          ), workInProgress2.child;
        case 8:
          return reconcileChildren(
            current,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 12:
          return reconcileChildren(
            current,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 10:
          return lazyComponent = workInProgress2.pendingProps, pushProvider(workInProgress2, workInProgress2.type, lazyComponent.value), reconcileChildren(
            current,
            workInProgress2,
            lazyComponent.children,
            renderLanes2
          ), workInProgress2.child;
        case 9:
          return init = workInProgress2.type._context, lazyComponent = workInProgress2.pendingProps.children, prepareToReadContext(workInProgress2), init = readContext(init), lazyComponent = lazyComponent(init), workInProgress2.flags |= 1, reconcileChildren(current, workInProgress2, lazyComponent, renderLanes2), workInProgress2.child;
        case 14:
          return updateMemoComponent(
            current,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 15:
          return updateSimpleMemoComponent(
            current,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 19:
          return updateSuspenseListComponent(current, workInProgress2, renderLanes2);
        case 22:
          return updateOffscreenComponent(current, workInProgress2, renderLanes2);
        case 24:
          return prepareToReadContext(workInProgress2), lazyComponent = readContext(CacheContext), null === current ? (init = peekCacheFromPool(), null === init && (init = workInProgressRoot, nextProps = createCache(), init.pooledCache = nextProps, nextProps.refCount++, null !== nextProps && (init.pooledCacheLanes |= renderLanes2), init = nextProps), workInProgress2.memoizedState = {
            parent: lazyComponent,
            cache: init
          }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, init)) : (0 !== (current.lanes & renderLanes2) && (cloneUpdateQueue(current, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), init = current.memoizedState, nextProps = workInProgress2.memoizedState, init.parent !== lazyComponent ? (init = { parent: lazyComponent, cache: lazyComponent }, workInProgress2.memoizedState = init, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = init), pushProvider(workInProgress2, CacheContext, lazyComponent)) : (lazyComponent = nextProps.cache, pushProvider(workInProgress2, CacheContext, lazyComponent), lazyComponent !== init.cache && propagateContextChanges(
            workInProgress2,
            [CacheContext],
            renderLanes2,
            true
          ))), reconcileChildren(
            current,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 29:
          throw workInProgress2.pendingProps;
      }
      throw Error(formatProdErrorMessage(156, workInProgress2.tag));
    }
    var valueCursor = createCursor(null), currentlyRenderingFiber = null, lastContextDependency = null;
    function pushProvider(providerFiber, context, nextValue) {
      push$1(valueCursor, context._currentValue);
      context._currentValue = nextValue;
    }
    function popProvider(context) {
      context._currentValue = valueCursor.current;
      pop$1(valueCursor);
    }
    function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
      for (; null !== parent; ) {
        var alternate = parent.alternate;
        (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
        if (parent === propagationRoot) break;
        parent = parent.return;
      }
    }
    function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
      var fiber = workInProgress2.child;
      null !== fiber && (fiber.return = workInProgress2);
      for (; null !== fiber; ) {
        var list2 = fiber.dependencies;
        if (null !== list2) {
          var nextFiber = fiber.child;
          list2 = list2.firstContext;
          a: for (; null !== list2; ) {
            var dependency = list2;
            list2 = fiber;
            for (var i2 = 0; i2 < contexts.length; i2++)
              if (dependency.context === contexts[i2]) {
                list2.lanes |= renderLanes2;
                dependency = list2.alternate;
                null !== dependency && (dependency.lanes |= renderLanes2);
                scheduleContextWorkOnParentPath(
                  list2.return,
                  renderLanes2,
                  workInProgress2
                );
                forcePropagateEntireTree || (nextFiber = null);
                break a;
              }
            list2 = dependency.next;
          }
        } else if (18 === fiber.tag) {
          nextFiber = fiber.return;
          if (null === nextFiber) throw Error(formatProdErrorMessage(341));
          nextFiber.lanes |= renderLanes2;
          list2 = nextFiber.alternate;
          null !== list2 && (list2.lanes |= renderLanes2);
          scheduleContextWorkOnParentPath(nextFiber, renderLanes2, workInProgress2);
          nextFiber = null;
        } else nextFiber = fiber.child;
        if (null !== nextFiber) nextFiber.return = fiber;
        else
          for (nextFiber = fiber; null !== nextFiber; ) {
            if (nextFiber === workInProgress2) {
              nextFiber = null;
              break;
            }
            fiber = nextFiber.sibling;
            if (null !== fiber) {
              fiber.return = nextFiber.return;
              nextFiber = fiber;
              break;
            }
            nextFiber = nextFiber.return;
          }
        fiber = nextFiber;
      }
    }
    function propagateParentContextChanges(current, workInProgress2, renderLanes2, forcePropagateEntireTree) {
      current = null;
      for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
        if (!isInsidePropagationBailout) {
          if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
          else if (0 !== (parent.flags & 262144)) break;
        }
        if (10 === parent.tag) {
          var currentParent = parent.alternate;
          if (null === currentParent) throw Error(formatProdErrorMessage(387));
          currentParent = currentParent.memoizedProps;
          if (null !== currentParent) {
            var context = parent.type;
            objectIs(parent.pendingProps.value, currentParent.value) || (null !== current ? current.push(context) : current = [context]);
          }
        } else if (parent === hostTransitionProviderCursor.current) {
          currentParent = parent.alternate;
          if (null === currentParent) throw Error(formatProdErrorMessage(387));
          currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current ? current.push(HostTransitionContext) : current = [HostTransitionContext]);
        }
        parent = parent.return;
      }
      null !== current && propagateContextChanges(
        workInProgress2,
        current,
        renderLanes2,
        forcePropagateEntireTree
      );
      workInProgress2.flags |= 262144;
    }
    function checkIfContextChanged(currentDependencies) {
      for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
        if (!objectIs(
          currentDependencies.context._currentValue,
          currentDependencies.memoizedValue
        ))
          return true;
        currentDependencies = currentDependencies.next;
      }
      return false;
    }
    function prepareToReadContext(workInProgress2) {
      currentlyRenderingFiber = workInProgress2;
      lastContextDependency = null;
      workInProgress2 = workInProgress2.dependencies;
      null !== workInProgress2 && (workInProgress2.firstContext = null);
    }
    function readContext(context) {
      return readContextForConsumer(currentlyRenderingFiber, context);
    }
    function readContextDuringReconciliation(consumer, context) {
      null === currentlyRenderingFiber && prepareToReadContext(consumer);
      return readContextForConsumer(consumer, context);
    }
    function readContextForConsumer(consumer, context) {
      var value2 = context._currentValue;
      context = { context, memoizedValue: value2, next: null };
      if (null === lastContextDependency) {
        if (null === consumer) throw Error(formatProdErrorMessage(308));
        lastContextDependency = context;
        consumer.dependencies = { lanes: 0, firstContext: context };
        consumer.flags |= 524288;
      } else lastContextDependency = lastContextDependency.next = context;
      return value2;
    }
    var hasForceUpdate = false;
    function initializeUpdateQueue(fiber) {
      fiber.updateQueue = {
        baseState: fiber.memoizedState,
        firstBaseUpdate: null,
        lastBaseUpdate: null,
        shared: { pending: null, lanes: 0, hiddenCallbacks: null },
        callbacks: null
      };
    }
    function cloneUpdateQueue(current, workInProgress2) {
      current = current.updateQueue;
      workInProgress2.updateQueue === current && (workInProgress2.updateQueue = {
        baseState: current.baseState,
        firstBaseUpdate: current.firstBaseUpdate,
        lastBaseUpdate: current.lastBaseUpdate,
        shared: current.shared,
        callbacks: null
      });
    }
    function createUpdate(lane) {
      return { lane, tag: 0, payload: null, callback: null, next: null };
    }
    function enqueueUpdate(fiber, update, lane) {
      var updateQueue = fiber.updateQueue;
      if (null === updateQueue) return null;
      updateQueue = updateQueue.shared;
      if (0 !== (executionContext & 2)) {
        var pending = updateQueue.pending;
        null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
        updateQueue.pending = update;
        update = getRootForUpdatedFiber(fiber);
        markUpdateLaneFromFiberToRoot(fiber, null, lane);
        return update;
      }
      enqueueUpdate$1(fiber, updateQueue, update, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function entangleTransitions(root2, fiber, lane) {
      fiber = fiber.updateQueue;
      if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194176))) {
        var queueLanes = fiber.lanes;
        queueLanes &= root2.pendingLanes;
        lane |= queueLanes;
        fiber.lanes = lane;
        markRootEntangled(root2, lane);
      }
    }
    function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
      var queue = workInProgress2.updateQueue, current = workInProgress2.alternate;
      if (null !== current && (current = current.updateQueue, queue === current)) {
        var newFirst = null, newLast = null;
        queue = queue.firstBaseUpdate;
        if (null !== queue) {
          do {
            var clone2 = {
              lane: queue.lane,
              tag: queue.tag,
              payload: queue.payload,
              callback: null,
              next: null
            };
            null === newLast ? newFirst = newLast = clone2 : newLast = newLast.next = clone2;
            queue = queue.next;
          } while (null !== queue);
          null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
        } else newFirst = newLast = capturedUpdate;
        queue = {
          baseState: current.baseState,
          firstBaseUpdate: newFirst,
          lastBaseUpdate: newLast,
          shared: current.shared,
          callbacks: current.callbacks
        };
        workInProgress2.updateQueue = queue;
        return;
      }
      workInProgress2 = queue.lastBaseUpdate;
      null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
      queue.lastBaseUpdate = capturedUpdate;
    }
    var didReadFromEntangledAsyncAction = false;
    function suspendIfUpdateReadFromEntangledAsyncAction() {
      if (didReadFromEntangledAsyncAction) {
        var entangledActionThenable = currentEntangledActionThenable;
        if (null !== entangledActionThenable) throw entangledActionThenable;
      }
    }
    function processUpdateQueue(workInProgress$jscomp$0, props, instance$jscomp$0, renderLanes2) {
      didReadFromEntangledAsyncAction = false;
      var queue = workInProgress$jscomp$0.updateQueue;
      hasForceUpdate = false;
      var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
      if (null !== pendingQueue) {
        queue.shared.pending = null;
        var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
        lastPendingUpdate.next = null;
        null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
        lastBaseUpdate = lastPendingUpdate;
        var current = workInProgress$jscomp$0.alternate;
        null !== current && (current = current.updateQueue, pendingQueue = current.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current.lastBaseUpdate = lastPendingUpdate));
      }
      if (null !== firstBaseUpdate) {
        var newState = queue.baseState;
        lastBaseUpdate = 0;
        current = firstPendingUpdate = lastPendingUpdate = null;
        pendingQueue = firstBaseUpdate;
        do {
          var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
          if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
            0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
            null !== current && (current = current.next = {
              lane: 0,
              tag: pendingQueue.tag,
              payload: pendingQueue.payload,
              callback: null,
              next: null
            });
            a: {
              var workInProgress2 = workInProgress$jscomp$0, update = pendingQueue;
              updateLane = props;
              var instance = instance$jscomp$0;
              switch (update.tag) {
                case 1:
                  workInProgress2 = update.payload;
                  if ("function" === typeof workInProgress2) {
                    newState = workInProgress2.call(instance, newState, updateLane);
                    break a;
                  }
                  newState = workInProgress2;
                  break a;
                case 3:
                  workInProgress2.flags = workInProgress2.flags & -65537 | 128;
                case 0:
                  workInProgress2 = update.payload;
                  updateLane = "function" === typeof workInProgress2 ? workInProgress2.call(instance, newState, updateLane) : workInProgress2;
                  if (null === updateLane || void 0 === updateLane) break a;
                  newState = assign$2({}, newState, updateLane);
                  break a;
                case 2:
                  hasForceUpdate = true;
              }
            }
            updateLane = pendingQueue.callback;
            null !== updateLane && (workInProgress$jscomp$0.flags |= 64, isHiddenUpdate && (workInProgress$jscomp$0.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
          } else
            isHiddenUpdate = {
              lane: updateLane,
              tag: pendingQueue.tag,
              payload: pendingQueue.payload,
              callback: pendingQueue.callback,
              next: null
            }, null === current ? (firstPendingUpdate = current = isHiddenUpdate, lastPendingUpdate = newState) : current = current.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
          pendingQueue = pendingQueue.next;
          if (null === pendingQueue)
            if (pendingQueue = queue.shared.pending, null === pendingQueue)
              break;
            else
              isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
        } while (1);
        null === current && (lastPendingUpdate = newState);
        queue.baseState = lastPendingUpdate;
        queue.firstBaseUpdate = firstPendingUpdate;
        queue.lastBaseUpdate = current;
        null === firstBaseUpdate && (queue.shared.lanes = 0);
        workInProgressRootSkippedLanes |= lastBaseUpdate;
        workInProgress$jscomp$0.lanes = lastBaseUpdate;
        workInProgress$jscomp$0.memoizedState = newState;
      }
    }
    function callCallback(callback, context) {
      if ("function" !== typeof callback)
        throw Error(formatProdErrorMessage(191, callback));
      callback.call(context);
    }
    function commitCallbacks(updateQueue, context) {
      var callbacks = updateQueue.callbacks;
      if (null !== callbacks)
        for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
          callCallback(callbacks[updateQueue], context);
    }
    function commitHookEffectListMount(flags, finishedWork) {
      try {
        var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
        if (null !== lastEffect) {
          var firstEffect = lastEffect.next;
          updateQueue = firstEffect;
          do {
            if ((updateQueue.tag & flags) === flags) {
              lastEffect = void 0;
              var create2 = updateQueue.create, inst = updateQueue.inst;
              lastEffect = create2();
              inst.destroy = lastEffect;
            }
            updateQueue = updateQueue.next;
          } while (updateQueue !== firstEffect);
        }
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor$jscomp$0) {
      try {
        var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
        if (null !== lastEffect) {
          var firstEffect = lastEffect.next;
          updateQueue = firstEffect;
          do {
            if ((updateQueue.tag & flags) === flags) {
              var inst = updateQueue.inst, destroy = inst.destroy;
              if (void 0 !== destroy) {
                inst.destroy = void 0;
                lastEffect = finishedWork;
                var nearestMountedAncestor = nearestMountedAncestor$jscomp$0;
                try {
                  destroy();
                } catch (error2) {
                  captureCommitPhaseError(
                    lastEffect,
                    nearestMountedAncestor,
                    error2
                  );
                }
              }
            }
            updateQueue = updateQueue.next;
          } while (updateQueue !== firstEffect);
        }
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function commitClassCallbacks(finishedWork) {
      var updateQueue = finishedWork.updateQueue;
      if (null !== updateQueue) {
        var instance = finishedWork.stateNode;
        try {
          commitCallbacks(updateQueue, instance);
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
    }
    function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
      instance.props = resolveClassComponentProps(
        current.type,
        current.memoizedProps
      );
      instance.state = current.memoizedState;
      try {
        instance.componentWillUnmount();
      } catch (error2) {
        captureCommitPhaseError(current, nearestMountedAncestor, error2);
      }
    }
    function safelyAttachRef(current, nearestMountedAncestor) {
      try {
        var ref = current.ref;
        if (null !== ref) {
          var instance = current.stateNode;
          switch (current.tag) {
            case 26:
            case 27:
            case 5:
              var instanceToUse = instance;
              break;
            default:
              instanceToUse = instance;
          }
          "function" === typeof ref ? current.refCleanup = ref(instanceToUse) : ref.current = instanceToUse;
        }
      } catch (error2) {
        captureCommitPhaseError(current, nearestMountedAncestor, error2);
      }
    }
    function safelyDetachRef(current, nearestMountedAncestor) {
      var ref = current.ref, refCleanup = current.refCleanup;
      if (null !== ref)
        if ("function" === typeof refCleanup)
          try {
            refCleanup();
          } catch (error2) {
            captureCommitPhaseError(current, nearestMountedAncestor, error2);
          } finally {
            current.refCleanup = null, current = current.alternate, null != current && (current.refCleanup = null);
          }
        else if ("function" === typeof ref)
          try {
            ref(null);
          } catch (error$112) {
            captureCommitPhaseError(current, nearestMountedAncestor, error$112);
          }
        else ref.current = null;
    }
    function commitHostMount(finishedWork) {
      var type = finishedWork.type, props = finishedWork.memoizedProps, instance = finishedWork.stateNode;
      try {
        a: switch (type) {
          case "button":
          case "input":
          case "select":
          case "textarea":
            props.autoFocus && instance.focus();
            break a;
          case "img":
            props.src ? instance.src = props.src : props.srcSet && (instance.srcset = props.srcSet);
        }
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function commitHostUpdate(finishedWork, newProps, oldProps) {
      try {
        var domElement = finishedWork.stateNode;
        updateProperties(domElement, finishedWork.type, oldProps, newProps);
        domElement[internalPropsKey] = newProps;
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function isHostParent(fiber) {
      return 5 === fiber.tag || 3 === fiber.tag || 26 === fiber.tag || 27 === fiber.tag || 4 === fiber.tag;
    }
    function getHostSibling(fiber) {
      a: for (; ; ) {
        for (; null === fiber.sibling; ) {
          if (null === fiber.return || isHostParent(fiber.return)) return null;
          fiber = fiber.return;
        }
        fiber.sibling.return = fiber.return;
        for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 27 !== fiber.tag && 18 !== fiber.tag; ) {
          if (fiber.flags & 2) continue a;
          if (null === fiber.child || 4 === fiber.tag) continue a;
          else fiber.child.return = fiber, fiber = fiber.child;
        }
        if (!(fiber.flags & 2)) return fiber.stateNode;
      }
    }
    function insertOrAppendPlacementNodeIntoContainer(node2, before, parent) {
      var tag = node2.tag;
      if (5 === tag || 6 === tag)
        node2 = node2.stateNode, before ? 8 === parent.nodeType ? parent.parentNode.insertBefore(node2, before) : parent.insertBefore(node2, before) : (8 === parent.nodeType ? (before = parent.parentNode, before.insertBefore(node2, parent)) : (before = parent, before.appendChild(node2)), parent = parent._reactRootContainer, null !== parent && void 0 !== parent || null !== before.onclick || (before.onclick = noop$1));
      else if (4 !== tag && 27 !== tag && (node2 = node2.child, null !== node2))
        for (insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling; null !== node2; )
          insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling;
    }
    function insertOrAppendPlacementNode(node2, before, parent) {
      var tag = node2.tag;
      if (5 === tag || 6 === tag)
        node2 = node2.stateNode, before ? parent.insertBefore(node2, before) : parent.appendChild(node2);
      else if (4 !== tag && 27 !== tag && (node2 = node2.child, null !== node2))
        for (insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling; null !== node2; )
          insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling;
    }
    var offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null, shouldFireAfterActiveInstanceBlur = false;
    function commitBeforeMutationEffects(root2, firstChild) {
      root2 = root2.containerInfo;
      eventsEnabled = _enabled;
      root2 = getActiveElementDeep(root2);
      if (hasSelectionCapabilities(root2)) {
        if ("selectionStart" in root2)
          var JSCompiler_temp = {
            start: root2.selectionStart,
            end: root2.selectionEnd
          };
        else
          a: {
            JSCompiler_temp = (JSCompiler_temp = root2.ownerDocument) && JSCompiler_temp.defaultView || window;
            var selection = JSCompiler_temp.getSelection && JSCompiler_temp.getSelection();
            if (selection && 0 !== selection.rangeCount) {
              JSCompiler_temp = selection.anchorNode;
              var anchorOffset = selection.anchorOffset, focusNode = selection.focusNode;
              selection = selection.focusOffset;
              try {
                JSCompiler_temp.nodeType, focusNode.nodeType;
              } catch (e$20) {
                JSCompiler_temp = null;
                break a;
              }
              var length = 0, start = -1, end = -1, indexWithinAnchor = 0, indexWithinFocus = 0, node2 = root2, parentNode = null;
              b: for (; ; ) {
                for (var next; ; ) {
                  node2 !== JSCompiler_temp || 0 !== anchorOffset && 3 !== node2.nodeType || (start = length + anchorOffset);
                  node2 !== focusNode || 0 !== selection && 3 !== node2.nodeType || (end = length + selection);
                  3 === node2.nodeType && (length += node2.nodeValue.length);
                  if (null === (next = node2.firstChild)) break;
                  parentNode = node2;
                  node2 = next;
                }
                for (; ; ) {
                  if (node2 === root2) break b;
                  parentNode === JSCompiler_temp && ++indexWithinAnchor === anchorOffset && (start = length);
                  parentNode === focusNode && ++indexWithinFocus === selection && (end = length);
                  if (null !== (next = node2.nextSibling)) break;
                  node2 = parentNode;
                  parentNode = node2.parentNode;
                }
                node2 = next;
              }
              JSCompiler_temp = -1 === start || -1 === end ? null : { start, end };
            } else JSCompiler_temp = null;
          }
        JSCompiler_temp = JSCompiler_temp || { start: 0, end: 0 };
      } else JSCompiler_temp = null;
      selectionInformation = { focusedElem: root2, selectionRange: JSCompiler_temp };
      _enabled = false;
      for (nextEffect = firstChild; null !== nextEffect; )
        if (firstChild = nextEffect, root2 = firstChild.child, 0 !== (firstChild.subtreeFlags & 1028) && null !== root2)
          root2.return = firstChild, nextEffect = root2;
        else
          for (; null !== nextEffect; ) {
            firstChild = nextEffect;
            focusNode = firstChild.alternate;
            root2 = firstChild.flags;
            switch (firstChild.tag) {
              case 0:
                break;
              case 11:
              case 15:
                break;
              case 1:
                if (0 !== (root2 & 1024) && null !== focusNode) {
                  root2 = void 0;
                  JSCompiler_temp = firstChild;
                  anchorOffset = focusNode.memoizedProps;
                  focusNode = focusNode.memoizedState;
                  selection = JSCompiler_temp.stateNode;
                  try {
                    var resolvedPrevProps = resolveClassComponentProps(
                      JSCompiler_temp.type,
                      anchorOffset,
                      JSCompiler_temp.elementType === JSCompiler_temp.type
                    );
                    root2 = selection.getSnapshotBeforeUpdate(
                      resolvedPrevProps,
                      focusNode
                    );
                    selection.__reactInternalSnapshotBeforeUpdate = root2;
                  } catch (error2) {
                    captureCommitPhaseError(
                      JSCompiler_temp,
                      JSCompiler_temp.return,
                      error2
                    );
                  }
                }
                break;
              case 3:
                if (0 !== (root2 & 1024)) {
                  if (root2 = firstChild.stateNode.containerInfo, JSCompiler_temp = root2.nodeType, 9 === JSCompiler_temp)
                    clearContainerSparingly(root2);
                  else if (1 === JSCompiler_temp)
                    switch (root2.nodeName) {
                      case "HEAD":
                      case "HTML":
                      case "BODY":
                        clearContainerSparingly(root2);
                        break;
                      default:
                        root2.textContent = "";
                    }
                }
                break;
              case 5:
              case 26:
              case 27:
              case 6:
              case 4:
              case 17:
                break;
              default:
                if (0 !== (root2 & 1024)) throw Error(formatProdErrorMessage(163));
            }
            root2 = firstChild.sibling;
            if (null !== root2) {
              root2.return = firstChild.return;
              nextEffect = root2;
              break;
            }
            nextEffect = firstChild.return;
          }
      resolvedPrevProps = shouldFireAfterActiveInstanceBlur;
      shouldFireAfterActiveInstanceBlur = false;
      return resolvedPrevProps;
    }
    function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) {
      var flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitHookEffectListMount(5, finishedWork);
          break;
        case 1:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (flags & 4)
            if (finishedRoot = finishedWork.stateNode, null === current)
              try {
                finishedRoot.componentDidMount();
              } catch (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
            else {
              var prevProps = resolveClassComponentProps(
                finishedWork.type,
                current.memoizedProps
              );
              current = current.memoizedState;
              try {
                finishedRoot.componentDidUpdate(
                  prevProps,
                  current,
                  finishedRoot.__reactInternalSnapshotBeforeUpdate
                );
              } catch (error$111) {
                captureCommitPhaseError(
                  finishedWork,
                  finishedWork.return,
                  error$111
                );
              }
            }
          flags & 64 && commitClassCallbacks(finishedWork);
          flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 3:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (flags & 64 && (flags = finishedWork.updateQueue, null !== flags)) {
            finishedRoot = null;
            if (null !== finishedWork.child)
              switch (finishedWork.child.tag) {
                case 27:
                case 5:
                  finishedRoot = finishedWork.child.stateNode;
                  break;
                case 1:
                  finishedRoot = finishedWork.child.stateNode;
              }
            try {
              commitCallbacks(flags, finishedRoot);
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
          break;
        case 26:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 27:
        case 5:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          null === current && flags & 4 && commitHostMount(finishedWork);
          flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 12:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          break;
        case 13:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 22:
          prevProps = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
          if (!prevProps) {
            current = null !== current && null !== current.memoizedState || offscreenSubtreeWasHidden;
            var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = prevProps;
            (offscreenSubtreeWasHidden = current) && !prevOffscreenSubtreeWasHidden ? recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              0 !== (finishedWork.subtreeFlags & 8772)
            ) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          }
          flags & 512 && ("manual" === finishedWork.memoizedProps.mode ? safelyAttachRef(finishedWork, finishedWork.return) : safelyDetachRef(finishedWork, finishedWork.return));
          break;
        default:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      }
    }
    function detachFiberAfterEffects(fiber) {
      var alternate = fiber.alternate;
      null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
      fiber.child = null;
      fiber.deletions = null;
      fiber.sibling = null;
      5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
      fiber.stateNode = null;
      fiber.return = null;
      fiber.dependencies = null;
      fiber.memoizedProps = null;
      fiber.memoizedState = null;
      fiber.pendingProps = null;
      fiber.stateNode = null;
      fiber.updateQueue = null;
    }
    var hostParent = null, hostParentIsContainer = false;
    function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
      for (parent = parent.child; null !== parent; )
        commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), parent = parent.sibling;
    }
    function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
      if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
        try {
          injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
        } catch (err2) {
        }
      switch (deletedFiber.tag) {
        case 26:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          deletedFiber.memoizedState ? deletedFiber.memoizedState.count-- : deletedFiber.stateNode && (deletedFiber = deletedFiber.stateNode, deletedFiber.parentNode.removeChild(deletedFiber));
          break;
        case 27:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
          hostParent = deletedFiber.stateNode;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          deletedFiber = deletedFiber.stateNode;
          for (nearestMountedAncestor = deletedFiber.attributes; nearestMountedAncestor.length; )
            deletedFiber.removeAttributeNode(nearestMountedAncestor[0]);
          detachDeletedInstance(deletedFiber);
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          break;
        case 5:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
        case 6:
          prevHostParentIsContainer = hostParent;
          var prevHostParentIsContainer$119 = hostParentIsContainer;
          hostParent = null;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          hostParent = prevHostParentIsContainer;
          hostParentIsContainer = prevHostParentIsContainer$119;
          if (null !== hostParent)
            if (hostParentIsContainer)
              try {
                finishedRoot = hostParent, prevHostParent = deletedFiber.stateNode, 8 === finishedRoot.nodeType ? finishedRoot.parentNode.removeChild(prevHostParent) : finishedRoot.removeChild(prevHostParent);
              } catch (error2) {
                captureCommitPhaseError(
                  deletedFiber,
                  nearestMountedAncestor,
                  error2
                );
              }
            else
              try {
                hostParent.removeChild(deletedFiber.stateNode);
              } catch (error2) {
                captureCommitPhaseError(
                  deletedFiber,
                  nearestMountedAncestor,
                  error2
                );
              }
          break;
        case 18:
          null !== hostParent && (hostParentIsContainer ? (nearestMountedAncestor = hostParent, deletedFiber = deletedFiber.stateNode, 8 === nearestMountedAncestor.nodeType ? clearSuspenseBoundary(
            nearestMountedAncestor.parentNode,
            deletedFiber
          ) : 1 === nearestMountedAncestor.nodeType && clearSuspenseBoundary(nearestMountedAncestor, deletedFiber), retryIfBlockedOn(nearestMountedAncestor)) : clearSuspenseBoundary(hostParent, deletedFiber.stateNode));
          break;
        case 4:
          prevHostParent = hostParent;
          prevHostParentIsContainer = hostParentIsContainer;
          hostParent = deletedFiber.stateNode.containerInfo;
          hostParentIsContainer = true;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          break;
        case 0:
        case 11:
        case 14:
        case 15:
          offscreenSubtreeWasHidden || commitHookEffectListUnmount(2, deletedFiber, nearestMountedAncestor);
          offscreenSubtreeWasHidden || commitHookEffectListUnmount(4, deletedFiber, nearestMountedAncestor);
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 1:
          offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
            deletedFiber,
            nearestMountedAncestor,
            prevHostParent
          ));
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 21:
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 22:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          offscreenSubtreeWasHidden = prevHostParent;
          break;
        default:
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
      }
    }
    function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
      if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
        try {
          retryIfBlockedOn(finishedRoot);
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
    }
    function getRetryCache(finishedWork) {
      switch (finishedWork.tag) {
        case 13:
        case 19:
          var retryCache = finishedWork.stateNode;
          null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
          return retryCache;
        case 22:
          return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
        default:
          throw Error(formatProdErrorMessage(435, finishedWork.tag));
      }
    }
    function attachSuspenseRetryListeners(finishedWork, wakeables) {
      var retryCache = getRetryCache(finishedWork);
      wakeables.forEach(function(wakeable) {
        var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
        retryCache.has(wakeable) || (retryCache.add(wakeable), wakeable.then(retry, retry));
      });
    }
    function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
      var deletions = parentFiber.deletions;
      if (null !== deletions)
        for (var i2 = 0; i2 < deletions.length; i2++) {
          var childToDelete = deletions[i2], root2 = root$jscomp$0, returnFiber = parentFiber, parent = returnFiber;
          a: for (; null !== parent; ) {
            switch (parent.tag) {
              case 27:
              case 5:
                hostParent = parent.stateNode;
                hostParentIsContainer = false;
                break a;
              case 3:
                hostParent = parent.stateNode.containerInfo;
                hostParentIsContainer = true;
                break a;
              case 4:
                hostParent = parent.stateNode.containerInfo;
                hostParentIsContainer = true;
                break a;
            }
            parent = parent.return;
          }
          if (null === hostParent) throw Error(formatProdErrorMessage(160));
          commitDeletionEffectsOnFiber(root2, returnFiber, childToDelete);
          hostParent = null;
          hostParentIsContainer = false;
          root2 = childToDelete.alternate;
          null !== root2 && (root2.return = null);
          childToDelete.return = null;
        }
      if (parentFiber.subtreeFlags & 13878)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
    }
    var currentHoistableRoot = null;
    function commitMutationEffectsOnFiber(finishedWork, root2) {
      var current = finishedWork.alternate, flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (commitHookEffectListUnmount(3, finishedWork, finishedWork.return), commitHookEffectListMount(3, finishedWork), commitHookEffectListUnmount(5, finishedWork, finishedWork.return));
          break;
        case 1:
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
          flags & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, null !== finishedWork && (flags = finishedWork.callbacks, null !== flags && (current = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = null === current ? flags : current.concat(flags))));
          break;
        case 26:
          var hoistableRoot = currentHoistableRoot;
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
          if (flags & 4) {
            var currentResource = null !== current ? current.memoizedState : null;
            flags = finishedWork.memoizedState;
            if (null === current)
              if (null === flags)
                if (null === finishedWork.stateNode) {
                  a: {
                    flags = finishedWork.type;
                    current = finishedWork.memoizedProps;
                    hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
                    b: switch (flags) {
                      case "title":
                        currentResource = hoistableRoot.getElementsByTagName("title")[0];
                        if (!currentResource || currentResource[internalHoistableMarker] || currentResource[internalInstanceKey] || "http://www.w3.org/2000/svg" === currentResource.namespaceURI || currentResource.hasAttribute("itemprop"))
                          currentResource = hoistableRoot.createElement(flags), hoistableRoot.head.insertBefore(
                            currentResource,
                            hoistableRoot.querySelector("head > title")
                          );
                        setInitialProperties(currentResource, flags, current);
                        currentResource[internalInstanceKey] = finishedWork;
                        markNodeAsHoistable(currentResource);
                        flags = currentResource;
                        break a;
                      case "link":
                        var maybeNodes = getHydratableHoistableCache(
                          "link",
                          "href",
                          hoistableRoot
                        ).get(flags + (current.href || ""));
                        if (maybeNodes) {
                          for (var i2 = 0; i2 < maybeNodes.length; i2++)
                            if (currentResource = maybeNodes[i2], currentResource.getAttribute("href") === (null == current.href ? null : current.href) && currentResource.getAttribute("rel") === (null == current.rel ? null : current.rel) && currentResource.getAttribute("title") === (null == current.title ? null : current.title) && currentResource.getAttribute("crossorigin") === (null == current.crossOrigin ? null : current.crossOrigin)) {
                              maybeNodes.splice(i2, 1);
                              break b;
                            }
                        }
                        currentResource = hoistableRoot.createElement(flags);
                        setInitialProperties(currentResource, flags, current);
                        hoistableRoot.head.appendChild(currentResource);
                        break;
                      case "meta":
                        if (maybeNodes = getHydratableHoistableCache(
                          "meta",
                          "content",
                          hoistableRoot
                        ).get(flags + (current.content || ""))) {
                          for (i2 = 0; i2 < maybeNodes.length; i2++)
                            if (currentResource = maybeNodes[i2], currentResource.getAttribute("content") === (null == current.content ? null : "" + current.content) && currentResource.getAttribute("name") === (null == current.name ? null : current.name) && currentResource.getAttribute("property") === (null == current.property ? null : current.property) && currentResource.getAttribute("http-equiv") === (null == current.httpEquiv ? null : current.httpEquiv) && currentResource.getAttribute("charset") === (null == current.charSet ? null : current.charSet)) {
                              maybeNodes.splice(i2, 1);
                              break b;
                            }
                        }
                        currentResource = hoistableRoot.createElement(flags);
                        setInitialProperties(currentResource, flags, current);
                        hoistableRoot.head.appendChild(currentResource);
                        break;
                      default:
                        throw Error(formatProdErrorMessage(468, flags));
                    }
                    currentResource[internalInstanceKey] = finishedWork;
                    markNodeAsHoistable(currentResource);
                    flags = currentResource;
                  }
                  finishedWork.stateNode = flags;
                } else
                  mountHoistable(
                    hoistableRoot,
                    finishedWork.type,
                    finishedWork.stateNode
                  );
              else
                finishedWork.stateNode = acquireResource(
                  hoistableRoot,
                  flags,
                  finishedWork.memoizedProps
                );
            else
              currentResource !== flags ? (null === currentResource ? null !== current.stateNode && (current = current.stateNode, current.parentNode.removeChild(current)) : currentResource.count--, null === flags ? mountHoistable(
                hoistableRoot,
                finishedWork.type,
                finishedWork.stateNode
              ) : acquireResource(
                hoistableRoot,
                flags,
                finishedWork.memoizedProps
              )) : null === flags && null !== finishedWork.stateNode && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current.memoizedProps
              );
          }
          break;
        case 27:
          if (flags & 4 && null === finishedWork.alternate) {
            hoistableRoot = finishedWork.stateNode;
            currentResource = finishedWork.memoizedProps;
            try {
              for (var node2 = hoistableRoot.firstChild; node2; ) {
                var nextNode = node2.nextSibling, nodeName = node2.nodeName;
                node2[internalHoistableMarker] || "HEAD" === nodeName || "BODY" === nodeName || "SCRIPT" === nodeName || "STYLE" === nodeName || "LINK" === nodeName && "stylesheet" === node2.rel.toLowerCase() || hoistableRoot.removeChild(node2);
                node2 = nextNode;
              }
              for (var type = finishedWork.type, attributes = hoistableRoot.attributes; attributes.length; )
                hoistableRoot.removeAttributeNode(attributes[0]);
              setInitialProperties(hoistableRoot, type, currentResource);
              hoistableRoot[internalInstanceKey] = finishedWork;
              hoistableRoot[internalPropsKey] = currentResource;
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
        case 5:
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
          if (finishedWork.flags & 32) {
            hoistableRoot = finishedWork.stateNode;
            try {
              setTextContent(hoistableRoot, "");
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
          flags & 4 && null != finishedWork.stateNode && (hoistableRoot = finishedWork.memoizedProps, commitHostUpdate(
            finishedWork,
            hoistableRoot,
            null !== current ? current.memoizedProps : hoistableRoot
          ));
          flags & 1024 && (needsFormReset = true);
          break;
        case 6:
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          if (flags & 4) {
            if (null === finishedWork.stateNode)
              throw Error(formatProdErrorMessage(162));
            flags = finishedWork.memoizedProps;
            current = finishedWork.stateNode;
            try {
              current.nodeValue = flags;
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
          break;
        case 3:
          tagCaches = null;
          hoistableRoot = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(root2.containerInfo);
          recursivelyTraverseMutationEffects(root2, finishedWork);
          currentHoistableRoot = hoistableRoot;
          commitReconciliationEffects(finishedWork);
          if (flags & 4 && null !== current && current.memoizedState.isDehydrated)
            try {
              retryIfBlockedOn(root2.containerInfo);
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
          break;
        case 4:
          flags = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(
            finishedWork.stateNode.containerInfo
          );
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          currentHoistableRoot = flags;
          break;
        case 12:
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          break;
        case 13:
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current && null !== current.memoizedState) && (globalMostRecentFallbackTime = now());
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 22:
          flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
          node2 = null !== finishedWork.memoizedState;
          nextNode = null !== current && null !== current.memoizedState;
          nodeName = offscreenSubtreeIsHidden;
          type = offscreenSubtreeWasHidden;
          offscreenSubtreeIsHidden = nodeName || node2;
          offscreenSubtreeWasHidden = type || nextNode;
          recursivelyTraverseMutationEffects(root2, finishedWork);
          offscreenSubtreeWasHidden = type;
          offscreenSubtreeIsHidden = nodeName;
          commitReconciliationEffects(finishedWork);
          root2 = finishedWork.stateNode;
          root2._current = finishedWork;
          root2._visibility &= -3;
          root2._visibility |= root2._pendingVisibility & 2;
          if (flags & 8192 && (root2._visibility = node2 ? root2._visibility & -2 : root2._visibility | 1, node2 && (root2 = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden, null === current || nextNode || root2 || recursivelyTraverseDisappearLayoutEffects(finishedWork)), null === finishedWork.memoizedProps || "manual" !== finishedWork.memoizedProps.mode))
            a: for (current = null, root2 = finishedWork; ; ) {
              if (5 === root2.tag || 26 === root2.tag || 27 === root2.tag) {
                if (null === current) {
                  nextNode = current = root2;
                  try {
                    if (hoistableRoot = nextNode.stateNode, node2)
                      currentResource = hoistableRoot.style, "function" === typeof currentResource.setProperty ? currentResource.setProperty(
                        "display",
                        "none",
                        "important"
                      ) : currentResource.display = "none";
                    else {
                      maybeNodes = nextNode.stateNode;
                      i2 = nextNode.memoizedProps.style;
                      var display = void 0 !== i2 && null !== i2 && i2.hasOwnProperty("display") ? i2.display : null;
                      maybeNodes.style.display = null == display || "boolean" === typeof display ? "" : ("" + display).trim();
                    }
                  } catch (error2) {
                    captureCommitPhaseError(nextNode, nextNode.return, error2);
                  }
                }
              } else if (6 === root2.tag) {
                if (null === current) {
                  nextNode = root2;
                  try {
                    nextNode.stateNode.nodeValue = node2 ? "" : nextNode.memoizedProps;
                  } catch (error2) {
                    captureCommitPhaseError(nextNode, nextNode.return, error2);
                  }
                }
              } else if ((22 !== root2.tag && 23 !== root2.tag || null === root2.memoizedState || root2 === finishedWork) && null !== root2.child) {
                root2.child.return = root2;
                root2 = root2.child;
                continue;
              }
              if (root2 === finishedWork) break a;
              for (; null === root2.sibling; ) {
                if (null === root2.return || root2.return === finishedWork) break a;
                current === root2 && (current = null);
                root2 = root2.return;
              }
              current === root2 && (current = null);
              root2.sibling.return = root2.return;
              root2 = root2.sibling;
            }
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current = flags.retryQueue, null !== current && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current))));
          break;
        case 19:
          recursivelyTraverseMutationEffects(root2, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 21:
          break;
        default:
          recursivelyTraverseMutationEffects(root2, finishedWork), commitReconciliationEffects(finishedWork);
      }
    }
    function commitReconciliationEffects(finishedWork) {
      var flags = finishedWork.flags;
      if (flags & 2) {
        try {
          if (27 !== finishedWork.tag) {
            a: {
              for (var parent = finishedWork.return; null !== parent; ) {
                if (isHostParent(parent)) {
                  var JSCompiler_inline_result = parent;
                  break a;
                }
                parent = parent.return;
              }
              throw Error(formatProdErrorMessage(160));
            }
            switch (JSCompiler_inline_result.tag) {
              case 27:
                var parent$jscomp$0 = JSCompiler_inline_result.stateNode, before = getHostSibling(finishedWork);
                insertOrAppendPlacementNode(finishedWork, before, parent$jscomp$0);
                break;
              case 5:
                var parent$113 = JSCompiler_inline_result.stateNode;
                JSCompiler_inline_result.flags & 32 && (setTextContent(parent$113, ""), JSCompiler_inline_result.flags &= -33);
                var before$114 = getHostSibling(finishedWork);
                insertOrAppendPlacementNode(finishedWork, before$114, parent$113);
                break;
              case 3:
              case 4:
                var parent$115 = JSCompiler_inline_result.stateNode.containerInfo, before$116 = getHostSibling(finishedWork);
                insertOrAppendPlacementNodeIntoContainer(
                  finishedWork,
                  before$116,
                  parent$115
                );
                break;
              default:
                throw Error(formatProdErrorMessage(161));
            }
          }
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
        finishedWork.flags &= -3;
      }
      flags & 4096 && (finishedWork.flags &= -4097);
    }
    function recursivelyResetForms(parentFiber) {
      if (parentFiber.subtreeFlags & 1024)
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var fiber = parentFiber;
          recursivelyResetForms(fiber);
          5 === fiber.tag && fiber.flags & 1024 && fiber.stateNode.reset();
          parentFiber = parentFiber.sibling;
        }
    }
    function recursivelyTraverseLayoutEffects(root2, parentFiber) {
      if (parentFiber.subtreeFlags & 8772)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitLayoutEffectOnFiber(root2, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
    }
    function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        var finishedWork = parentFiber;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            commitHookEffectListUnmount(4, finishedWork, finishedWork.return);
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 1:
            safelyDetachRef(finishedWork, finishedWork.return);
            var instance = finishedWork.stateNode;
            "function" === typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(
              finishedWork,
              finishedWork.return,
              instance
            );
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 26:
          case 27:
          case 5:
            safelyDetachRef(finishedWork, finishedWork.return);
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 22:
            safelyDetachRef(finishedWork, finishedWork.return);
            null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          default:
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
        }
        parentFiber = parentFiber.sibling;
      }
    }
    function recursivelyTraverseReappearLayoutEffects(finishedRoot$jscomp$0, parentFiber, includeWorkInProgressEffects) {
      includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        var current = parentFiber.alternate, finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            commitHookEffectListMount(4, finishedWork);
            break;
          case 1:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            current = finishedWork;
            finishedRoot = current.stateNode;
            if ("function" === typeof finishedRoot.componentDidMount)
              try {
                finishedRoot.componentDidMount();
              } catch (error2) {
                captureCommitPhaseError(current, current.return, error2);
              }
            current = finishedWork;
            finishedRoot = current.updateQueue;
            if (null !== finishedRoot) {
              var instance = current.stateNode;
              try {
                var hiddenCallbacks = finishedRoot.shared.hiddenCallbacks;
                if (null !== hiddenCallbacks)
                  for (finishedRoot.shared.hiddenCallbacks = null, finishedRoot = 0; finishedRoot < hiddenCallbacks.length; finishedRoot++)
                    callCallback(hiddenCallbacks[finishedRoot], instance);
              } catch (error2) {
                captureCommitPhaseError(current, current.return, error2);
              }
            }
            includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 26:
          case 27:
          case 5:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && null === current && flags & 4 && commitHostMount(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            break;
          case 13:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            break;
          case 22:
            null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          default:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
        }
        parentFiber = parentFiber.sibling;
      }
    }
    function commitOffscreenPassiveMountEffects(current, finishedWork) {
      var previousCache = null;
      null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (previousCache = current.memoizedState.cachePool.pool);
      current = null;
      null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current = finishedWork.memoizedState.cachePool.pool);
      current !== previousCache && (null != current && current.refCount++, null != previousCache && releaseCache(previousCache));
    }
    function commitCachePassiveMountEffect(current, finishedWork) {
      current = null;
      null !== finishedWork.alternate && (current = finishedWork.alternate.memoizedState.cache);
      finishedWork = finishedWork.memoizedState.cache;
      finishedWork !== current && (finishedWork.refCount++, null != current && releaseCache(current));
    }
    function recursivelyTraversePassiveMountEffects(root2, parentFiber, committedLanes, committedTransitions) {
      if (parentFiber.subtreeFlags & 10256)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitPassiveMountOnFiber(
            root2,
            parentFiber,
            committedLanes,
            committedTransitions
          ), parentFiber = parentFiber.sibling;
    }
    function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
      var flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          );
          flags & 2048 && commitHookEffectListMount(9, finishedWork);
          break;
        case 3:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          );
          flags & 2048 && (finishedRoot = null, null !== finishedWork.alternate && (finishedRoot = finishedWork.alternate.memoizedState.cache), finishedWork = finishedWork.memoizedState.cache, finishedWork !== finishedRoot && (finishedWork.refCount++, null != finishedRoot && releaseCache(finishedRoot)));
          break;
        case 12:
          if (flags & 2048) {
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            finishedRoot = finishedWork.stateNode;
            try {
              var _finishedWork$memoize2 = finishedWork.memoizedProps, id = _finishedWork$memoize2.id, onPostCommit = _finishedWork$memoize2.onPostCommit;
              "function" === typeof onPostCommit && onPostCommit(
                id,
                null === finishedWork.alternate ? "mount" : "update",
                finishedRoot.passiveEffectDuration,
                -0
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          } else
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
          break;
        case 23:
          break;
        case 22:
          _finishedWork$memoize2 = finishedWork.stateNode;
          null !== finishedWork.memoizedState ? _finishedWork$memoize2._visibility & 4 ? recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          ) : recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork) : _finishedWork$memoize2._visibility & 4 ? recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          ) : (_finishedWork$memoize2._visibility |= 4, recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            0 !== (finishedWork.subtreeFlags & 10256)
          ));
          flags & 2048 && commitOffscreenPassiveMountEffects(
            finishedWork.alternate,
            finishedWork
          );
          break;
        case 24:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          );
          flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
          break;
        default:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          );
      }
    }
    function recursivelyTraverseReconnectPassiveEffects(finishedRoot$jscomp$0, parentFiber, committedLanes$jscomp$0, committedTransitions$jscomp$0, includeWorkInProgressEffects) {
      includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 10256);
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, committedLanes = committedLanes$jscomp$0, committedTransitions = committedTransitions$jscomp$0, flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            );
            commitHookEffectListMount(8, finishedWork);
            break;
          case 23:
            break;
          case 22:
            var instance = finishedWork.stateNode;
            null !== finishedWork.memoizedState ? instance._visibility & 4 ? recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            ) : recursivelyTraverseAtomicPassiveEffects(
              finishedRoot,
              finishedWork
            ) : (instance._visibility |= 4, recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            ));
            includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
              finishedWork.alternate,
              finishedWork
            );
            break;
          case 24:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
            break;
          default:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            );
        }
        parentFiber = parentFiber.sibling;
      }
    }
    function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber) {
      if (parentFiber.subtreeFlags & 10256)
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
          switch (finishedWork.tag) {
            case 22:
              recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
              flags & 2048 && commitOffscreenPassiveMountEffects(
                finishedWork.alternate,
                finishedWork
              );
              break;
            case 24:
              recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
              flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
              break;
            default:
              recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
          }
          parentFiber = parentFiber.sibling;
        }
    }
    var suspenseyCommitFlag = 8192;
    function recursivelyAccumulateSuspenseyCommit(parentFiber) {
      if (parentFiber.subtreeFlags & suspenseyCommitFlag)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          accumulateSuspenseyCommitOnFiber(parentFiber), parentFiber = parentFiber.sibling;
    }
    function accumulateSuspenseyCommitOnFiber(fiber) {
      switch (fiber.tag) {
        case 26:
          recursivelyAccumulateSuspenseyCommit(fiber);
          fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState && suspendResource(
            currentHoistableRoot,
            fiber.memoizedState,
            fiber.memoizedProps
          );
          break;
        case 5:
          recursivelyAccumulateSuspenseyCommit(fiber);
          break;
        case 3:
        case 4:
          var previousHoistableRoot = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(fiber.stateNode.containerInfo);
          recursivelyAccumulateSuspenseyCommit(fiber);
          currentHoistableRoot = previousHoistableRoot;
          break;
        case 22:
          null === fiber.memoizedState && (previousHoistableRoot = fiber.alternate, null !== previousHoistableRoot && null !== previousHoistableRoot.memoizedState ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(fiber), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(fiber));
          break;
        default:
          recursivelyAccumulateSuspenseyCommit(fiber);
      }
    }
    function detachAlternateSiblings(parentFiber) {
      var previousFiber = parentFiber.alternate;
      if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
        previousFiber.child = null;
        do
          previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
        while (null !== parentFiber);
      }
    }
    function recursivelyTraversePassiveUnmountEffects(parentFiber) {
      var deletions = parentFiber.deletions;
      if (0 !== (parentFiber.flags & 16)) {
        if (null !== deletions)
          for (var i2 = 0; i2 < deletions.length; i2++) {
            var childToDelete = deletions[i2];
            nextEffect = childToDelete;
            commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
              childToDelete,
              parentFiber
            );
          }
        detachAlternateSiblings(parentFiber);
      }
      if (parentFiber.subtreeFlags & 10256)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
    }
    function commitPassiveUnmountOnFiber(finishedWork) {
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          finishedWork.flags & 2048 && commitHookEffectListUnmount(9, finishedWork, finishedWork.return);
          break;
        case 3:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          break;
        case 12:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          break;
        case 22:
          var instance = finishedWork.stateNode;
          null !== finishedWork.memoizedState && instance._visibility & 4 && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (instance._visibility &= -5, recursivelyTraverseDisconnectPassiveEffects(finishedWork)) : recursivelyTraversePassiveUnmountEffects(finishedWork);
          break;
        default:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
      }
    }
    function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
      var deletions = parentFiber.deletions;
      if (0 !== (parentFiber.flags & 16)) {
        if (null !== deletions)
          for (var i2 = 0; i2 < deletions.length; i2++) {
            var childToDelete = deletions[i2];
            nextEffect = childToDelete;
            commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
              childToDelete,
              parentFiber
            );
          }
        detachAlternateSiblings(parentFiber);
      }
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        deletions = parentFiber;
        switch (deletions.tag) {
          case 0:
          case 11:
          case 15:
            commitHookEffectListUnmount(8, deletions, deletions.return);
            recursivelyTraverseDisconnectPassiveEffects(deletions);
            break;
          case 22:
            i2 = deletions.stateNode;
            i2._visibility & 4 && (i2._visibility &= -5, recursivelyTraverseDisconnectPassiveEffects(deletions));
            break;
          default:
            recursivelyTraverseDisconnectPassiveEffects(deletions);
        }
        parentFiber = parentFiber.sibling;
      }
    }
    function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
      for (; null !== nextEffect; ) {
        var fiber = nextEffect;
        switch (fiber.tag) {
          case 0:
          case 11:
          case 15:
            commitHookEffectListUnmount(8, fiber, nearestMountedAncestor);
            break;
          case 23:
          case 22:
            if (null !== fiber.memoizedState && null !== fiber.memoizedState.cachePool) {
              var cache = fiber.memoizedState.cachePool.pool;
              null != cache && cache.refCount++;
            }
            break;
          case 24:
            releaseCache(fiber.memoizedState.cache);
        }
        cache = fiber.child;
        if (null !== cache) cache.return = fiber, nextEffect = cache;
        else
          a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
            cache = nextEffect;
            var sibling = cache.sibling, returnFiber = cache.return;
            detachFiberAfterEffects(cache);
            if (cache === fiber) {
              nextEffect = null;
              break a;
            }
            if (null !== sibling) {
              sibling.return = returnFiber;
              nextEffect = sibling;
              break a;
            }
            nextEffect = returnFiber;
          }
      }
    }
    function FiberNode(tag, pendingProps, key2, mode) {
      this.tag = tag;
      this.key = key2;
      this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
      this.index = 0;
      this.refCleanup = this.ref = null;
      this.pendingProps = pendingProps;
      this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
      this.mode = mode;
      this.subtreeFlags = this.flags = 0;
      this.deletions = null;
      this.childLanes = this.lanes = 0;
      this.alternate = null;
    }
    function createFiberImplClass(tag, pendingProps, key2, mode) {
      return new FiberNode(tag, pendingProps, key2, mode);
    }
    function shouldConstruct(Component2) {
      Component2 = Component2.prototype;
      return !(!Component2 || !Component2.isReactComponent);
    }
    function createWorkInProgress(current, pendingProps) {
      var workInProgress2 = current.alternate;
      null === workInProgress2 ? (workInProgress2 = createFiberImplClass(
        current.tag,
        pendingProps,
        current.key,
        current.mode
      ), workInProgress2.elementType = current.elementType, workInProgress2.type = current.type, workInProgress2.stateNode = current.stateNode, workInProgress2.alternate = current, current.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null);
      workInProgress2.flags = current.flags & 31457280;
      workInProgress2.childLanes = current.childLanes;
      workInProgress2.lanes = current.lanes;
      workInProgress2.child = current.child;
      workInProgress2.memoizedProps = current.memoizedProps;
      workInProgress2.memoizedState = current.memoizedState;
      workInProgress2.updateQueue = current.updateQueue;
      pendingProps = current.dependencies;
      workInProgress2.dependencies = null === pendingProps ? null : { lanes: pendingProps.lanes, firstContext: pendingProps.firstContext };
      workInProgress2.sibling = current.sibling;
      workInProgress2.index = current.index;
      workInProgress2.ref = current.ref;
      workInProgress2.refCleanup = current.refCleanup;
      return workInProgress2;
    }
    function resetWorkInProgress(workInProgress2, renderLanes2) {
      workInProgress2.flags &= 31457282;
      var current = workInProgress2.alternate;
      null === current ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null) : (workInProgress2.childLanes = current.childLanes, workInProgress2.lanes = current.lanes, workInProgress2.child = current.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current.memoizedProps, workInProgress2.memoizedState = current.memoizedState, workInProgress2.updateQueue = current.updateQueue, workInProgress2.type = current.type, renderLanes2 = current.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
        lanes: renderLanes2.lanes,
        firstContext: renderLanes2.firstContext
      });
      return workInProgress2;
    }
    function createFiberFromTypeAndProps(type, key2, pendingProps, owner, mode, lanes) {
      var fiberTag = 0;
      owner = type;
      if ("function" === typeof type) shouldConstruct(type) && (fiberTag = 1);
      else if ("string" === typeof type)
        fiberTag = isHostHoistableType(
          type,
          pendingProps,
          contextStackCursor.current
        ) ? 26 : "html" === type || "head" === type || "body" === type ? 27 : 5;
      else
        a: switch (type) {
          case REACT_FRAGMENT_TYPE:
            return createFiberFromFragment(pendingProps.children, mode, lanes, key2);
          case REACT_STRICT_MODE_TYPE:
            fiberTag = 8;
            mode |= 24;
            break;
          case REACT_PROFILER_TYPE:
            return type = createFiberImplClass(12, pendingProps, key2, mode | 2), type.elementType = REACT_PROFILER_TYPE, type.lanes = lanes, type;
          case REACT_SUSPENSE_TYPE:
            return type = createFiberImplClass(13, pendingProps, key2, mode), type.elementType = REACT_SUSPENSE_TYPE, type.lanes = lanes, type;
          case REACT_SUSPENSE_LIST_TYPE:
            return type = createFiberImplClass(19, pendingProps, key2, mode), type.elementType = REACT_SUSPENSE_LIST_TYPE, type.lanes = lanes, type;
          case REACT_OFFSCREEN_TYPE:
            return createFiberFromOffscreen(pendingProps, mode, lanes, key2);
          default:
            if ("object" === typeof type && null !== type)
              switch (type.$$typeof) {
                case REACT_PROVIDER_TYPE:
                case REACT_CONTEXT_TYPE:
                  fiberTag = 10;
                  break a;
                case REACT_CONSUMER_TYPE:
                  fiberTag = 9;
                  break a;
                case REACT_FORWARD_REF_TYPE:
                  fiberTag = 11;
                  break a;
                case REACT_MEMO_TYPE:
                  fiberTag = 14;
                  break a;
                case REACT_LAZY_TYPE:
                  fiberTag = 16;
                  owner = null;
                  break a;
              }
            fiberTag = 29;
            pendingProps = Error(
              formatProdErrorMessage(130, null === type ? "null" : typeof type, "")
            );
            owner = null;
        }
      key2 = createFiberImplClass(fiberTag, pendingProps, key2, mode);
      key2.elementType = type;
      key2.type = owner;
      key2.lanes = lanes;
      return key2;
    }
    function createFiberFromFragment(elements, mode, lanes, key2) {
      elements = createFiberImplClass(7, elements, key2, mode);
      elements.lanes = lanes;
      return elements;
    }
    function createFiberFromOffscreen(pendingProps, mode, lanes, key2) {
      pendingProps = createFiberImplClass(22, pendingProps, key2, mode);
      pendingProps.elementType = REACT_OFFSCREEN_TYPE;
      pendingProps.lanes = lanes;
      var primaryChildInstance = {
        _visibility: 1,
        _pendingVisibility: 1,
        _pendingMarkers: null,
        _retryCache: null,
        _transitions: null,
        _current: null,
        detach: function() {
          var fiber = primaryChildInstance._current;
          if (null === fiber) throw Error(formatProdErrorMessage(456));
          if (0 === (primaryChildInstance._pendingVisibility & 2)) {
            var root2 = enqueueConcurrentRenderForLane(fiber, 2);
            null !== root2 && (primaryChildInstance._pendingVisibility |= 2, scheduleUpdateOnFiber(root2, fiber, 2));
          }
        },
        attach: function() {
          var fiber = primaryChildInstance._current;
          if (null === fiber) throw Error(formatProdErrorMessage(456));
          if (0 !== (primaryChildInstance._pendingVisibility & 2)) {
            var root2 = enqueueConcurrentRenderForLane(fiber, 2);
            null !== root2 && (primaryChildInstance._pendingVisibility &= -3, scheduleUpdateOnFiber(root2, fiber, 2));
          }
        }
      };
      pendingProps.stateNode = primaryChildInstance;
      return pendingProps;
    }
    function createFiberFromText(content2, mode, lanes) {
      content2 = createFiberImplClass(6, content2, null, mode);
      content2.lanes = lanes;
      return content2;
    }
    function createFiberFromPortal(portal, mode, lanes) {
      mode = createFiberImplClass(
        4,
        null !== portal.children ? portal.children : [],
        portal.key,
        mode
      );
      mode.lanes = lanes;
      mode.stateNode = {
        containerInfo: portal.containerInfo,
        pendingChildren: null,
        implementation: portal.implementation
      };
      return mode;
    }
    function markUpdate(workInProgress2) {
      workInProgress2.flags |= 4;
    }
    function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
      if ("stylesheet" !== resource.type || 0 !== (resource.state.loading & 4))
        workInProgress2.flags &= -16777217;
      else if (workInProgress2.flags |= 16777216, !preloadResource(resource)) {
        resource = suspenseHandlerStackCursor.current;
        if (null !== resource && ((workInProgressRootRenderLanes & 4194176) === workInProgressRootRenderLanes ? null !== shellBoundary : (workInProgressRootRenderLanes & 62914560) !== workInProgressRootRenderLanes && 0 === (workInProgressRootRenderLanes & 536870912) || resource !== shellBoundary))
          throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
        workInProgress2.flags |= 8192;
      }
    }
    function scheduleRetryEffect(workInProgress2, retryQueue) {
      null !== retryQueue && (workInProgress2.flags |= 4);
      workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
    }
    function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
      if (!isHydrating)
        switch (renderState.tailMode) {
          case "hidden":
            hasRenderedATailFallback = renderState.tail;
            for (var lastTailNode = null; null !== hasRenderedATailFallback; )
              null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
            null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
            break;
          case "collapsed":
            lastTailNode = renderState.tail;
            for (var lastTailNode$131 = null; null !== lastTailNode; )
              null !== lastTailNode.alternate && (lastTailNode$131 = lastTailNode), lastTailNode = lastTailNode.sibling;
            null === lastTailNode$131 ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : lastTailNode$131.sibling = null;
        }
    }
    function bubbleProperties(completedWork) {
      var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
      if (didBailout)
        for (var child$132 = completedWork.child; null !== child$132; )
          newChildLanes |= child$132.lanes | child$132.childLanes, subtreeFlags |= child$132.subtreeFlags & 31457280, subtreeFlags |= child$132.flags & 31457280, child$132.return = completedWork, child$132 = child$132.sibling;
      else
        for (child$132 = completedWork.child; null !== child$132; )
          newChildLanes |= child$132.lanes | child$132.childLanes, subtreeFlags |= child$132.subtreeFlags, subtreeFlags |= child$132.flags, child$132.return = completedWork, child$132 = child$132.sibling;
      completedWork.subtreeFlags |= subtreeFlags;
      completedWork.childLanes = newChildLanes;
      return didBailout;
    }
    function completeWork(current, workInProgress2, renderLanes2) {
      var newProps = workInProgress2.pendingProps;
      popTreeContext(workInProgress2);
      switch (workInProgress2.tag) {
        case 16:
        case 15:
        case 0:
        case 11:
        case 7:
        case 8:
        case 12:
        case 9:
        case 14:
          return bubbleProperties(workInProgress2), null;
        case 1:
          return bubbleProperties(workInProgress2), null;
        case 3:
          renderLanes2 = workInProgress2.stateNode;
          newProps = null;
          null !== current && (newProps = current.memoizedState.cache);
          workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
          popProvider(CacheContext);
          popHostContainer();
          renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
          if (null === current || null === current.child)
            popHydrationState(workInProgress2) ? markUpdate(workInProgress2) : null === current || current.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, null !== hydrationErrors && (queueRecoverableErrors(hydrationErrors), hydrationErrors = null));
          bubbleProperties(workInProgress2);
          return null;
        case 26:
          return renderLanes2 = workInProgress2.memoizedState, null === current ? (markUpdate(workInProgress2), null !== renderLanes2 ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(workInProgress2, renderLanes2)) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217)) : renderLanes2 ? renderLanes2 !== current.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(workInProgress2, renderLanes2)) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (current.memoizedProps !== newProps && markUpdate(workInProgress2), bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217), null;
        case 27:
          popHostContext(workInProgress2);
          renderLanes2 = rootInstanceStackCursor.current;
          var type = workInProgress2.type;
          if (null !== current && null != workInProgress2.stateNode)
            current.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if (!newProps) {
              if (null === workInProgress2.stateNode)
                throw Error(formatProdErrorMessage(166));
              bubbleProperties(workInProgress2);
              return null;
            }
            current = contextStackCursor.current;
            popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2) : (current = resolveSingletonInstance(type, newProps, renderLanes2), workInProgress2.stateNode = current, markUpdate(workInProgress2));
          }
          bubbleProperties(workInProgress2);
          return null;
        case 5:
          popHostContext(workInProgress2);
          renderLanes2 = workInProgress2.type;
          if (null !== current && null != workInProgress2.stateNode)
            current.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if (!newProps) {
              if (null === workInProgress2.stateNode)
                throw Error(formatProdErrorMessage(166));
              bubbleProperties(workInProgress2);
              return null;
            }
            current = contextStackCursor.current;
            if (popHydrationState(workInProgress2))
              prepareToHydrateHostInstance(workInProgress2);
            else {
              type = getOwnerDocumentFromRootContainer(
                rootInstanceStackCursor.current
              );
              switch (current) {
                case 1:
                  current = type.createElementNS(
                    "http://www.w3.org/2000/svg",
                    renderLanes2
                  );
                  break;
                case 2:
                  current = type.createElementNS(
                    "http://www.w3.org/1998/Math/MathML",
                    renderLanes2
                  );
                  break;
                default:
                  switch (renderLanes2) {
                    case "svg":
                      current = type.createElementNS(
                        "http://www.w3.org/2000/svg",
                        renderLanes2
                      );
                      break;
                    case "math":
                      current = type.createElementNS(
                        "http://www.w3.org/1998/Math/MathML",
                        renderLanes2
                      );
                      break;
                    case "script":
                      current = type.createElement("div");
                      current.innerHTML = "<script><\/script>";
                      current = current.removeChild(current.firstChild);
                      break;
                    case "select":
                      current = "string" === typeof newProps.is ? type.createElement("select", { is: newProps.is }) : type.createElement("select");
                      newProps.multiple ? current.multiple = true : newProps.size && (current.size = newProps.size);
                      break;
                    default:
                      current = "string" === typeof newProps.is ? type.createElement(renderLanes2, { is: newProps.is }) : type.createElement(renderLanes2);
                  }
              }
              current[internalInstanceKey] = workInProgress2;
              current[internalPropsKey] = newProps;
              a: for (type = workInProgress2.child; null !== type; ) {
                if (5 === type.tag || 6 === type.tag)
                  current.appendChild(type.stateNode);
                else if (4 !== type.tag && 27 !== type.tag && null !== type.child) {
                  type.child.return = type;
                  type = type.child;
                  continue;
                }
                if (type === workInProgress2) break a;
                for (; null === type.sibling; ) {
                  if (null === type.return || type.return === workInProgress2)
                    break a;
                  type = type.return;
                }
                type.sibling.return = type.return;
                type = type.sibling;
              }
              workInProgress2.stateNode = current;
              a: switch (setInitialProperties(current, renderLanes2, newProps), renderLanes2) {
                case "button":
                case "input":
                case "select":
                case "textarea":
                  current = !!newProps.autoFocus;
                  break a;
                case "img":
                  current = true;
                  break a;
                default:
                  current = false;
              }
              current && markUpdate(workInProgress2);
            }
          }
          bubbleProperties(workInProgress2);
          workInProgress2.flags &= -16777217;
          return null;
        case 6:
          if (current && null != workInProgress2.stateNode)
            current.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if ("string" !== typeof newProps && null === workInProgress2.stateNode)
              throw Error(formatProdErrorMessage(166));
            current = rootInstanceStackCursor.current;
            if (popHydrationState(workInProgress2)) {
              current = workInProgress2.stateNode;
              renderLanes2 = workInProgress2.memoizedProps;
              newProps = null;
              type = hydrationParentFiber;
              if (null !== type)
                switch (type.tag) {
                  case 27:
                  case 5:
                    newProps = type.memoizedProps;
                }
              current[internalInstanceKey] = workInProgress2;
              current = current.nodeValue === renderLanes2 || null !== newProps && true === newProps.suppressHydrationWarning || checkForUnmatchedText(current.nodeValue, renderLanes2) ? true : false;
              current || throwOnHydrationMismatch(workInProgress2);
            } else
              current = getOwnerDocumentFromRootContainer(current).createTextNode(
                newProps
              ), current[internalInstanceKey] = workInProgress2, workInProgress2.stateNode = current;
          }
          bubbleProperties(workInProgress2);
          return null;
        case 13:
          newProps = workInProgress2.memoizedState;
          if (null === current || null !== current.memoizedState && null !== current.memoizedState.dehydrated) {
            type = popHydrationState(workInProgress2);
            if (null !== newProps && null !== newProps.dehydrated) {
              if (null === current) {
                if (!type) throw Error(formatProdErrorMessage(318));
                type = workInProgress2.memoizedState;
                type = null !== type ? type.dehydrated : null;
                if (!type) throw Error(formatProdErrorMessage(317));
                type[internalInstanceKey] = workInProgress2;
              } else
                resetHydrationState(), 0 === (workInProgress2.flags & 128) && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4;
              bubbleProperties(workInProgress2);
              type = false;
            } else
              null !== hydrationErrors && (queueRecoverableErrors(hydrationErrors), hydrationErrors = null), type = true;
            if (!type) {
              if (workInProgress2.flags & 256)
                return popSuspenseHandler(workInProgress2), workInProgress2;
              popSuspenseHandler(workInProgress2);
              return null;
            }
          }
          popSuspenseHandler(workInProgress2);
          if (0 !== (workInProgress2.flags & 128))
            return workInProgress2.lanes = renderLanes2, workInProgress2;
          renderLanes2 = null !== newProps;
          current = null !== current && null !== current.memoizedState;
          if (renderLanes2) {
            newProps = workInProgress2.child;
            type = null;
            null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (type = newProps.alternate.memoizedState.cachePool.pool);
            var cache$144 = null;
            null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (cache$144 = newProps.memoizedState.cachePool.pool);
            cache$144 !== type && (newProps.flags |= 2048);
          }
          renderLanes2 !== current && renderLanes2 && (workInProgress2.child.flags |= 8192);
          scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
          bubbleProperties(workInProgress2);
          return null;
        case 4:
          return popHostContainer(), null === current && listenToAllSupportedEvents(workInProgress2.stateNode.containerInfo), bubbleProperties(workInProgress2), null;
        case 10:
          return popProvider(workInProgress2.type), bubbleProperties(workInProgress2), null;
        case 19:
          pop$1(suspenseStackCursor);
          type = workInProgress2.memoizedState;
          if (null === type) return bubbleProperties(workInProgress2), null;
          newProps = 0 !== (workInProgress2.flags & 128);
          cache$144 = type.rendering;
          if (null === cache$144)
            if (newProps) cutOffTailIfNeeded(type, false);
            else {
              if (0 !== workInProgressRootExitStatus || null !== current && 0 !== (current.flags & 128))
                for (current = workInProgress2.child; null !== current; ) {
                  cache$144 = findFirstSuspended(current);
                  if (null !== cache$144) {
                    workInProgress2.flags |= 128;
                    cutOffTailIfNeeded(type, false);
                    current = cache$144.updateQueue;
                    workInProgress2.updateQueue = current;
                    scheduleRetryEffect(workInProgress2, current);
                    workInProgress2.subtreeFlags = 0;
                    current = renderLanes2;
                    for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
                      resetWorkInProgress(renderLanes2, current), renderLanes2 = renderLanes2.sibling;
                    push$1(
                      suspenseStackCursor,
                      suspenseStackCursor.current & 1 | 2
                    );
                    return workInProgress2.child;
                  }
                  current = current.sibling;
                }
              null !== type.tail && now() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(type, false), workInProgress2.lanes = 4194304);
            }
          else {
            if (!newProps)
              if (current = findFirstSuspended(cache$144), null !== current) {
                if (workInProgress2.flags |= 128, newProps = true, current = current.updateQueue, workInProgress2.updateQueue = current, scheduleRetryEffect(workInProgress2, current), cutOffTailIfNeeded(type, true), null === type.tail && "hidden" === type.tailMode && !cache$144.alternate && !isHydrating)
                  return bubbleProperties(workInProgress2), null;
              } else
                2 * now() - type.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, newProps = true, cutOffTailIfNeeded(type, false), workInProgress2.lanes = 4194304);
            type.isBackwards ? (cache$144.sibling = workInProgress2.child, workInProgress2.child = cache$144) : (current = type.last, null !== current ? current.sibling = cache$144 : workInProgress2.child = cache$144, type.last = cache$144);
          }
          if (null !== type.tail)
            return workInProgress2 = type.tail, type.rendering = workInProgress2, type.tail = workInProgress2.sibling, type.renderingStartTime = now(), workInProgress2.sibling = null, current = suspenseStackCursor.current, push$1(suspenseStackCursor, newProps ? current & 1 | 2 : current & 1), workInProgress2;
          bubbleProperties(workInProgress2);
          return null;
        case 22:
        case 23:
          return popSuspenseHandler(workInProgress2), popHiddenContext(), newProps = null !== workInProgress2.memoizedState, null !== current ? null !== current.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (renderLanes2 = current.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current && pop$1(resumedCache), null;
        case 24:
          return renderLanes2 = null, null !== current && (renderLanes2 = current.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext), bubbleProperties(workInProgress2), null;
        case 25:
          return null;
      }
      throw Error(formatProdErrorMessage(156, workInProgress2.tag));
    }
    function unwindWork(current, workInProgress2) {
      popTreeContext(workInProgress2);
      switch (workInProgress2.tag) {
        case 1:
          return current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
        case 3:
          return popProvider(CacheContext), popHostContainer(), current = workInProgress2.flags, 0 !== (current & 65536) && 0 === (current & 128) ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
        case 26:
        case 27:
        case 5:
          return popHostContext(workInProgress2), null;
        case 13:
          popSuspenseHandler(workInProgress2);
          current = workInProgress2.memoizedState;
          if (null !== current && null !== current.dehydrated) {
            if (null === workInProgress2.alternate)
              throw Error(formatProdErrorMessage(340));
            resetHydrationState();
          }
          current = workInProgress2.flags;
          return current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
        case 19:
          return pop$1(suspenseStackCursor), null;
        case 4:
          return popHostContainer(), null;
        case 10:
          return popProvider(workInProgress2.type), null;
        case 22:
        case 23:
          return popSuspenseHandler(workInProgress2), popHiddenContext(), null !== current && pop$1(resumedCache), current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
        case 24:
          return popProvider(CacheContext), null;
        case 25:
          return null;
        default:
          return null;
      }
    }
    function unwindInterruptedWork(current, interruptedWork) {
      popTreeContext(interruptedWork);
      switch (interruptedWork.tag) {
        case 3:
          popProvider(CacheContext);
          popHostContainer();
          break;
        case 26:
        case 27:
        case 5:
          popHostContext(interruptedWork);
          break;
        case 4:
          popHostContainer();
          break;
        case 13:
          popSuspenseHandler(interruptedWork);
          break;
        case 19:
          pop$1(suspenseStackCursor);
          break;
        case 10:
          popProvider(interruptedWork.type);
          break;
        case 22:
        case 23:
          popSuspenseHandler(interruptedWork);
          popHiddenContext();
          null !== current && pop$1(resumedCache);
          break;
        case 24:
          popProvider(CacheContext);
      }
    }
    var DefaultAsyncDispatcher = {
      getCacheForType: function(resourceType) {
        var cache = readContext(CacheContext), cacheForType = cache.data.get(resourceType);
        void 0 === cacheForType && (cacheForType = resourceType(), cache.data.set(resourceType, cacheForType));
        return cacheForType;
      }
    }, PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, executionContext = 0, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = 0, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, workInProgressRootRenderTargetTime = Infinity, workInProgressTransitions = null, legacyErrorBoundariesThatAlreadyFailed = null, rootDoesHavePassiveEffects = false, rootWithPendingPassiveEffects = null, pendingPassiveEffectsLanes = 0, pendingPassiveEffectsRemainingLanes = 0, pendingPassiveTransitions = null, nestedUpdateCount = 0, rootWithNestedUpdates = null;
    function requestUpdateLane() {
      if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes)
        return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
      if (null !== ReactSharedInternals.T) {
        var actionScopeLane = currentEntangledLane;
        return 0 !== actionScopeLane ? actionScopeLane : requestTransitionLane();
      }
      return resolveUpdatePriority();
    }
    function requestDeferredLane() {
      0 === workInProgressDeferredLane && (workInProgressDeferredLane = 0 === (workInProgressRootRenderLanes & 536870912) || isHydrating ? claimNextTransitionLane() : 536870912);
      var suspenseHandler = suspenseHandlerStackCursor.current;
      null !== suspenseHandler && (suspenseHandler.flags |= 32);
      return workInProgressDeferredLane;
    }
    function scheduleUpdateOnFiber(root2, fiber, lane) {
      if (root2 === workInProgressRoot && 2 === workInProgressSuspendedReason || null !== root2.cancelPendingCommit)
        prepareFreshStack(root2, 0), markRootSuspended(
          root2,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        );
      markRootUpdated$1(root2, lane);
      if (0 === (executionContext & 2) || root2 !== workInProgressRoot)
        root2 === workInProgressRoot && (0 === (executionContext & 2) && (workInProgressRootInterleavedUpdatedLanes |= lane), 4 === workInProgressRootExitStatus && markRootSuspended(
          root2,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        )), ensureRootIsScheduled(root2);
    }
    function performWorkOnRoot(root$jscomp$0, lanes, forceSync) {
      if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
      var shouldTimeSlice = !forceSync && 0 === (lanes & 60) && 0 === (lanes & root$jscomp$0.expiredLanes) || checkIfRootIsPrerendering(root$jscomp$0, lanes), exitStatus = shouldTimeSlice ? renderRootConcurrent(root$jscomp$0, lanes) : renderRootSync(root$jscomp$0, lanes, true), renderWasConcurrent = shouldTimeSlice;
      do {
        if (0 === exitStatus) {
          workInProgressRootIsPrerendering && !shouldTimeSlice && markRootSuspended(root$jscomp$0, lanes, 0, false);
          break;
        } else if (6 === exitStatus)
          markRootSuspended(
            root$jscomp$0,
            lanes,
            0,
            !workInProgressRootDidSkipSuspendedSiblings
          );
        else {
          forceSync = root$jscomp$0.current.alternate;
          if (renderWasConcurrent && !isRenderConsistentWithExternalStores(forceSync)) {
            exitStatus = renderRootSync(root$jscomp$0, lanes, false);
            renderWasConcurrent = false;
            continue;
          }
          if (2 === exitStatus) {
            renderWasConcurrent = lanes;
            if (root$jscomp$0.errorRecoveryDisabledLanes & renderWasConcurrent)
              var JSCompiler_inline_result = 0;
            else
              JSCompiler_inline_result = root$jscomp$0.pendingLanes & -536870913, JSCompiler_inline_result = 0 !== JSCompiler_inline_result ? JSCompiler_inline_result : JSCompiler_inline_result & 536870912 ? 536870912 : 0;
            if (0 !== JSCompiler_inline_result) {
              lanes = JSCompiler_inline_result;
              a: {
                var root2 = root$jscomp$0;
                exitStatus = workInProgressRootConcurrentErrors;
                var wasRootDehydrated = root2.current.memoizedState.isDehydrated;
                wasRootDehydrated && (prepareFreshStack(root2, JSCompiler_inline_result).flags |= 256);
                JSCompiler_inline_result = renderRootSync(
                  root2,
                  JSCompiler_inline_result,
                  false
                );
                if (2 !== JSCompiler_inline_result) {
                  if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
                    root2.errorRecoveryDisabledLanes |= renderWasConcurrent;
                    workInProgressRootInterleavedUpdatedLanes |= renderWasConcurrent;
                    exitStatus = 4;
                    break a;
                  }
                  renderWasConcurrent = workInProgressRootRecoverableErrors;
                  workInProgressRootRecoverableErrors = exitStatus;
                  null !== renderWasConcurrent && queueRecoverableErrors(renderWasConcurrent);
                }
                exitStatus = JSCompiler_inline_result;
              }
              renderWasConcurrent = false;
              if (2 !== exitStatus) continue;
            }
          }
          if (1 === exitStatus) {
            prepareFreshStack(root$jscomp$0, 0);
            markRootSuspended(root$jscomp$0, lanes, 0, true);
            break;
          }
          a: {
            shouldTimeSlice = root$jscomp$0;
            switch (exitStatus) {
              case 0:
              case 1:
                throw Error(formatProdErrorMessage(345));
              case 4:
                if ((lanes & 4194176) === lanes) {
                  markRootSuspended(
                    shouldTimeSlice,
                    lanes,
                    workInProgressDeferredLane,
                    !workInProgressRootDidSkipSuspendedSiblings
                  );
                  break a;
                }
                break;
              case 2:
                workInProgressRootRecoverableErrors = null;
                break;
              case 3:
              case 5:
                break;
              default:
                throw Error(formatProdErrorMessage(329));
            }
            shouldTimeSlice.finishedWork = forceSync;
            shouldTimeSlice.finishedLanes = lanes;
            if ((lanes & 62914560) === lanes && (renderWasConcurrent = globalMostRecentFallbackTime + 300 - now(), 10 < renderWasConcurrent)) {
              markRootSuspended(
                shouldTimeSlice,
                lanes,
                workInProgressDeferredLane,
                !workInProgressRootDidSkipSuspendedSiblings
              );
              if (0 !== getNextLanes(shouldTimeSlice, 0)) break a;
              shouldTimeSlice.timeoutHandle = scheduleTimeout(
                commitRootWhenReady.bind(
                  null,
                  shouldTimeSlice,
                  forceSync,
                  workInProgressRootRecoverableErrors,
                  workInProgressTransitions,
                  workInProgressRootDidIncludeRecursiveRenderUpdate,
                  lanes,
                  workInProgressDeferredLane,
                  workInProgressRootInterleavedUpdatedLanes,
                  workInProgressSuspendedRetryLanes,
                  workInProgressRootDidSkipSuspendedSiblings,
                  2,
                  -0,
                  0
                ),
                renderWasConcurrent
              );
              break a;
            }
            commitRootWhenReady(
              shouldTimeSlice,
              forceSync,
              workInProgressRootRecoverableErrors,
              workInProgressTransitions,
              workInProgressRootDidIncludeRecursiveRenderUpdate,
              lanes,
              workInProgressDeferredLane,
              workInProgressRootInterleavedUpdatedLanes,
              workInProgressSuspendedRetryLanes,
              workInProgressRootDidSkipSuspendedSiblings,
              0,
              -0,
              0
            );
          }
        }
        break;
      } while (1);
      ensureRootIsScheduled(root$jscomp$0);
    }
    function queueRecoverableErrors(errors2) {
      null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = errors2 : workInProgressRootRecoverableErrors.push.apply(
        workInProgressRootRecoverableErrors,
        errors2
      );
    }
    function commitRootWhenReady(root2, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
      var subtreeFlags = finishedWork.subtreeFlags;
      if (subtreeFlags & 8192 || 16785408 === (subtreeFlags & 16785408)) {
        if (suspendedState = { stylesheets: null, count: 0, unsuspend: noop }, accumulateSuspenseyCommitOnFiber(finishedWork), finishedWork = waitForCommitToBeReady(), null !== finishedWork) {
          root2.cancelPendingCommit = finishedWork(
            commitRoot.bind(
              null,
              root2,
              recoverableErrors,
              transitions,
              didIncludeRenderPhaseUpdate,
              spawnedLane,
              updatedLanes,
              suspendedRetryLanes,
              1,
              completedRenderStartTime,
              completedRenderEndTime
            )
          );
          markRootSuspended(root2, lanes, spawnedLane, !didSkipSuspendedSiblings);
          return;
        }
      }
      commitRoot(
        root2,
        recoverableErrors,
        transitions,
        didIncludeRenderPhaseUpdate,
        spawnedLane,
        updatedLanes,
        suspendedRetryLanes,
        suspendedCommitReason,
        completedRenderStartTime,
        completedRenderEndTime
      );
    }
    function isRenderConsistentWithExternalStores(finishedWork) {
      for (var node2 = finishedWork; ; ) {
        var tag = node2.tag;
        if ((0 === tag || 11 === tag || 15 === tag) && node2.flags & 16384 && (tag = node2.updateQueue, null !== tag && (tag = tag.stores, null !== tag)))
          for (var i2 = 0; i2 < tag.length; i2++) {
            var check = tag[i2], getSnapshot = check.getSnapshot;
            check = check.value;
            try {
              if (!objectIs(getSnapshot(), check)) return false;
            } catch (error2) {
              return false;
            }
          }
        tag = node2.child;
        if (node2.subtreeFlags & 16384 && null !== tag)
          tag.return = node2, node2 = tag;
        else {
          if (node2 === finishedWork) break;
          for (; null === node2.sibling; ) {
            if (null === node2.return || node2.return === finishedWork) return true;
            node2 = node2.return;
          }
          node2.sibling.return = node2.return;
          node2 = node2.sibling;
        }
      }
      return true;
    }
    function markRootSuspended(root2, suspendedLanes, spawnedLane, didAttemptEntireTree) {
      suspendedLanes &= ~workInProgressRootPingedLanes;
      suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
      root2.suspendedLanes |= suspendedLanes;
      root2.pingedLanes &= ~suspendedLanes;
      didAttemptEntireTree && (root2.warmLanes |= suspendedLanes);
      didAttemptEntireTree = root2.expirationTimes;
      for (var lanes = suspendedLanes; 0 < lanes; ) {
        var index$6 = 31 - clz32(lanes), lane = 1 << index$6;
        didAttemptEntireTree[index$6] = -1;
        lanes &= ~lane;
      }
      0 !== spawnedLane && markSpawnedDeferredLane(root2, spawnedLane, suspendedLanes);
    }
    function flushSyncWork$1() {
      return 0 === (executionContext & 6) ? (flushSyncWorkAcrossRoots_impl(0), false) : true;
    }
    function resetWorkInProgressStack() {
      if (null !== workInProgress) {
        if (0 === workInProgressSuspendedReason)
          var interruptedWork = workInProgress.return;
        else
          interruptedWork = workInProgress, lastContextDependency = currentlyRenderingFiber = null, resetHooksOnUnwind(interruptedWork), thenableState$1 = null, thenableIndexCounter$1 = 0, interruptedWork = workInProgress;
        for (; null !== interruptedWork; )
          unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
        workInProgress = null;
      }
    }
    function prepareFreshStack(root2, lanes) {
      root2.finishedWork = null;
      root2.finishedLanes = 0;
      var timeoutHandle = root2.timeoutHandle;
      -1 !== timeoutHandle && (root2.timeoutHandle = -1, cancelTimeout(timeoutHandle));
      timeoutHandle = root2.cancelPendingCommit;
      null !== timeoutHandle && (root2.cancelPendingCommit = null, timeoutHandle());
      resetWorkInProgressStack();
      workInProgressRoot = root2;
      workInProgress = timeoutHandle = createWorkInProgress(root2.current, null);
      workInProgressRootRenderLanes = lanes;
      workInProgressSuspendedReason = 0;
      workInProgressThrownValue = null;
      workInProgressRootDidSkipSuspendedSiblings = false;
      workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root2, lanes);
      workInProgressRootDidAttachPingListener = false;
      workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = workInProgressRootExitStatus = 0;
      workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
      workInProgressRootDidIncludeRecursiveRenderUpdate = false;
      0 !== (lanes & 8) && (lanes |= lanes & 32);
      var allEntangledLanes = root2.entangledLanes;
      if (0 !== allEntangledLanes)
        for (root2 = root2.entanglements, allEntangledLanes &= lanes; 0 < allEntangledLanes; ) {
          var index$4 = 31 - clz32(allEntangledLanes), lane = 1 << index$4;
          lanes |= root2[index$4];
          allEntangledLanes &= ~lane;
        }
      entangledRenderLanes = lanes;
      finishQueueingConcurrentUpdates();
      return timeoutHandle;
    }
    function handleThrow(root2, thrownValue) {
      currentlyRenderingFiber$1 = null;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      thrownValue === SuspenseException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 3) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 4) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? 8 : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? 6 : 1;
      workInProgressThrownValue = thrownValue;
      null === workInProgress && (workInProgressRootExitStatus = 1, logUncaughtError(
        root2,
        createCapturedValueAtFiber(thrownValue, root2.current)
      ));
    }
    function pushDispatcher() {
      var prevDispatcher = ReactSharedInternals.H;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
    }
    function pushAsyncDispatcher() {
      var prevAsyncDispatcher = ReactSharedInternals.A;
      ReactSharedInternals.A = DefaultAsyncDispatcher;
      return prevAsyncDispatcher;
    }
    function renderDidSuspendDelayIfPossible() {
      workInProgressRootExitStatus = 4;
      workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194176) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
      0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
        workInProgressRoot,
        workInProgressRootRenderLanes,
        workInProgressDeferredLane,
        false
      );
    }
    function renderRootSync(root2, lanes, shouldYieldForPrerendering) {
      var prevExecutionContext = executionContext;
      executionContext |= 2;
      var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
      if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes)
        workInProgressTransitions = null, prepareFreshStack(root2, lanes);
      lanes = false;
      var exitStatus = workInProgressRootExitStatus;
      a: do
        try {
          if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
            var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
            switch (workInProgressSuspendedReason) {
              case 8:
                resetWorkInProgressStack();
                exitStatus = 6;
                break a;
              case 3:
              case 2:
              case 6:
                null === suspenseHandlerStackCursor.current && (lanes = true);
                var reason = workInProgressSuspendedReason;
                workInProgressSuspendedReason = 0;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, reason);
                if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
                  exitStatus = 0;
                  break a;
                }
                break;
              default:
                reason = workInProgressSuspendedReason, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, reason);
            }
          }
          workLoopSync();
          exitStatus = workInProgressRootExitStatus;
          break;
        } catch (thrownValue$164) {
          handleThrow(root2, thrownValue$164);
        }
      while (1);
      lanes && root2.shellSuspendCounter++;
      lastContextDependency = currentlyRenderingFiber = null;
      executionContext = prevExecutionContext;
      ReactSharedInternals.H = prevDispatcher;
      ReactSharedInternals.A = prevAsyncDispatcher;
      null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
      return exitStatus;
    }
    function workLoopSync() {
      for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
    }
    function renderRootConcurrent(root2, lanes) {
      var prevExecutionContext = executionContext;
      executionContext |= 2;
      var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
      workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes ? (workInProgressTransitions = null, workInProgressRootRenderTargetTime = now() + 500, prepareFreshStack(root2, lanes)) : workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
        root2,
        lanes
      );
      a: do
        try {
          if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
            lanes = workInProgress;
            var thrownValue = workInProgressThrownValue;
            b: switch (workInProgressSuspendedReason) {
              case 1:
                workInProgressSuspendedReason = 0;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(root2, lanes, thrownValue, 1);
                break;
              case 2:
                if (isThenableResolved(thrownValue)) {
                  workInProgressSuspendedReason = 0;
                  workInProgressThrownValue = null;
                  replaySuspendedUnitOfWork(lanes);
                  break;
                }
                lanes = function() {
                  2 === workInProgressSuspendedReason && workInProgressRoot === root2 && (workInProgressSuspendedReason = 7);
                  ensureRootIsScheduled(root2);
                };
                thrownValue.then(lanes, lanes);
                break a;
              case 3:
                workInProgressSuspendedReason = 7;
                break a;
              case 4:
                workInProgressSuspendedReason = 5;
                break a;
              case 7:
                isThenableResolved(thrownValue) ? (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root2, lanes, thrownValue, 7));
                break;
              case 5:
                var resource = null;
                switch (workInProgress.tag) {
                  case 26:
                    resource = workInProgress.memoizedState;
                  case 5:
                  case 27:
                    var hostFiber = workInProgress;
                    if (resource ? preloadResource(resource) : 1) {
                      workInProgressSuspendedReason = 0;
                      workInProgressThrownValue = null;
                      var sibling = hostFiber.sibling;
                      if (null !== sibling) workInProgress = sibling;
                      else {
                        var returnFiber = hostFiber.return;
                        null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
                      }
                      break b;
                    }
                }
                workInProgressSuspendedReason = 0;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(root2, lanes, thrownValue, 5);
                break;
              case 6:
                workInProgressSuspendedReason = 0;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(root2, lanes, thrownValue, 6);
                break;
              case 8:
                resetWorkInProgressStack();
                workInProgressRootExitStatus = 6;
                break a;
              default:
                throw Error(formatProdErrorMessage(462));
            }
          }
          workLoopConcurrent();
          break;
        } catch (thrownValue$166) {
          handleThrow(root2, thrownValue$166);
        }
      while (1);
      lastContextDependency = currentlyRenderingFiber = null;
      ReactSharedInternals.H = prevDispatcher;
      ReactSharedInternals.A = prevAsyncDispatcher;
      executionContext = prevExecutionContext;
      if (null !== workInProgress) return 0;
      workInProgressRoot = null;
      workInProgressRootRenderLanes = 0;
      finishQueueingConcurrentUpdates();
      return workInProgressRootExitStatus;
    }
    function workLoopConcurrent() {
      for (; null !== workInProgress && !shouldYield(); )
        performUnitOfWork(workInProgress);
    }
    function performUnitOfWork(unitOfWork) {
      var next = beginWork(unitOfWork.alternate, unitOfWork, entangledRenderLanes);
      unitOfWork.memoizedProps = unitOfWork.pendingProps;
      null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
    }
    function replaySuspendedUnitOfWork(unitOfWork) {
      var next = unitOfWork;
      var current = next.alternate;
      switch (next.tag) {
        case 15:
        case 0:
          next = replayFunctionComponent(
            current,
            next,
            next.pendingProps,
            next.type,
            void 0,
            workInProgressRootRenderLanes
          );
          break;
        case 11:
          next = replayFunctionComponent(
            current,
            next,
            next.pendingProps,
            next.type.render,
            next.ref,
            workInProgressRootRenderLanes
          );
          break;
        case 5:
          resetHooksOnUnwind(next);
        default:
          unwindInterruptedWork(current, next), next = workInProgress = resetWorkInProgress(next, entangledRenderLanes), next = beginWork(current, next, entangledRenderLanes);
      }
      unitOfWork.memoizedProps = unitOfWork.pendingProps;
      null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
    }
    function throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, suspendedReason) {
      lastContextDependency = currentlyRenderingFiber = null;
      resetHooksOnUnwind(unitOfWork);
      thenableState$1 = null;
      thenableIndexCounter$1 = 0;
      var returnFiber = unitOfWork.return;
      try {
        if (throwException(
          root2,
          returnFiber,
          unitOfWork,
          thrownValue,
          workInProgressRootRenderLanes
        )) {
          workInProgressRootExitStatus = 1;
          logUncaughtError(
            root2,
            createCapturedValueAtFiber(thrownValue, root2.current)
          );
          workInProgress = null;
          return;
        }
      } catch (error2) {
        if (null !== returnFiber) throw workInProgress = returnFiber, error2;
        workInProgressRootExitStatus = 1;
        logUncaughtError(
          root2,
          createCapturedValueAtFiber(thrownValue, root2.current)
        );
        workInProgress = null;
        return;
      }
      if (unitOfWork.flags & 32768) {
        if (isHydrating || 1 === suspendedReason) root2 = true;
        else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
          root2 = false;
        else if (workInProgressRootDidSkipSuspendedSiblings = root2 = true, 2 === suspendedReason || 3 === suspendedReason || 6 === suspendedReason)
          suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
        unwindUnitOfWork(unitOfWork, root2);
      } else completeUnitOfWork(unitOfWork);
    }
    function completeUnitOfWork(unitOfWork) {
      var completedWork = unitOfWork;
      do {
        if (0 !== (completedWork.flags & 32768)) {
          unwindUnitOfWork(
            completedWork,
            workInProgressRootDidSkipSuspendedSiblings
          );
          return;
        }
        unitOfWork = completedWork.return;
        var next = completeWork(
          completedWork.alternate,
          completedWork,
          entangledRenderLanes
        );
        if (null !== next) {
          workInProgress = next;
          return;
        }
        completedWork = completedWork.sibling;
        if (null !== completedWork) {
          workInProgress = completedWork;
          return;
        }
        workInProgress = completedWork = unitOfWork;
      } while (null !== completedWork);
      0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5);
    }
    function unwindUnitOfWork(unitOfWork, skipSiblings) {
      do {
        var next = unwindWork(unitOfWork.alternate, unitOfWork);
        if (null !== next) {
          next.flags &= 32767;
          workInProgress = next;
          return;
        }
        next = unitOfWork.return;
        null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
        if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
          workInProgress = unitOfWork;
          return;
        }
        workInProgress = unitOfWork = next;
      } while (null !== unitOfWork);
      workInProgressRootExitStatus = 6;
      workInProgress = null;
    }
    function commitRoot(root2, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
      var prevTransition = ReactSharedInternals.T, previousUpdateLanePriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = 2, ReactSharedInternals.T = null, commitRootImpl(
          root2,
          recoverableErrors,
          transitions,
          didIncludeRenderPhaseUpdate,
          previousUpdateLanePriority,
          spawnedLane,
          updatedLanes,
          suspendedRetryLanes,
          suspendedCommitReason,
          completedRenderStartTime,
          completedRenderEndTime
        );
      } finally {
        ReactSharedInternals.T = prevTransition, ReactDOMSharedInternals.p = previousUpdateLanePriority;
      }
    }
    function commitRootImpl(root2, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, renderPriorityLevel, spawnedLane, updatedLanes, suspendedRetryLanes) {
      do
        flushPassiveEffects();
      while (null !== rootWithPendingPassiveEffects);
      if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
      var finishedWork = root2.finishedWork;
      didIncludeRenderPhaseUpdate = root2.finishedLanes;
      if (null === finishedWork) return null;
      root2.finishedWork = null;
      root2.finishedLanes = 0;
      if (finishedWork === root2.current) throw Error(formatProdErrorMessage(177));
      root2.callbackNode = null;
      root2.callbackPriority = 0;
      root2.cancelPendingCommit = null;
      var remainingLanes = finishedWork.lanes | finishedWork.childLanes;
      remainingLanes |= concurrentlyUpdatedLanes;
      markRootFinished(
        root2,
        didIncludeRenderPhaseUpdate,
        remainingLanes,
        spawnedLane,
        updatedLanes,
        suspendedRetryLanes
      );
      root2 === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
      0 === (finishedWork.subtreeFlags & 10256) && 0 === (finishedWork.flags & 10256) || rootDoesHavePassiveEffects || (rootDoesHavePassiveEffects = true, pendingPassiveEffectsRemainingLanes = remainingLanes, pendingPassiveTransitions = transitions, scheduleCallback$1(NormalPriority$1, function() {
        flushPassiveEffects();
        return null;
      }));
      transitions = 0 !== (finishedWork.flags & 15990);
      0 !== (finishedWork.subtreeFlags & 15990) || transitions ? (transitions = ReactSharedInternals.T, ReactSharedInternals.T = null, spawnedLane = ReactDOMSharedInternals.p, ReactDOMSharedInternals.p = 2, updatedLanes = executionContext, executionContext |= 4, commitBeforeMutationEffects(root2, finishedWork), commitMutationEffectsOnFiber(finishedWork, root2), restoreSelection(selectionInformation, root2.containerInfo), _enabled = !!eventsEnabled, selectionInformation = eventsEnabled = null, root2.current = finishedWork, commitLayoutEffectOnFiber(root2, finishedWork.alternate, finishedWork), requestPaint(), executionContext = updatedLanes, ReactDOMSharedInternals.p = spawnedLane, ReactSharedInternals.T = transitions) : root2.current = finishedWork;
      rootDoesHavePassiveEffects ? (rootDoesHavePassiveEffects = false, rootWithPendingPassiveEffects = root2, pendingPassiveEffectsLanes = didIncludeRenderPhaseUpdate) : releaseRootPooledCache(root2, remainingLanes);
      remainingLanes = root2.pendingLanes;
      0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
      onCommitRoot(finishedWork.stateNode);
      ensureRootIsScheduled(root2);
      if (null !== recoverableErrors)
        for (renderPriorityLevel = root2.onRecoverableError, finishedWork = 0; finishedWork < recoverableErrors.length; finishedWork++)
          remainingLanes = recoverableErrors[finishedWork], renderPriorityLevel(remainingLanes.value, {
            componentStack: remainingLanes.stack
          });
      0 !== (pendingPassiveEffectsLanes & 3) && flushPassiveEffects();
      remainingLanes = root2.pendingLanes;
      0 !== (didIncludeRenderPhaseUpdate & 4194218) && 0 !== (remainingLanes & 42) ? root2 === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = root2) : nestedUpdateCount = 0;
      flushSyncWorkAcrossRoots_impl(0);
      return null;
    }
    function releaseRootPooledCache(root2, remainingLanes) {
      0 === (root2.pooledCacheLanes &= remainingLanes) && (remainingLanes = root2.pooledCache, null != remainingLanes && (root2.pooledCache = null, releaseCache(remainingLanes)));
    }
    function flushPassiveEffects() {
      if (null !== rootWithPendingPassiveEffects) {
        var root$170 = rootWithPendingPassiveEffects, remainingLanes = pendingPassiveEffectsRemainingLanes;
        pendingPassiveEffectsRemainingLanes = 0;
        var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes), prevTransition = ReactSharedInternals.T, previousPriority = ReactDOMSharedInternals.p;
        try {
          ReactDOMSharedInternals.p = 32 > renderPriority ? 32 : renderPriority;
          ReactSharedInternals.T = null;
          if (null === rootWithPendingPassiveEffects)
            var JSCompiler_inline_result = false;
          else {
            renderPriority = pendingPassiveTransitions;
            pendingPassiveTransitions = null;
            var root2 = rootWithPendingPassiveEffects, lanes = pendingPassiveEffectsLanes;
            rootWithPendingPassiveEffects = null;
            pendingPassiveEffectsLanes = 0;
            if (0 !== (executionContext & 6))
              throw Error(formatProdErrorMessage(331));
            var prevExecutionContext = executionContext;
            executionContext |= 4;
            commitPassiveUnmountOnFiber(root2.current);
            commitPassiveMountOnFiber(root2, root2.current, lanes, renderPriority);
            executionContext = prevExecutionContext;
            flushSyncWorkAcrossRoots_impl(0, false);
            if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
              try {
                injectedHook.onPostCommitFiberRoot(rendererID, root2);
              } catch (err2) {
              }
            JSCompiler_inline_result = true;
          }
          return JSCompiler_inline_result;
        } finally {
          ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition, releaseRootPooledCache(root$170, remainingLanes);
        }
      }
      return false;
    }
    function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) {
      sourceFiber = createCapturedValueAtFiber(error2, sourceFiber);
      sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
      rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
      null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
    }
    function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error2) {
      if (3 === sourceFiber.tag)
        captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error2);
      else
        for (; null !== nearestMountedAncestor; ) {
          if (3 === nearestMountedAncestor.tag) {
            captureCommitPhaseErrorOnRoot(
              nearestMountedAncestor,
              sourceFiber,
              error2
            );
            break;
          } else if (1 === nearestMountedAncestor.tag) {
            var instance = nearestMountedAncestor.stateNode;
            if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
              sourceFiber = createCapturedValueAtFiber(error2, sourceFiber);
              error2 = createClassErrorUpdate(2);
              instance = enqueueUpdate(nearestMountedAncestor, error2, 2);
              null !== instance && (initializeClassErrorUpdate(
                error2,
                instance,
                nearestMountedAncestor,
                sourceFiber
              ), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
              break;
            }
          }
          nearestMountedAncestor = nearestMountedAncestor.return;
        }
    }
    function attachPingListener(root2, wakeable, lanes) {
      var pingCache = root2.pingCache;
      if (null === pingCache) {
        pingCache = root2.pingCache = new PossiblyWeakMap();
        var threadIDs = /* @__PURE__ */ new Set();
        pingCache.set(wakeable, threadIDs);
      } else
        threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
      threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), root2 = pingSuspendedRoot.bind(null, root2, wakeable, lanes), wakeable.then(root2, root2));
    }
    function pingSuspendedRoot(root2, wakeable, pingedLanes) {
      var pingCache = root2.pingCache;
      null !== pingCache && pingCache.delete(wakeable);
      root2.pingedLanes |= root2.suspendedLanes & pingedLanes;
      root2.warmLanes &= ~pingedLanes;
      workInProgressRoot === root2 && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (4 === workInProgressRootExitStatus || 3 === workInProgressRootExitStatus && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && 300 > now() - globalMostRecentFallbackTime ? 0 === (executionContext & 2) && prepareFreshStack(root2, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
      ensureRootIsScheduled(root2);
    }
    function retryTimedOutBoundary(boundaryFiber, retryLane) {
      0 === retryLane && (retryLane = claimNextRetryLane());
      boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
      null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
    }
    function retryDehydratedSuspenseBoundary(boundaryFiber) {
      var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
      null !== suspenseState && (retryLane = suspenseState.retryLane);
      retryTimedOutBoundary(boundaryFiber, retryLane);
    }
    function resolveRetryWakeable(boundaryFiber, wakeable) {
      var retryLane = 0;
      switch (boundaryFiber.tag) {
        case 13:
          var retryCache = boundaryFiber.stateNode;
          var suspenseState = boundaryFiber.memoizedState;
          null !== suspenseState && (retryLane = suspenseState.retryLane);
          break;
        case 19:
          retryCache = boundaryFiber.stateNode;
          break;
        case 22:
          retryCache = boundaryFiber.stateNode._retryCache;
          break;
        default:
          throw Error(formatProdErrorMessage(314));
      }
      null !== retryCache && retryCache.delete(wakeable);
      retryTimedOutBoundary(boundaryFiber, retryLane);
    }
    function scheduleCallback$1(priorityLevel, callback) {
      return scheduleCallback$3(priorityLevel, callback);
    }
    var firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0;
    function ensureRootIsScheduled(root2) {
      root2 !== lastScheduledRoot && null === root2.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root2 : lastScheduledRoot = lastScheduledRoot.next = root2);
      mightHavePendingSyncWork = true;
      didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateTask(processRootScheduleInMicrotask));
    }
    function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
      if (!isFlushingWork && mightHavePendingSyncWork) {
        isFlushingWork = true;
        do {
          var didPerformSomeWork = false;
          for (var root$172 = firstScheduledRoot; null !== root$172; ) {
            if (0 !== syncTransitionLanes) {
              var pendingLanes = root$172.pendingLanes;
              if (0 === pendingLanes) var JSCompiler_inline_result = 0;
              else {
                var suspendedLanes = root$172.suspendedLanes, pingedLanes = root$172.pingedLanes;
                JSCompiler_inline_result = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
                JSCompiler_inline_result &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
                JSCompiler_inline_result = JSCompiler_inline_result & 201326677 ? JSCompiler_inline_result & 201326677 | 1 : JSCompiler_inline_result ? JSCompiler_inline_result | 2 : 0;
              }
              0 !== JSCompiler_inline_result && (didPerformSomeWork = true, performSyncWorkOnRoot(root$172, JSCompiler_inline_result));
            } else
              JSCompiler_inline_result = workInProgressRootRenderLanes, JSCompiler_inline_result = getNextLanes(
                root$172,
                root$172 === workInProgressRoot ? JSCompiler_inline_result : 0
              ), 0 === (JSCompiler_inline_result & 3) || checkIfRootIsPrerendering(root$172, JSCompiler_inline_result) || (didPerformSomeWork = true, performSyncWorkOnRoot(root$172, JSCompiler_inline_result));
            root$172 = root$172.next;
          }
        } while (didPerformSomeWork);
        isFlushingWork = false;
      }
    }
    function processRootScheduleInMicrotask() {
      mightHavePendingSyncWork = didScheduleMicrotask = false;
      var syncTransitionLanes = 0;
      0 !== currentEventTransitionLane && (shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane), currentEventTransitionLane = 0);
      for (var currentTime = now(), prev = null, root2 = firstScheduledRoot; null !== root2; ) {
        var next = root2.next, nextLanes = scheduleTaskForRootDuringMicrotask(root2, currentTime);
        if (0 === nextLanes)
          root2.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
        else if (prev = root2, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
          mightHavePendingSyncWork = true;
        root2 = next;
      }
      flushSyncWorkAcrossRoots_impl(syncTransitionLanes);
    }
    function scheduleTaskForRootDuringMicrotask(root2, currentTime) {
      for (var suspendedLanes = root2.suspendedLanes, pingedLanes = root2.pingedLanes, expirationTimes = root2.expirationTimes, lanes = root2.pendingLanes & -62914561; 0 < lanes; ) {
        var index$5 = 31 - clz32(lanes), lane = 1 << index$5, expirationTime = expirationTimes[index$5];
        if (-1 === expirationTime) {
          if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
            expirationTimes[index$5] = computeExpirationTime(lane, currentTime);
        } else expirationTime <= currentTime && (root2.expiredLanes |= lane);
        lanes &= ~lane;
      }
      currentTime = workInProgressRoot;
      suspendedLanes = workInProgressRootRenderLanes;
      suspendedLanes = getNextLanes(
        root2,
        root2 === currentTime ? suspendedLanes : 0
      );
      pingedLanes = root2.callbackNode;
      if (0 === suspendedLanes || root2 === currentTime && 2 === workInProgressSuspendedReason || null !== root2.cancelPendingCommit)
        return null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes), root2.callbackNode = null, root2.callbackPriority = 0;
      if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root2, suspendedLanes)) {
        currentTime = suspendedLanes & -suspendedLanes;
        if (currentTime === root2.callbackPriority) return currentTime;
        null !== pingedLanes && cancelCallback$1(pingedLanes);
        switch (lanesToEventPriority(suspendedLanes)) {
          case 2:
          case 8:
            suspendedLanes = UserBlockingPriority;
            break;
          case 32:
            suspendedLanes = NormalPriority$1;
            break;
          case 268435456:
            suspendedLanes = IdlePriority;
            break;
          default:
            suspendedLanes = NormalPriority$1;
        }
        pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root2);
        suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
        root2.callbackPriority = currentTime;
        root2.callbackNode = suspendedLanes;
        return currentTime;
      }
      null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes);
      root2.callbackPriority = 2;
      root2.callbackNode = null;
      return 2;
    }
    function performWorkOnRootViaSchedulerTask(root2, didTimeout) {
      var originalCallbackNode = root2.callbackNode;
      if (flushPassiveEffects() && root2.callbackNode !== originalCallbackNode)
        return null;
      var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
      workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
        root2,
        root2 === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0
      );
      if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
      performWorkOnRoot(root2, workInProgressRootRenderLanes$jscomp$0, didTimeout);
      scheduleTaskForRootDuringMicrotask(root2, now());
      return null != root2.callbackNode && root2.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root2) : null;
    }
    function performSyncWorkOnRoot(root2, lanes) {
      if (flushPassiveEffects()) return null;
      performWorkOnRoot(root2, lanes, true);
    }
    function scheduleImmediateTask(cb) {
      scheduleMicrotask(function() {
        0 !== (executionContext & 6) ? scheduleCallback$3(ImmediatePriority, cb) : cb();
      });
    }
    function requestTransitionLane() {
      0 === currentEventTransitionLane && (currentEventTransitionLane = claimNextTransitionLane());
      return currentEventTransitionLane;
    }
    function coerceFormActionProp(actionProp) {
      return null == actionProp || "symbol" === typeof actionProp || "boolean" === typeof actionProp ? null : "function" === typeof actionProp ? actionProp : sanitizeURL("" + actionProp);
    }
    function createFormDataWithSubmitter(form, submitter) {
      var temp = submitter.ownerDocument.createElement("input");
      temp.name = submitter.name;
      temp.value = submitter.value;
      form.id && temp.setAttribute("form", form.id);
      submitter.parentNode.insertBefore(temp, submitter);
      form = new FormData(form);
      temp.parentNode.removeChild(temp);
      return form;
    }
    function extractEvents$1(dispatchQueue, domEventName, maybeTargetInst, nativeEvent, nativeEventTarget) {
      if ("submit" === domEventName && maybeTargetInst && maybeTargetInst.stateNode === nativeEventTarget) {
        var action = coerceFormActionProp(
          (nativeEventTarget[internalPropsKey] || null).action
        ), submitter = nativeEvent.submitter;
        submitter && (domEventName = (domEventName = submitter[internalPropsKey] || null) ? coerceFormActionProp(domEventName.formAction) : submitter.getAttribute("formAction"), null !== domEventName && (action = domEventName, submitter = null));
        var event = new SyntheticEvent(
          "action",
          "action",
          null,
          nativeEvent,
          nativeEventTarget
        );
        dispatchQueue.push({
          event,
          listeners: [
            {
              instance: null,
              listener: function() {
                if (nativeEvent.defaultPrevented) {
                  if (0 !== currentEventTransitionLane) {
                    var formData = submitter ? createFormDataWithSubmitter(nativeEventTarget, submitter) : new FormData(nativeEventTarget);
                    startHostTransition(
                      maybeTargetInst,
                      {
                        pending: true,
                        data: formData,
                        method: nativeEventTarget.method,
                        action
                      },
                      null,
                      formData
                    );
                  }
                } else
                  "function" === typeof action && (event.preventDefault(), formData = submitter ? createFormDataWithSubmitter(nativeEventTarget, submitter) : new FormData(nativeEventTarget), startHostTransition(
                    maybeTargetInst,
                    {
                      pending: true,
                      data: formData,
                      method: nativeEventTarget.method,
                      action
                    },
                    action,
                    formData
                  ));
              },
              currentTarget: nativeEventTarget
            }
          ]
        });
      }
    }
    for (var i$jscomp$inline_1439 = 0; i$jscomp$inline_1439 < simpleEventPluginEvents.length; i$jscomp$inline_1439++) {
      var eventName$jscomp$inline_1440 = simpleEventPluginEvents[i$jscomp$inline_1439], domEventName$jscomp$inline_1441 = eventName$jscomp$inline_1440.toLowerCase(), capitalizedEvent$jscomp$inline_1442 = eventName$jscomp$inline_1440[0].toUpperCase() + eventName$jscomp$inline_1440.slice(1);
      registerSimpleEvent(
        domEventName$jscomp$inline_1441,
        "on" + capitalizedEvent$jscomp$inline_1442
      );
    }
    registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
    registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
    registerSimpleEvent(ANIMATION_START, "onAnimationStart");
    registerSimpleEvent("dblclick", "onDoubleClick");
    registerSimpleEvent("focusin", "onFocus");
    registerSimpleEvent("focusout", "onBlur");
    registerSimpleEvent(TRANSITION_RUN, "onTransitionRun");
    registerSimpleEvent(TRANSITION_START, "onTransitionStart");
    registerSimpleEvent(TRANSITION_CANCEL, "onTransitionCancel");
    registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
    registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
    registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
    registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
    registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
    registerTwoPhaseEvent(
      "onChange",
      "change click focusin focusout input keydown keyup selectionchange".split(" ")
    );
    registerTwoPhaseEvent(
      "onSelect",
      "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(
        " "
      )
    );
    registerTwoPhaseEvent("onBeforeInput", [
      "compositionend",
      "keypress",
      "textInput",
      "paste"
    ]);
    registerTwoPhaseEvent(
      "onCompositionEnd",
      "compositionend focusout keydown keypress keyup mousedown".split(" ")
    );
    registerTwoPhaseEvent(
      "onCompositionStart",
      "compositionstart focusout keydown keypress keyup mousedown".split(" ")
    );
    registerTwoPhaseEvent(
      "onCompositionUpdate",
      "compositionupdate focusout keydown keypress keyup mousedown".split(" ")
    );
    var mediaEventTypes = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(
      " "
    ), nonDelegatedEvents = new Set(
      "beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(mediaEventTypes)
    );
    function processDispatchQueue(dispatchQueue, eventSystemFlags) {
      eventSystemFlags = 0 !== (eventSystemFlags & 4);
      for (var i2 = 0; i2 < dispatchQueue.length; i2++) {
        var _dispatchQueue$i = dispatchQueue[i2], event = _dispatchQueue$i.event;
        _dispatchQueue$i = _dispatchQueue$i.listeners;
        a: {
          var previousInstance = void 0;
          if (eventSystemFlags)
            for (var i$jscomp$0 = _dispatchQueue$i.length - 1; 0 <= i$jscomp$0; i$jscomp$0--) {
              var _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget;
              _dispatchListeners$i = _dispatchListeners$i.listener;
              if (instance !== previousInstance && event.isPropagationStopped())
                break a;
              previousInstance = _dispatchListeners$i;
              event.currentTarget = currentTarget;
              try {
                previousInstance(event);
              } catch (error2) {
                reportGlobalError(error2);
              }
              event.currentTarget = null;
              previousInstance = instance;
            }
          else
            for (i$jscomp$0 = 0; i$jscomp$0 < _dispatchQueue$i.length; i$jscomp$0++) {
              _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0];
              instance = _dispatchListeners$i.instance;
              currentTarget = _dispatchListeners$i.currentTarget;
              _dispatchListeners$i = _dispatchListeners$i.listener;
              if (instance !== previousInstance && event.isPropagationStopped())
                break a;
              previousInstance = _dispatchListeners$i;
              event.currentTarget = currentTarget;
              try {
                previousInstance(event);
              } catch (error2) {
                reportGlobalError(error2);
              }
              event.currentTarget = null;
              previousInstance = instance;
            }
        }
      }
    }
    function listenToNonDelegatedEvent(domEventName, targetElement) {
      var JSCompiler_inline_result = targetElement[internalEventHandlersKey];
      void 0 === JSCompiler_inline_result && (JSCompiler_inline_result = targetElement[internalEventHandlersKey] = /* @__PURE__ */ new Set());
      var listenerSetKey = domEventName + "__bubble";
      JSCompiler_inline_result.has(listenerSetKey) || (addTrappedEventListener(targetElement, domEventName, 2, false), JSCompiler_inline_result.add(listenerSetKey));
    }
    function listenToNativeEvent(domEventName, isCapturePhaseListener, target2) {
      var eventSystemFlags = 0;
      isCapturePhaseListener && (eventSystemFlags |= 4);
      addTrappedEventListener(
        target2,
        domEventName,
        eventSystemFlags,
        isCapturePhaseListener
      );
    }
    var listeningMarker = "_reactListening" + Math.random().toString(36).slice(2);
    function listenToAllSupportedEvents(rootContainerElement) {
      if (!rootContainerElement[listeningMarker]) {
        rootContainerElement[listeningMarker] = true;
        allNativeEvents.forEach(function(domEventName) {
          "selectionchange" !== domEventName && (nonDelegatedEvents.has(domEventName) || listenToNativeEvent(domEventName, false, rootContainerElement), listenToNativeEvent(domEventName, true, rootContainerElement));
        });
        var ownerDocument = 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
        null === ownerDocument || ownerDocument[listeningMarker] || (ownerDocument[listeningMarker] = true, listenToNativeEvent("selectionchange", false, ownerDocument));
      }
    }
    function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener) {
      switch (getEventPriority(domEventName)) {
        case 2:
          var listenerWrapper = dispatchDiscreteEvent;
          break;
        case 8:
          listenerWrapper = dispatchContinuousEvent;
          break;
        default:
          listenerWrapper = dispatchEvent;
      }
      eventSystemFlags = listenerWrapper.bind(
        null,
        domEventName,
        eventSystemFlags,
        targetContainer
      );
      listenerWrapper = void 0;
      !passiveBrowserEventsSupported || "touchstart" !== domEventName && "touchmove" !== domEventName && "wheel" !== domEventName || (listenerWrapper = true);
      isCapturePhaseListener ? void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
        capture: true,
        passive: listenerWrapper
      }) : targetContainer.addEventListener(domEventName, eventSystemFlags, true) : void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
        passive: listenerWrapper
      }) : targetContainer.addEventListener(domEventName, eventSystemFlags, false);
    }
    function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst$jscomp$0, targetContainer) {
      var ancestorInst = targetInst$jscomp$0;
      if (0 === (eventSystemFlags & 1) && 0 === (eventSystemFlags & 2) && null !== targetInst$jscomp$0)
        a: for (; ; ) {
          if (null === targetInst$jscomp$0) return;
          var nodeTag = targetInst$jscomp$0.tag;
          if (3 === nodeTag || 4 === nodeTag) {
            var container2 = targetInst$jscomp$0.stateNode.containerInfo;
            if (container2 === targetContainer || 8 === container2.nodeType && container2.parentNode === targetContainer)
              break;
            if (4 === nodeTag)
              for (nodeTag = targetInst$jscomp$0.return; null !== nodeTag; ) {
                var grandTag = nodeTag.tag;
                if (3 === grandTag || 4 === grandTag) {
                  if (grandTag = nodeTag.stateNode.containerInfo, grandTag === targetContainer || 8 === grandTag.nodeType && grandTag.parentNode === targetContainer)
                    return;
                }
                nodeTag = nodeTag.return;
              }
            for (; null !== container2; ) {
              nodeTag = getClosestInstanceFromNode(container2);
              if (null === nodeTag) return;
              grandTag = nodeTag.tag;
              if (5 === grandTag || 6 === grandTag || 26 === grandTag || 27 === grandTag) {
                targetInst$jscomp$0 = ancestorInst = nodeTag;
                continue a;
              }
              container2 = container2.parentNode;
            }
          }
          targetInst$jscomp$0 = targetInst$jscomp$0.return;
        }
      batchedUpdates$1(function() {
        var targetInst = ancestorInst, nativeEventTarget = getEventTarget(nativeEvent), dispatchQueue = [];
        a: {
          var reactName = topLevelEventsToReactNames.get(domEventName);
          if (void 0 !== reactName) {
            var SyntheticEventCtor = SyntheticEvent, reactEventType = domEventName;
            switch (domEventName) {
              case "keypress":
                if (0 === getEventCharCode(nativeEvent)) break a;
              case "keydown":
              case "keyup":
                SyntheticEventCtor = SyntheticKeyboardEvent;
                break;
              case "focusin":
                reactEventType = "focus";
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "focusout":
                reactEventType = "blur";
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "beforeblur":
              case "afterblur":
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "click":
                if (2 === nativeEvent.button) break a;
              case "auxclick":
              case "dblclick":
              case "mousedown":
              case "mousemove":
              case "mouseup":
              case "mouseout":
              case "mouseover":
              case "contextmenu":
                SyntheticEventCtor = SyntheticMouseEvent;
                break;
              case "drag":
              case "dragend":
              case "dragenter":
              case "dragexit":
              case "dragleave":
              case "dragover":
              case "dragstart":
              case "drop":
                SyntheticEventCtor = SyntheticDragEvent;
                break;
              case "touchcancel":
              case "touchend":
              case "touchmove":
              case "touchstart":
                SyntheticEventCtor = SyntheticTouchEvent;
                break;
              case ANIMATION_END:
              case ANIMATION_ITERATION:
              case ANIMATION_START:
                SyntheticEventCtor = SyntheticAnimationEvent;
                break;
              case TRANSITION_END:
                SyntheticEventCtor = SyntheticTransitionEvent;
                break;
              case "scroll":
              case "scrollend":
                SyntheticEventCtor = SyntheticUIEvent;
                break;
              case "wheel":
                SyntheticEventCtor = SyntheticWheelEvent;
                break;
              case "copy":
              case "cut":
              case "paste":
                SyntheticEventCtor = SyntheticClipboardEvent;
                break;
              case "gotpointercapture":
              case "lostpointercapture":
              case "pointercancel":
              case "pointerdown":
              case "pointermove":
              case "pointerout":
              case "pointerover":
              case "pointerup":
                SyntheticEventCtor = SyntheticPointerEvent;
                break;
              case "toggle":
              case "beforetoggle":
                SyntheticEventCtor = SyntheticToggleEvent;
            }
            var inCapturePhase = 0 !== (eventSystemFlags & 4), accumulateTargetOnly = !inCapturePhase && ("scroll" === domEventName || "scrollend" === domEventName), reactEventName = inCapturePhase ? null !== reactName ? reactName + "Capture" : null : reactName;
            inCapturePhase = [];
            for (var instance = targetInst, lastHostComponent; null !== instance; ) {
              var _instance = instance;
              lastHostComponent = _instance.stateNode;
              _instance = _instance.tag;
              5 !== _instance && 26 !== _instance && 27 !== _instance || null === lastHostComponent || null === reactEventName || (_instance = getListener$1(instance, reactEventName), null != _instance && inCapturePhase.push(
                createDispatchListener(instance, _instance, lastHostComponent)
              ));
              if (accumulateTargetOnly) break;
              instance = instance.return;
            }
            0 < inCapturePhase.length && (reactName = new SyntheticEventCtor(
              reactName,
              reactEventType,
              null,
              nativeEvent,
              nativeEventTarget
            ), dispatchQueue.push({ event: reactName, listeners: inCapturePhase }));
          }
        }
        if (0 === (eventSystemFlags & 7)) {
          a: {
            reactName = "mouseover" === domEventName || "pointerover" === domEventName;
            SyntheticEventCtor = "mouseout" === domEventName || "pointerout" === domEventName;
            if (reactName && nativeEvent !== currentReplayingEvent && (reactEventType = nativeEvent.relatedTarget || nativeEvent.fromElement) && (getClosestInstanceFromNode(reactEventType) || reactEventType[internalContainerInstanceKey]))
              break a;
            if (SyntheticEventCtor || reactName) {
              reactName = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget : (reactName = nativeEventTarget.ownerDocument) ? reactName.defaultView || reactName.parentWindow : window;
              if (SyntheticEventCtor) {
                if (reactEventType = nativeEvent.relatedTarget || nativeEvent.toElement, SyntheticEventCtor = targetInst, reactEventType = reactEventType ? getClosestInstanceFromNode(reactEventType) : null, null !== reactEventType && (accumulateTargetOnly = getNearestMountedFiber(reactEventType), inCapturePhase = reactEventType.tag, reactEventType !== accumulateTargetOnly || 5 !== inCapturePhase && 27 !== inCapturePhase && 6 !== inCapturePhase))
                  reactEventType = null;
              } else SyntheticEventCtor = null, reactEventType = targetInst;
              if (SyntheticEventCtor !== reactEventType) {
                inCapturePhase = SyntheticMouseEvent;
                _instance = "onMouseLeave";
                reactEventName = "onMouseEnter";
                instance = "mouse";
                if ("pointerout" === domEventName || "pointerover" === domEventName)
                  inCapturePhase = SyntheticPointerEvent, _instance = "onPointerLeave", reactEventName = "onPointerEnter", instance = "pointer";
                accumulateTargetOnly = null == SyntheticEventCtor ? reactName : getNodeFromInstance(SyntheticEventCtor);
                lastHostComponent = null == reactEventType ? reactName : getNodeFromInstance(reactEventType);
                reactName = new inCapturePhase(
                  _instance,
                  instance + "leave",
                  SyntheticEventCtor,
                  nativeEvent,
                  nativeEventTarget
                );
                reactName.target = accumulateTargetOnly;
                reactName.relatedTarget = lastHostComponent;
                _instance = null;
                getClosestInstanceFromNode(nativeEventTarget) === targetInst && (inCapturePhase = new inCapturePhase(
                  reactEventName,
                  instance + "enter",
                  reactEventType,
                  nativeEvent,
                  nativeEventTarget
                ), inCapturePhase.target = lastHostComponent, inCapturePhase.relatedTarget = accumulateTargetOnly, _instance = inCapturePhase);
                accumulateTargetOnly = _instance;
                if (SyntheticEventCtor && reactEventType)
                  b: {
                    inCapturePhase = SyntheticEventCtor;
                    reactEventName = reactEventType;
                    instance = 0;
                    for (lastHostComponent = inCapturePhase; lastHostComponent; lastHostComponent = getParent(lastHostComponent))
                      instance++;
                    lastHostComponent = 0;
                    for (_instance = reactEventName; _instance; _instance = getParent(_instance))
                      lastHostComponent++;
                    for (; 0 < instance - lastHostComponent; )
                      inCapturePhase = getParent(inCapturePhase), instance--;
                    for (; 0 < lastHostComponent - instance; )
                      reactEventName = getParent(reactEventName), lastHostComponent--;
                    for (; instance--; ) {
                      if (inCapturePhase === reactEventName || null !== reactEventName && inCapturePhase === reactEventName.alternate)
                        break b;
                      inCapturePhase = getParent(inCapturePhase);
                      reactEventName = getParent(reactEventName);
                    }
                    inCapturePhase = null;
                  }
                else inCapturePhase = null;
                null !== SyntheticEventCtor && accumulateEnterLeaveListenersForEvent(
                  dispatchQueue,
                  reactName,
                  SyntheticEventCtor,
                  inCapturePhase,
                  false
                );
                null !== reactEventType && null !== accumulateTargetOnly && accumulateEnterLeaveListenersForEvent(
                  dispatchQueue,
                  accumulateTargetOnly,
                  reactEventType,
                  inCapturePhase,
                  true
                );
              }
            }
          }
          a: {
            reactName = targetInst ? getNodeFromInstance(targetInst) : window;
            SyntheticEventCtor = reactName.nodeName && reactName.nodeName.toLowerCase();
            if ("select" === SyntheticEventCtor || "input" === SyntheticEventCtor && "file" === reactName.type)
              var getTargetInstFunc = getTargetInstForChangeEvent;
            else if (isTextInputElement(reactName))
              if (isInputEventSupported)
                getTargetInstFunc = getTargetInstForInputOrChangeEvent;
              else {
                getTargetInstFunc = getTargetInstForInputEventPolyfill;
                var handleEventFunc = handleEventsForInputEventPolyfill;
              }
            else
              SyntheticEventCtor = reactName.nodeName, !SyntheticEventCtor || "input" !== SyntheticEventCtor.toLowerCase() || "checkbox" !== reactName.type && "radio" !== reactName.type ? targetInst && isCustomElement(targetInst.elementType) && (getTargetInstFunc = getTargetInstForChangeEvent) : getTargetInstFunc = getTargetInstForClickEvent;
            if (getTargetInstFunc && (getTargetInstFunc = getTargetInstFunc(domEventName, targetInst))) {
              createAndAccumulateChangeEvent(
                dispatchQueue,
                getTargetInstFunc,
                nativeEvent,
                nativeEventTarget
              );
              break a;
            }
            handleEventFunc && handleEventFunc(domEventName, reactName, targetInst);
            "focusout" === domEventName && targetInst && "number" === reactName.type && null != targetInst.memoizedProps.value && setDefaultValue(reactName, "number", reactName.value);
          }
          handleEventFunc = targetInst ? getNodeFromInstance(targetInst) : window;
          switch (domEventName) {
            case "focusin":
              if (isTextInputElement(handleEventFunc) || "true" === handleEventFunc.contentEditable)
                activeElement = handleEventFunc, activeElementInst = targetInst, lastSelection = null;
              break;
            case "focusout":
              lastSelection = activeElementInst = activeElement = null;
              break;
            case "mousedown":
              mouseDown = true;
              break;
            case "contextmenu":
            case "mouseup":
            case "dragend":
              mouseDown = false;
              constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
              break;
            case "selectionchange":
              if (skipSelectionChangeEvent) break;
            case "keydown":
            case "keyup":
              constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
          }
          var fallbackData;
          if (canUseCompositionEvent)
            b: {
              switch (domEventName) {
                case "compositionstart":
                  var eventType = "onCompositionStart";
                  break b;
                case "compositionend":
                  eventType = "onCompositionEnd";
                  break b;
                case "compositionupdate":
                  eventType = "onCompositionUpdate";
                  break b;
              }
              eventType = void 0;
            }
          else
            isComposing ? isFallbackCompositionEnd(domEventName, nativeEvent) && (eventType = "onCompositionEnd") : "keydown" === domEventName && 229 === nativeEvent.keyCode && (eventType = "onCompositionStart");
          eventType && (useFallbackCompositionData && "ko" !== nativeEvent.locale && (isComposing || "onCompositionStart" !== eventType ? "onCompositionEnd" === eventType && isComposing && (fallbackData = getData()) : (root$2 = nativeEventTarget, startText = "value" in root$2 ? root$2.value : root$2.textContent, isComposing = true)), handleEventFunc = accumulateTwoPhaseListeners(targetInst, eventType), 0 < handleEventFunc.length && (eventType = new SyntheticCompositionEvent(
            eventType,
            domEventName,
            null,
            nativeEvent,
            nativeEventTarget
          ), dispatchQueue.push({ event: eventType, listeners: handleEventFunc }), fallbackData ? eventType.data = fallbackData : (fallbackData = getDataFromCustomEvent(nativeEvent), null !== fallbackData && (eventType.data = fallbackData))));
          if (fallbackData = canUseTextInputEvent ? getNativeBeforeInputChars(domEventName, nativeEvent) : getFallbackBeforeInputChars(domEventName, nativeEvent))
            eventType = accumulateTwoPhaseListeners(targetInst, "onBeforeInput"), 0 < eventType.length && (handleEventFunc = new SyntheticCompositionEvent(
              "onBeforeInput",
              "beforeinput",
              null,
              nativeEvent,
              nativeEventTarget
            ), dispatchQueue.push({
              event: handleEventFunc,
              listeners: eventType
            }), handleEventFunc.data = fallbackData);
          extractEvents$1(
            dispatchQueue,
            domEventName,
            targetInst,
            nativeEvent,
            nativeEventTarget
          );
        }
        processDispatchQueue(dispatchQueue, eventSystemFlags);
      });
    }
    function createDispatchListener(instance, listener, currentTarget) {
      return {
        instance,
        listener,
        currentTarget
      };
    }
    function accumulateTwoPhaseListeners(targetFiber, reactName) {
      for (var captureName = reactName + "Capture", listeners = []; null !== targetFiber; ) {
        var _instance2 = targetFiber, stateNode = _instance2.stateNode;
        _instance2 = _instance2.tag;
        5 !== _instance2 && 26 !== _instance2 && 27 !== _instance2 || null === stateNode || (_instance2 = getListener$1(targetFiber, captureName), null != _instance2 && listeners.unshift(
          createDispatchListener(targetFiber, _instance2, stateNode)
        ), _instance2 = getListener$1(targetFiber, reactName), null != _instance2 && listeners.push(
          createDispatchListener(targetFiber, _instance2, stateNode)
        ));
        targetFiber = targetFiber.return;
      }
      return listeners;
    }
    function getParent(inst) {
      if (null === inst) return null;
      do
        inst = inst.return;
      while (inst && 5 !== inst.tag && 27 !== inst.tag);
      return inst ? inst : null;
    }
    function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target2, common, inCapturePhase) {
      for (var registrationName = event._reactName, listeners = []; null !== target2 && target2 !== common; ) {
        var _instance3 = target2, alternate = _instance3.alternate, stateNode = _instance3.stateNode;
        _instance3 = _instance3.tag;
        if (null !== alternate && alternate === common) break;
        5 !== _instance3 && 26 !== _instance3 && 27 !== _instance3 || null === stateNode || (alternate = stateNode, inCapturePhase ? (stateNode = getListener$1(target2, registrationName), null != stateNode && listeners.unshift(
          createDispatchListener(target2, stateNode, alternate)
        )) : inCapturePhase || (stateNode = getListener$1(target2, registrationName), null != stateNode && listeners.push(
          createDispatchListener(target2, stateNode, alternate)
        )));
        target2 = target2.return;
      }
      0 !== listeners.length && dispatchQueue.push({ event, listeners });
    }
    var NORMALIZE_NEWLINES_REGEX = /\r\n?/g, NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
    function normalizeMarkupForTextOrAttribute(markup) {
      return ("string" === typeof markup ? markup : "" + markup).replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
    }
    function checkForUnmatchedText(serverText, clientText) {
      clientText = normalizeMarkupForTextOrAttribute(clientText);
      return normalizeMarkupForTextOrAttribute(serverText) === clientText ? true : false;
    }
    function noop$1() {
    }
    function setProp(domElement, tag, key2, value2, props, prevValue) {
      switch (key2) {
        case "children":
          "string" === typeof value2 ? "body" === tag || "textarea" === tag && "" === value2 || setTextContent(domElement, value2) : ("number" === typeof value2 || "bigint" === typeof value2) && "body" !== tag && setTextContent(domElement, "" + value2);
          break;
        case "className":
          setValueForKnownAttribute(domElement, "class", value2);
          break;
        case "tabIndex":
          setValueForKnownAttribute(domElement, "tabindex", value2);
          break;
        case "dir":
        case "role":
        case "viewBox":
        case "width":
        case "height":
          setValueForKnownAttribute(domElement, key2, value2);
          break;
        case "style":
          setValueForStyles(domElement, value2, prevValue);
          break;
        case "data":
          if ("object" !== tag) {
            setValueForKnownAttribute(domElement, "data", value2);
            break;
          }
        case "src":
        case "href":
          if ("" === value2 && ("a" !== tag || "href" !== key2)) {
            domElement.removeAttribute(key2);
            break;
          }
          if (null == value2 || "function" === typeof value2 || "symbol" === typeof value2 || "boolean" === typeof value2) {
            domElement.removeAttribute(key2);
            break;
          }
          value2 = sanitizeURL("" + value2);
          domElement.setAttribute(key2, value2);
          break;
        case "action":
        case "formAction":
          if ("function" === typeof value2) {
            domElement.setAttribute(
              key2,
              "javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
            );
            break;
          } else
            "function" === typeof prevValue && ("formAction" === key2 ? ("input" !== tag && setProp(domElement, tag, "name", props.name, props, null), setProp(
              domElement,
              tag,
              "formEncType",
              props.formEncType,
              props,
              null
            ), setProp(
              domElement,
              tag,
              "formMethod",
              props.formMethod,
              props,
              null
            ), setProp(
              domElement,
              tag,
              "formTarget",
              props.formTarget,
              props,
              null
            )) : (setProp(domElement, tag, "encType", props.encType, props, null), setProp(domElement, tag, "method", props.method, props, null), setProp(domElement, tag, "target", props.target, props, null)));
          if (null == value2 || "symbol" === typeof value2 || "boolean" === typeof value2) {
            domElement.removeAttribute(key2);
            break;
          }
          value2 = sanitizeURL("" + value2);
          domElement.setAttribute(key2, value2);
          break;
        case "onClick":
          null != value2 && (domElement.onclick = noop$1);
          break;
        case "onScroll":
          null != value2 && listenToNonDelegatedEvent("scroll", domElement);
          break;
        case "onScrollEnd":
          null != value2 && listenToNonDelegatedEvent("scrollend", domElement);
          break;
        case "dangerouslySetInnerHTML":
          if (null != value2) {
            if ("object" !== typeof value2 || !("__html" in value2))
              throw Error(formatProdErrorMessage(61));
            key2 = value2.__html;
            if (null != key2) {
              if (null != props.children) throw Error(formatProdErrorMessage(60));
              domElement.innerHTML = key2;
            }
          }
          break;
        case "multiple":
          domElement.multiple = value2 && "function" !== typeof value2 && "symbol" !== typeof value2;
          break;
        case "muted":
          domElement.muted = value2 && "function" !== typeof value2 && "symbol" !== typeof value2;
          break;
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "ref":
          break;
        case "autoFocus":
          break;
        case "xlinkHref":
          if (null == value2 || "function" === typeof value2 || "boolean" === typeof value2 || "symbol" === typeof value2) {
            domElement.removeAttribute("xlink:href");
            break;
          }
          key2 = sanitizeURL("" + value2);
          domElement.setAttributeNS(
            "http://www.w3.org/1999/xlink",
            "xlink:href",
            key2
          );
          break;
        case "contentEditable":
        case "spellCheck":
        case "draggable":
        case "value":
        case "autoReverse":
        case "externalResourcesRequired":
        case "focusable":
        case "preserveAlpha":
          null != value2 && "function" !== typeof value2 && "symbol" !== typeof value2 ? domElement.setAttribute(key2, "" + value2) : domElement.removeAttribute(key2);
          break;
        case "inert":
        case "allowFullScreen":
        case "async":
        case "autoPlay":
        case "controls":
        case "default":
        case "defer":
        case "disabled":
        case "disablePictureInPicture":
        case "disableRemotePlayback":
        case "formNoValidate":
        case "hidden":
        case "loop":
        case "noModule":
        case "noValidate":
        case "open":
        case "playsInline":
        case "readOnly":
        case "required":
        case "reversed":
        case "scoped":
        case "seamless":
        case "itemScope":
          value2 && "function" !== typeof value2 && "symbol" !== typeof value2 ? domElement.setAttribute(key2, "") : domElement.removeAttribute(key2);
          break;
        case "capture":
        case "download":
          true === value2 ? domElement.setAttribute(key2, "") : false !== value2 && null != value2 && "function" !== typeof value2 && "symbol" !== typeof value2 ? domElement.setAttribute(key2, value2) : domElement.removeAttribute(key2);
          break;
        case "cols":
        case "rows":
        case "size":
        case "span":
          null != value2 && "function" !== typeof value2 && "symbol" !== typeof value2 && !isNaN(value2) && 1 <= value2 ? domElement.setAttribute(key2, value2) : domElement.removeAttribute(key2);
          break;
        case "rowSpan":
        case "start":
          null == value2 || "function" === typeof value2 || "symbol" === typeof value2 || isNaN(value2) ? domElement.removeAttribute(key2) : domElement.setAttribute(key2, value2);
          break;
        case "popover":
          listenToNonDelegatedEvent("beforetoggle", domElement);
          listenToNonDelegatedEvent("toggle", domElement);
          setValueForAttribute(domElement, "popover", value2);
          break;
        case "xlinkActuate":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/1999/xlink",
            "xlink:actuate",
            value2
          );
          break;
        case "xlinkArcrole":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/1999/xlink",
            "xlink:arcrole",
            value2
          );
          break;
        case "xlinkRole":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/1999/xlink",
            "xlink:role",
            value2
          );
          break;
        case "xlinkShow":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/1999/xlink",
            "xlink:show",
            value2
          );
          break;
        case "xlinkTitle":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/1999/xlink",
            "xlink:title",
            value2
          );
          break;
        case "xlinkType":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/1999/xlink",
            "xlink:type",
            value2
          );
          break;
        case "xmlBase":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/XML/1998/namespace",
            "xml:base",
            value2
          );
          break;
        case "xmlLang":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/XML/1998/namespace",
            "xml:lang",
            value2
          );
          break;
        case "xmlSpace":
          setValueForNamespacedAttribute(
            domElement,
            "http://www.w3.org/XML/1998/namespace",
            "xml:space",
            value2
          );
          break;
        case "is":
          setValueForAttribute(domElement, "is", value2);
          break;
        case "innerText":
        case "textContent":
          break;
        default:
          if (!(2 < key2.length) || "o" !== key2[0] && "O" !== key2[0] || "n" !== key2[1] && "N" !== key2[1])
            key2 = aliases.get(key2) || key2, setValueForAttribute(domElement, key2, value2);
      }
    }
    function setPropOnCustomElement(domElement, tag, key2, value2, props, prevValue) {
      switch (key2) {
        case "style":
          setValueForStyles(domElement, value2, prevValue);
          break;
        case "dangerouslySetInnerHTML":
          if (null != value2) {
            if ("object" !== typeof value2 || !("__html" in value2))
              throw Error(formatProdErrorMessage(61));
            key2 = value2.__html;
            if (null != key2) {
              if (null != props.children) throw Error(formatProdErrorMessage(60));
              domElement.innerHTML = key2;
            }
          }
          break;
        case "children":
          "string" === typeof value2 ? setTextContent(domElement, value2) : ("number" === typeof value2 || "bigint" === typeof value2) && setTextContent(domElement, "" + value2);
          break;
        case "onScroll":
          null != value2 && listenToNonDelegatedEvent("scroll", domElement);
          break;
        case "onScrollEnd":
          null != value2 && listenToNonDelegatedEvent("scrollend", domElement);
          break;
        case "onClick":
          null != value2 && (domElement.onclick = noop$1);
          break;
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "innerHTML":
        case "ref":
          break;
        case "innerText":
        case "textContent":
          break;
        default:
          if (!registrationNameDependencies.hasOwnProperty(key2))
            a: {
              if ("o" === key2[0] && "n" === key2[1] && (props = key2.endsWith("Capture"), tag = key2.slice(2, props ? key2.length - 7 : void 0), prevValue = domElement[internalPropsKey] || null, prevValue = null != prevValue ? prevValue[key2] : null, "function" === typeof prevValue && domElement.removeEventListener(tag, prevValue, props), "function" === typeof value2)) {
                "function" !== typeof prevValue && null !== prevValue && (key2 in domElement ? domElement[key2] = null : domElement.hasAttribute(key2) && domElement.removeAttribute(key2));
                domElement.addEventListener(tag, value2, props);
                break a;
              }
              key2 in domElement ? domElement[key2] = value2 : true === value2 ? domElement.setAttribute(key2, "") : setValueForAttribute(domElement, key2, value2);
            }
      }
    }
    function setInitialProperties(domElement, tag, props) {
      switch (tag) {
        case "div":
        case "span":
        case "svg":
        case "path":
        case "a":
        case "g":
        case "p":
        case "li":
          break;
        case "img":
          listenToNonDelegatedEvent("error", domElement);
          listenToNonDelegatedEvent("load", domElement);
          var hasSrc = false, hasSrcSet = false, propKey;
          for (propKey in props)
            if (props.hasOwnProperty(propKey)) {
              var propValue = props[propKey];
              if (null != propValue)
                switch (propKey) {
                  case "src":
                    hasSrc = true;
                    break;
                  case "srcSet":
                    hasSrcSet = true;
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(formatProdErrorMessage(137, tag));
                  default:
                    setProp(domElement, tag, propKey, propValue, props, null);
                }
            }
          hasSrcSet && setProp(domElement, tag, "srcSet", props.srcSet, props, null);
          hasSrc && setProp(domElement, tag, "src", props.src, props, null);
          return;
        case "input":
          listenToNonDelegatedEvent("invalid", domElement);
          var defaultValue = propKey = propValue = hasSrcSet = null, checked = null, defaultChecked = null;
          for (hasSrc in props)
            if (props.hasOwnProperty(hasSrc)) {
              var propValue$186 = props[hasSrc];
              if (null != propValue$186)
                switch (hasSrc) {
                  case "name":
                    hasSrcSet = propValue$186;
                    break;
                  case "type":
                    propValue = propValue$186;
                    break;
                  case "checked":
                    checked = propValue$186;
                    break;
                  case "defaultChecked":
                    defaultChecked = propValue$186;
                    break;
                  case "value":
                    propKey = propValue$186;
                    break;
                  case "defaultValue":
                    defaultValue = propValue$186;
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    if (null != propValue$186)
                      throw Error(formatProdErrorMessage(137, tag));
                    break;
                  default:
                    setProp(domElement, tag, hasSrc, propValue$186, props, null);
                }
            }
          initInput(
            domElement,
            propKey,
            defaultValue,
            checked,
            defaultChecked,
            propValue,
            hasSrcSet,
            false
          );
          track(domElement);
          return;
        case "select":
          listenToNonDelegatedEvent("invalid", domElement);
          hasSrc = propValue = propKey = null;
          for (hasSrcSet in props)
            if (props.hasOwnProperty(hasSrcSet) && (defaultValue = props[hasSrcSet], null != defaultValue))
              switch (hasSrcSet) {
                case "value":
                  propKey = defaultValue;
                  break;
                case "defaultValue":
                  propValue = defaultValue;
                  break;
                case "multiple":
                  hasSrc = defaultValue;
                default:
                  setProp(domElement, tag, hasSrcSet, defaultValue, props, null);
              }
          tag = propKey;
          props = propValue;
          domElement.multiple = !!hasSrc;
          null != tag ? updateOptions(domElement, !!hasSrc, tag, false) : null != props && updateOptions(domElement, !!hasSrc, props, true);
          return;
        case "textarea":
          listenToNonDelegatedEvent("invalid", domElement);
          propKey = hasSrcSet = hasSrc = null;
          for (propValue in props)
            if (props.hasOwnProperty(propValue) && (defaultValue = props[propValue], null != defaultValue))
              switch (propValue) {
                case "value":
                  hasSrc = defaultValue;
                  break;
                case "defaultValue":
                  hasSrcSet = defaultValue;
                  break;
                case "children":
                  propKey = defaultValue;
                  break;
                case "dangerouslySetInnerHTML":
                  if (null != defaultValue) throw Error(formatProdErrorMessage(91));
                  break;
                default:
                  setProp(domElement, tag, propValue, defaultValue, props, null);
              }
          initTextarea(domElement, hasSrc, hasSrcSet, propKey);
          track(domElement);
          return;
        case "option":
          for (checked in props)
            if (props.hasOwnProperty(checked) && (hasSrc = props[checked], null != hasSrc))
              switch (checked) {
                case "selected":
                  domElement.selected = hasSrc && "function" !== typeof hasSrc && "symbol" !== typeof hasSrc;
                  break;
                default:
                  setProp(domElement, tag, checked, hasSrc, props, null);
              }
          return;
        case "dialog":
          listenToNonDelegatedEvent("cancel", domElement);
          listenToNonDelegatedEvent("close", domElement);
          break;
        case "iframe":
        case "object":
          listenToNonDelegatedEvent("load", domElement);
          break;
        case "video":
        case "audio":
          for (hasSrc = 0; hasSrc < mediaEventTypes.length; hasSrc++)
            listenToNonDelegatedEvent(mediaEventTypes[hasSrc], domElement);
          break;
        case "image":
          listenToNonDelegatedEvent("error", domElement);
          listenToNonDelegatedEvent("load", domElement);
          break;
        case "details":
          listenToNonDelegatedEvent("toggle", domElement);
          break;
        case "embed":
        case "source":
        case "link":
          listenToNonDelegatedEvent("error", domElement), listenToNonDelegatedEvent("load", domElement);
        case "area":
        case "base":
        case "br":
        case "col":
        case "hr":
        case "keygen":
        case "meta":
        case "param":
        case "track":
        case "wbr":
        case "menuitem":
          for (defaultChecked in props)
            if (props.hasOwnProperty(defaultChecked) && (hasSrc = props[defaultChecked], null != hasSrc))
              switch (defaultChecked) {
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(formatProdErrorMessage(137, tag));
                default:
                  setProp(domElement, tag, defaultChecked, hasSrc, props, null);
              }
          return;
        default:
          if (isCustomElement(tag)) {
            for (propValue$186 in props)
              props.hasOwnProperty(propValue$186) && (hasSrc = props[propValue$186], void 0 !== hasSrc && setPropOnCustomElement(
                domElement,
                tag,
                propValue$186,
                hasSrc,
                props,
                void 0
              ));
            return;
          }
      }
      for (defaultValue in props)
        props.hasOwnProperty(defaultValue) && (hasSrc = props[defaultValue], null != hasSrc && setProp(domElement, tag, defaultValue, hasSrc, props, null));
    }
    function updateProperties(domElement, tag, lastProps, nextProps) {
      switch (tag) {
        case "div":
        case "span":
        case "svg":
        case "path":
        case "a":
        case "g":
        case "p":
        case "li":
          break;
        case "input":
          var name2 = null, type = null, value2 = null, defaultValue = null, lastDefaultValue = null, checked = null, defaultChecked = null;
          for (propKey in lastProps) {
            var lastProp = lastProps[propKey];
            if (lastProps.hasOwnProperty(propKey) && null != lastProp)
              switch (propKey) {
                case "checked":
                  break;
                case "value":
                  break;
                case "defaultValue":
                  lastDefaultValue = lastProp;
                default:
                  nextProps.hasOwnProperty(propKey) || setProp(domElement, tag, propKey, null, nextProps, lastProp);
              }
          }
          for (var propKey$203 in nextProps) {
            var propKey = nextProps[propKey$203];
            lastProp = lastProps[propKey$203];
            if (nextProps.hasOwnProperty(propKey$203) && (null != propKey || null != lastProp))
              switch (propKey$203) {
                case "type":
                  type = propKey;
                  break;
                case "name":
                  name2 = propKey;
                  break;
                case "checked":
                  checked = propKey;
                  break;
                case "defaultChecked":
                  defaultChecked = propKey;
                  break;
                case "value":
                  value2 = propKey;
                  break;
                case "defaultValue":
                  defaultValue = propKey;
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  if (null != propKey)
                    throw Error(formatProdErrorMessage(137, tag));
                  break;
                default:
                  propKey !== lastProp && setProp(
                    domElement,
                    tag,
                    propKey$203,
                    propKey,
                    nextProps,
                    lastProp
                  );
              }
          }
          updateInput(
            domElement,
            value2,
            defaultValue,
            lastDefaultValue,
            checked,
            defaultChecked,
            type,
            name2
          );
          return;
        case "select":
          propKey = value2 = defaultValue = propKey$203 = null;
          for (type in lastProps)
            if (lastDefaultValue = lastProps[type], lastProps.hasOwnProperty(type) && null != lastDefaultValue)
              switch (type) {
                case "value":
                  break;
                case "multiple":
                  propKey = lastDefaultValue;
                default:
                  nextProps.hasOwnProperty(type) || setProp(
                    domElement,
                    tag,
                    type,
                    null,
                    nextProps,
                    lastDefaultValue
                  );
              }
          for (name2 in nextProps)
            if (type = nextProps[name2], lastDefaultValue = lastProps[name2], nextProps.hasOwnProperty(name2) && (null != type || null != lastDefaultValue))
              switch (name2) {
                case "value":
                  propKey$203 = type;
                  break;
                case "defaultValue":
                  defaultValue = type;
                  break;
                case "multiple":
                  value2 = type;
                default:
                  type !== lastDefaultValue && setProp(
                    domElement,
                    tag,
                    name2,
                    type,
                    nextProps,
                    lastDefaultValue
                  );
              }
          tag = defaultValue;
          lastProps = value2;
          nextProps = propKey;
          null != propKey$203 ? updateOptions(domElement, !!lastProps, propKey$203, false) : !!nextProps !== !!lastProps && (null != tag ? updateOptions(domElement, !!lastProps, tag, true) : updateOptions(domElement, !!lastProps, lastProps ? [] : "", false));
          return;
        case "textarea":
          propKey = propKey$203 = null;
          for (defaultValue in lastProps)
            if (name2 = lastProps[defaultValue], lastProps.hasOwnProperty(defaultValue) && null != name2 && !nextProps.hasOwnProperty(defaultValue))
              switch (defaultValue) {
                case "value":
                  break;
                case "children":
                  break;
                default:
                  setProp(domElement, tag, defaultValue, null, nextProps, name2);
              }
          for (value2 in nextProps)
            if (name2 = nextProps[value2], type = lastProps[value2], nextProps.hasOwnProperty(value2) && (null != name2 || null != type))
              switch (value2) {
                case "value":
                  propKey$203 = name2;
                  break;
                case "defaultValue":
                  propKey = name2;
                  break;
                case "children":
                  break;
                case "dangerouslySetInnerHTML":
                  if (null != name2) throw Error(formatProdErrorMessage(91));
                  break;
                default:
                  name2 !== type && setProp(domElement, tag, value2, name2, nextProps, type);
              }
          updateTextarea(domElement, propKey$203, propKey);
          return;
        case "option":
          for (var propKey$219 in lastProps)
            if (propKey$203 = lastProps[propKey$219], lastProps.hasOwnProperty(propKey$219) && null != propKey$203 && !nextProps.hasOwnProperty(propKey$219))
              switch (propKey$219) {
                case "selected":
                  domElement.selected = false;
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    propKey$219,
                    null,
                    nextProps,
                    propKey$203
                  );
              }
          for (lastDefaultValue in nextProps)
            if (propKey$203 = nextProps[lastDefaultValue], propKey = lastProps[lastDefaultValue], nextProps.hasOwnProperty(lastDefaultValue) && propKey$203 !== propKey && (null != propKey$203 || null != propKey))
              switch (lastDefaultValue) {
                case "selected":
                  domElement.selected = propKey$203 && "function" !== typeof propKey$203 && "symbol" !== typeof propKey$203;
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    lastDefaultValue,
                    propKey$203,
                    nextProps,
                    propKey
                  );
              }
          return;
        case "img":
        case "link":
        case "area":
        case "base":
        case "br":
        case "col":
        case "embed":
        case "hr":
        case "keygen":
        case "meta":
        case "param":
        case "source":
        case "track":
        case "wbr":
        case "menuitem":
          for (var propKey$224 in lastProps)
            propKey$203 = lastProps[propKey$224], lastProps.hasOwnProperty(propKey$224) && null != propKey$203 && !nextProps.hasOwnProperty(propKey$224) && setProp(domElement, tag, propKey$224, null, nextProps, propKey$203);
          for (checked in nextProps)
            if (propKey$203 = nextProps[checked], propKey = lastProps[checked], nextProps.hasOwnProperty(checked) && propKey$203 !== propKey && (null != propKey$203 || null != propKey))
              switch (checked) {
                case "children":
                case "dangerouslySetInnerHTML":
                  if (null != propKey$203)
                    throw Error(formatProdErrorMessage(137, tag));
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    checked,
                    propKey$203,
                    nextProps,
                    propKey
                  );
              }
          return;
        default:
          if (isCustomElement(tag)) {
            for (var propKey$229 in lastProps)
              propKey$203 = lastProps[propKey$229], lastProps.hasOwnProperty(propKey$229) && void 0 !== propKey$203 && !nextProps.hasOwnProperty(propKey$229) && setPropOnCustomElement(
                domElement,
                tag,
                propKey$229,
                void 0,
                nextProps,
                propKey$203
              );
            for (defaultChecked in nextProps)
              propKey$203 = nextProps[defaultChecked], propKey = lastProps[defaultChecked], !nextProps.hasOwnProperty(defaultChecked) || propKey$203 === propKey || void 0 === propKey$203 && void 0 === propKey || setPropOnCustomElement(
                domElement,
                tag,
                defaultChecked,
                propKey$203,
                nextProps,
                propKey
              );
            return;
          }
      }
      for (var propKey$234 in lastProps)
        propKey$203 = lastProps[propKey$234], lastProps.hasOwnProperty(propKey$234) && null != propKey$203 && !nextProps.hasOwnProperty(propKey$234) && setProp(domElement, tag, propKey$234, null, nextProps, propKey$203);
      for (lastProp in nextProps)
        propKey$203 = nextProps[lastProp], propKey = lastProps[lastProp], !nextProps.hasOwnProperty(lastProp) || propKey$203 === propKey || null == propKey$203 && null == propKey || setProp(domElement, tag, lastProp, propKey$203, nextProps, propKey);
    }
    var eventsEnabled = null, selectionInformation = null;
    function getOwnerDocumentFromRootContainer(rootContainerElement) {
      return 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
    }
    function getOwnHostContext(namespaceURI) {
      switch (namespaceURI) {
        case "http://www.w3.org/2000/svg":
          return 1;
        case "http://www.w3.org/1998/Math/MathML":
          return 2;
        default:
          return 0;
      }
    }
    function getChildHostContextProd(parentNamespace, type) {
      if (0 === parentNamespace)
        switch (type) {
          case "svg":
            return 1;
          case "math":
            return 2;
          default:
            return 0;
        }
      return 1 === parentNamespace && "foreignObject" === type ? 0 : parentNamespace;
    }
    function shouldSetTextContent(type, props) {
      return "textarea" === type || "noscript" === type || "string" === typeof props.children || "number" === typeof props.children || "bigint" === typeof props.children || "object" === typeof props.dangerouslySetInnerHTML && null !== props.dangerouslySetInnerHTML && null != props.dangerouslySetInnerHTML.__html;
    }
    var currentPopstateTransitionEvent = null;
    function shouldAttemptEagerTransition() {
      var event = window.event;
      if (event && "popstate" === event.type) {
        if (event === currentPopstateTransitionEvent) return false;
        currentPopstateTransitionEvent = event;
        return true;
      }
      currentPopstateTransitionEvent = null;
      return false;
    }
    var scheduleTimeout = "function" === typeof setTimeout ? setTimeout : void 0, cancelTimeout = "function" === typeof clearTimeout ? clearTimeout : void 0, localPromise = "function" === typeof Promise ? Promise : void 0, scheduleMicrotask = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof localPromise ? function(callback) {
      return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
    } : scheduleTimeout;
    function handleErrorInNextTick(error2) {
      setTimeout(function() {
        throw error2;
      });
    }
    function clearSuspenseBoundary(parentInstance, suspenseInstance) {
      var node2 = suspenseInstance, depth = 0;
      do {
        var nextNode = node2.nextSibling;
        parentInstance.removeChild(node2);
        if (nextNode && 8 === nextNode.nodeType)
          if (node2 = nextNode.data, "/$" === node2) {
            if (0 === depth) {
              parentInstance.removeChild(nextNode);
              retryIfBlockedOn(suspenseInstance);
              return;
            }
            depth--;
          } else "$" !== node2 && "$?" !== node2 && "$!" !== node2 || depth++;
        node2 = nextNode;
      } while (node2);
      retryIfBlockedOn(suspenseInstance);
    }
    function clearContainerSparingly(container2) {
      var nextNode = container2.firstChild;
      nextNode && 10 === nextNode.nodeType && (nextNode = nextNode.nextSibling);
      for (; nextNode; ) {
        var node2 = nextNode;
        nextNode = nextNode.nextSibling;
        switch (node2.nodeName) {
          case "HTML":
          case "HEAD":
          case "BODY":
            clearContainerSparingly(node2);
            detachDeletedInstance(node2);
            continue;
          case "SCRIPT":
          case "STYLE":
            continue;
          case "LINK":
            if ("stylesheet" === node2.rel.toLowerCase()) continue;
        }
        container2.removeChild(node2);
      }
    }
    function canHydrateInstance(instance, type, props, inRootOrSingleton) {
      for (; 1 === instance.nodeType; ) {
        var anyProps = props;
        if (instance.nodeName.toLowerCase() !== type.toLowerCase()) {
          if (!inRootOrSingleton && ("INPUT" !== instance.nodeName || "hidden" !== instance.type))
            break;
        } else if (!inRootOrSingleton)
          if ("input" === type && "hidden" === instance.type) {
            var name2 = null == anyProps.name ? null : "" + anyProps.name;
            if ("hidden" === anyProps.type && instance.getAttribute("name") === name2)
              return instance;
          } else return instance;
        else if (!instance[internalHoistableMarker])
          switch (type) {
            case "meta":
              if (!instance.hasAttribute("itemprop")) break;
              return instance;
            case "link":
              name2 = instance.getAttribute("rel");
              if ("stylesheet" === name2 && instance.hasAttribute("data-precedence"))
                break;
              else if (name2 !== anyProps.rel || instance.getAttribute("href") !== (null == anyProps.href ? null : anyProps.href) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin) || instance.getAttribute("title") !== (null == anyProps.title ? null : anyProps.title))
                break;
              return instance;
            case "style":
              if (instance.hasAttribute("data-precedence")) break;
              return instance;
            case "script":
              name2 = instance.getAttribute("src");
              if ((name2 !== (null == anyProps.src ? null : anyProps.src) || instance.getAttribute("type") !== (null == anyProps.type ? null : anyProps.type) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin)) && name2 && instance.hasAttribute("async") && !instance.hasAttribute("itemprop"))
                break;
              return instance;
            default:
              return instance;
          }
        instance = getNextHydratable(instance.nextSibling);
        if (null === instance) break;
      }
      return null;
    }
    function canHydrateTextInstance(instance, text2, inRootOrSingleton) {
      if ("" === text2) return null;
      for (; 3 !== instance.nodeType; ) {
        if ((1 !== instance.nodeType || "INPUT" !== instance.nodeName || "hidden" !== instance.type) && !inRootOrSingleton)
          return null;
        instance = getNextHydratable(instance.nextSibling);
        if (null === instance) return null;
      }
      return instance;
    }
    function getNextHydratable(node2) {
      for (; null != node2; node2 = node2.nextSibling) {
        var nodeType = node2.nodeType;
        if (1 === nodeType || 3 === nodeType) break;
        if (8 === nodeType) {
          nodeType = node2.data;
          if ("$" === nodeType || "$!" === nodeType || "$?" === nodeType || "F!" === nodeType || "F" === nodeType)
            break;
          if ("/$" === nodeType) return null;
        }
      }
      return node2;
    }
    function getParentSuspenseInstance(targetInstance) {
      targetInstance = targetInstance.previousSibling;
      for (var depth = 0; targetInstance; ) {
        if (8 === targetInstance.nodeType) {
          var data = targetInstance.data;
          if ("$" === data || "$!" === data || "$?" === data) {
            if (0 === depth) return targetInstance;
            depth--;
          } else "/$" === data && depth++;
        }
        targetInstance = targetInstance.previousSibling;
      }
      return null;
    }
    function resolveSingletonInstance(type, props, rootContainerInstance) {
      props = getOwnerDocumentFromRootContainer(rootContainerInstance);
      switch (type) {
        case "html":
          type = props.documentElement;
          if (!type) throw Error(formatProdErrorMessage(452));
          return type;
        case "head":
          type = props.head;
          if (!type) throw Error(formatProdErrorMessage(453));
          return type;
        case "body":
          type = props.body;
          if (!type) throw Error(formatProdErrorMessage(454));
          return type;
        default:
          throw Error(formatProdErrorMessage(451));
      }
    }
    var preloadPropsMap = /* @__PURE__ */ new Map(), preconnectsSet = /* @__PURE__ */ new Set();
    function getHoistableRoot(container2) {
      return "function" === typeof container2.getRootNode ? container2.getRootNode() : container2.ownerDocument;
    }
    var previousDispatcher = ReactDOMSharedInternals.d;
    ReactDOMSharedInternals.d = {
      f: flushSyncWork,
      r: requestFormReset,
      D: prefetchDNS,
      C: preconnect,
      L: preload,
      m: preloadModule,
      X: preinitScript,
      S: preinitStyle,
      M: preinitModuleScript
    };
    function flushSyncWork() {
      var previousWasRendering = previousDispatcher.f(), wasRendering = flushSyncWork$1();
      return previousWasRendering || wasRendering;
    }
    function requestFormReset(form) {
      var formInst = getInstanceFromNode(form);
      null !== formInst && 5 === formInst.tag && "form" === formInst.type ? requestFormReset$1(formInst) : previousDispatcher.r(form);
    }
    var globalDocument = "undefined" === typeof document ? null : document;
    function preconnectAs(rel, href, crossOrigin) {
      var ownerDocument = globalDocument;
      if (ownerDocument && "string" === typeof href && href) {
        var limitedEscapedHref = escapeSelectorAttributeValueInsideDoubleQuotes(href);
        limitedEscapedHref = 'link[rel="' + rel + '"][href="' + limitedEscapedHref + '"]';
        "string" === typeof crossOrigin && (limitedEscapedHref += '[crossorigin="' + crossOrigin + '"]');
        preconnectsSet.has(limitedEscapedHref) || (preconnectsSet.add(limitedEscapedHref), rel = { rel, crossOrigin, href }, null === ownerDocument.querySelector(limitedEscapedHref) && (href = ownerDocument.createElement("link"), setInitialProperties(href, "link", rel), markNodeAsHoistable(href), ownerDocument.head.appendChild(href)));
      }
    }
    function prefetchDNS(href) {
      previousDispatcher.D(href);
      preconnectAs("dns-prefetch", href, null);
    }
    function preconnect(href, crossOrigin) {
      previousDispatcher.C(href, crossOrigin);
      preconnectAs("preconnect", href, crossOrigin);
    }
    function preload(href, as, options2) {
      previousDispatcher.L(href, as, options2);
      var ownerDocument = globalDocument;
      if (ownerDocument && href && as) {
        var preloadSelector = 'link[rel="preload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"]';
        "image" === as ? options2 && options2.imageSrcSet ? (preloadSelector += '[imagesrcset="' + escapeSelectorAttributeValueInsideDoubleQuotes(
          options2.imageSrcSet
        ) + '"]', "string" === typeof options2.imageSizes && (preloadSelector += '[imagesizes="' + escapeSelectorAttributeValueInsideDoubleQuotes(
          options2.imageSizes
        ) + '"]')) : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]' : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]';
        var key2 = preloadSelector;
        switch (as) {
          case "style":
            key2 = getStyleKey(href);
            break;
          case "script":
            key2 = getScriptKey(href);
        }
        preloadPropsMap.has(key2) || (href = assign$2(
          {
            rel: "preload",
            href: "image" === as && options2 && options2.imageSrcSet ? void 0 : href,
            as
          },
          options2
        ), preloadPropsMap.set(key2, href), null !== ownerDocument.querySelector(preloadSelector) || "style" === as && ownerDocument.querySelector(getStylesheetSelectorFromKey(key2)) || "script" === as && ownerDocument.querySelector(getScriptSelectorFromKey(key2)) || (as = ownerDocument.createElement("link"), setInitialProperties(as, "link", href), markNodeAsHoistable(as), ownerDocument.head.appendChild(as)));
      }
    }
    function preloadModule(href, options2) {
      previousDispatcher.m(href, options2);
      var ownerDocument = globalDocument;
      if (ownerDocument && href) {
        var as = options2 && "string" === typeof options2.as ? options2.as : "script", preloadSelector = 'link[rel="modulepreload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"][href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]', key2 = preloadSelector;
        switch (as) {
          case "audioworklet":
          case "paintworklet":
          case "serviceworker":
          case "sharedworker":
          case "worker":
          case "script":
            key2 = getScriptKey(href);
        }
        if (!preloadPropsMap.has(key2) && (href = assign$2({ rel: "modulepreload", href }, options2), preloadPropsMap.set(key2, href), null === ownerDocument.querySelector(preloadSelector))) {
          switch (as) {
            case "audioworklet":
            case "paintworklet":
            case "serviceworker":
            case "sharedworker":
            case "worker":
            case "script":
              if (ownerDocument.querySelector(getScriptSelectorFromKey(key2)))
                return;
          }
          as = ownerDocument.createElement("link");
          setInitialProperties(as, "link", href);
          markNodeAsHoistable(as);
          ownerDocument.head.appendChild(as);
        }
      }
    }
    function preinitStyle(href, precedence, options2) {
      previousDispatcher.S(href, precedence, options2);
      var ownerDocument = globalDocument;
      if (ownerDocument && href) {
        var styles2 = getResourcesFromRoot(ownerDocument).hoistableStyles, key2 = getStyleKey(href);
        precedence = precedence || "default";
        var resource = styles2.get(key2);
        if (!resource) {
          var state = { loading: 0, preload: null };
          if (resource = ownerDocument.querySelector(
            getStylesheetSelectorFromKey(key2)
          ))
            state.loading = 5;
          else {
            href = assign$2(
              { rel: "stylesheet", href, "data-precedence": precedence },
              options2
            );
            (options2 = preloadPropsMap.get(key2)) && adoptPreloadPropsForStylesheet(href, options2);
            var link2 = resource = ownerDocument.createElement("link");
            markNodeAsHoistable(link2);
            setInitialProperties(link2, "link", href);
            link2._p = new Promise(function(resolve, reject) {
              link2.onload = resolve;
              link2.onerror = reject;
            });
            link2.addEventListener("load", function() {
              state.loading |= 1;
            });
            link2.addEventListener("error", function() {
              state.loading |= 2;
            });
            state.loading |= 4;
            insertStylesheet(resource, precedence, ownerDocument);
          }
          resource = {
            type: "stylesheet",
            instance: resource,
            count: 1,
            state
          };
          styles2.set(key2, resource);
        }
      }
    }
    function preinitScript(src, options2) {
      previousDispatcher.X(src, options2);
      var ownerDocument = globalDocument;
      if (ownerDocument && src) {
        var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key2 = getScriptKey(src), resource = scripts.get(key2);
        resource || (resource = ownerDocument.querySelector(getScriptSelectorFromKey(key2)), resource || (src = assign$2({ src, async: true }, options2), (options2 = preloadPropsMap.get(key2)) && adoptPreloadPropsForScript(src, options2), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src), ownerDocument.head.appendChild(resource)), resource = {
          type: "script",
          instance: resource,
          count: 1,
          state: null
        }, scripts.set(key2, resource));
      }
    }
    function preinitModuleScript(src, options2) {
      previousDispatcher.M(src, options2);
      var ownerDocument = globalDocument;
      if (ownerDocument && src) {
        var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key2 = getScriptKey(src), resource = scripts.get(key2);
        resource || (resource = ownerDocument.querySelector(getScriptSelectorFromKey(key2)), resource || (src = assign$2({ src, async: true, type: "module" }, options2), (options2 = preloadPropsMap.get(key2)) && adoptPreloadPropsForScript(src, options2), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src), ownerDocument.head.appendChild(resource)), resource = {
          type: "script",
          instance: resource,
          count: 1,
          state: null
        }, scripts.set(key2, resource));
      }
    }
    function getResource(type, currentProps, pendingProps, currentResource) {
      var JSCompiler_inline_result = (JSCompiler_inline_result = rootInstanceStackCursor.current) ? getHoistableRoot(JSCompiler_inline_result) : null;
      if (!JSCompiler_inline_result) throw Error(formatProdErrorMessage(446));
      switch (type) {
        case "meta":
        case "title":
          return null;
        case "style":
          return "string" === typeof pendingProps.precedence && "string" === typeof pendingProps.href ? (currentProps = getStyleKey(pendingProps.href), pendingProps = getResourcesFromRoot(
            JSCompiler_inline_result
          ).hoistableStyles, currentResource = pendingProps.get(currentProps), currentResource || (currentResource = {
            type: "style",
            instance: null,
            count: 0,
            state: null
          }, pendingProps.set(currentProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
        case "link":
          if ("stylesheet" === pendingProps.rel && "string" === typeof pendingProps.href && "string" === typeof pendingProps.precedence) {
            type = getStyleKey(pendingProps.href);
            var styles$242 = getResourcesFromRoot(
              JSCompiler_inline_result
            ).hoistableStyles, resource$243 = styles$242.get(type);
            resource$243 || (JSCompiler_inline_result = JSCompiler_inline_result.ownerDocument || JSCompiler_inline_result, resource$243 = {
              type: "stylesheet",
              instance: null,
              count: 0,
              state: { loading: 0, preload: null }
            }, styles$242.set(type, resource$243), (styles$242 = JSCompiler_inline_result.querySelector(
              getStylesheetSelectorFromKey(type)
            )) && !styles$242._p && (resource$243.instance = styles$242, resource$243.state.loading = 5), preloadPropsMap.has(type) || (pendingProps = {
              rel: "preload",
              as: "style",
              href: pendingProps.href,
              crossOrigin: pendingProps.crossOrigin,
              integrity: pendingProps.integrity,
              media: pendingProps.media,
              hrefLang: pendingProps.hrefLang,
              referrerPolicy: pendingProps.referrerPolicy
            }, preloadPropsMap.set(type, pendingProps), styles$242 || preloadStylesheet(
              JSCompiler_inline_result,
              type,
              pendingProps,
              resource$243.state
            )));
            if (currentProps && null === currentResource)
              throw Error(formatProdErrorMessage(528, ""));
            return resource$243;
          }
          if (currentProps && null !== currentResource)
            throw Error(formatProdErrorMessage(529, ""));
          return null;
        case "script":
          return currentProps = pendingProps.async, pendingProps = pendingProps.src, "string" === typeof pendingProps && currentProps && "function" !== typeof currentProps && "symbol" !== typeof currentProps ? (currentProps = getScriptKey(pendingProps), pendingProps = getResourcesFromRoot(
            JSCompiler_inline_result
          ).hoistableScripts, currentResource = pendingProps.get(currentProps), currentResource || (currentResource = {
            type: "script",
            instance: null,
            count: 0,
            state: null
          }, pendingProps.set(currentProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
        default:
          throw Error(formatProdErrorMessage(444, type));
      }
    }
    function getStyleKey(href) {
      return 'href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"';
    }
    function getStylesheetSelectorFromKey(key2) {
      return 'link[rel="stylesheet"][' + key2 + "]";
    }
    function stylesheetPropsFromRawProps(rawProps) {
      return assign$2({}, rawProps, {
        "data-precedence": rawProps.precedence,
        precedence: null
      });
    }
    function preloadStylesheet(ownerDocument, key2, preloadProps, state) {
      ownerDocument.querySelector('link[rel="preload"][as="style"][' + key2 + "]") ? state.loading = 1 : (key2 = ownerDocument.createElement("link"), state.preload = key2, key2.addEventListener("load", function() {
        return state.loading |= 1;
      }), key2.addEventListener("error", function() {
        return state.loading |= 2;
      }), setInitialProperties(key2, "link", preloadProps), markNodeAsHoistable(key2), ownerDocument.head.appendChild(key2));
    }
    function getScriptKey(src) {
      return '[src="' + escapeSelectorAttributeValueInsideDoubleQuotes(src) + '"]';
    }
    function getScriptSelectorFromKey(key2) {
      return "script[async]" + key2;
    }
    function acquireResource(hoistableRoot, resource, props) {
      resource.count++;
      if (null === resource.instance)
        switch (resource.type) {
          case "style":
            var instance = hoistableRoot.querySelector(
              'style[data-href~="' + escapeSelectorAttributeValueInsideDoubleQuotes(props.href) + '"]'
            );
            if (instance)
              return resource.instance = instance, markNodeAsHoistable(instance), instance;
            var styleProps = assign$2({}, props, {
              "data-href": props.href,
              "data-precedence": props.precedence,
              href: null,
              precedence: null
            });
            instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement(
              "style"
            );
            markNodeAsHoistable(instance);
            setInitialProperties(instance, "style", styleProps);
            insertStylesheet(instance, props.precedence, hoistableRoot);
            return resource.instance = instance;
          case "stylesheet":
            styleProps = getStyleKey(props.href);
            var instance$248 = hoistableRoot.querySelector(
              getStylesheetSelectorFromKey(styleProps)
            );
            if (instance$248)
              return resource.state.loading |= 4, resource.instance = instance$248, markNodeAsHoistable(instance$248), instance$248;
            instance = stylesheetPropsFromRawProps(props);
            (styleProps = preloadPropsMap.get(styleProps)) && adoptPreloadPropsForStylesheet(instance, styleProps);
            instance$248 = (hoistableRoot.ownerDocument || hoistableRoot).createElement("link");
            markNodeAsHoistable(instance$248);
            var linkInstance = instance$248;
            linkInstance._p = new Promise(function(resolve, reject) {
              linkInstance.onload = resolve;
              linkInstance.onerror = reject;
            });
            setInitialProperties(instance$248, "link", instance);
            resource.state.loading |= 4;
            insertStylesheet(instance$248, props.precedence, hoistableRoot);
            return resource.instance = instance$248;
          case "script":
            instance$248 = getScriptKey(props.src);
            if (styleProps = hoistableRoot.querySelector(
              getScriptSelectorFromKey(instance$248)
            ))
              return resource.instance = styleProps, markNodeAsHoistable(styleProps), styleProps;
            instance = props;
            if (styleProps = preloadPropsMap.get(instance$248))
              instance = assign$2({}, props), adoptPreloadPropsForScript(instance, styleProps);
            hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
            styleProps = hoistableRoot.createElement("script");
            markNodeAsHoistable(styleProps);
            setInitialProperties(styleProps, "link", instance);
            hoistableRoot.head.appendChild(styleProps);
            return resource.instance = styleProps;
          case "void":
            return null;
          default:
            throw Error(formatProdErrorMessage(443, resource.type));
        }
      else
        "stylesheet" === resource.type && 0 === (resource.state.loading & 4) && (instance = resource.instance, resource.state.loading |= 4, insertStylesheet(instance, props.precedence, hoistableRoot));
      return resource.instance;
    }
    function insertStylesheet(instance, precedence, root2) {
      for (var nodes = root2.querySelectorAll(
        'link[rel="stylesheet"][data-precedence],style[data-precedence]'
      ), last = nodes.length ? nodes[nodes.length - 1] : null, prior = last, i2 = 0; i2 < nodes.length; i2++) {
        var node2 = nodes[i2];
        if (node2.dataset.precedence === precedence) prior = node2;
        else if (prior !== last) break;
      }
      prior ? prior.parentNode.insertBefore(instance, prior.nextSibling) : (precedence = 9 === root2.nodeType ? root2.head : root2, precedence.insertBefore(instance, precedence.firstChild));
    }
    function adoptPreloadPropsForStylesheet(stylesheetProps, preloadProps) {
      null == stylesheetProps.crossOrigin && (stylesheetProps.crossOrigin = preloadProps.crossOrigin);
      null == stylesheetProps.referrerPolicy && (stylesheetProps.referrerPolicy = preloadProps.referrerPolicy);
      null == stylesheetProps.title && (stylesheetProps.title = preloadProps.title);
    }
    function adoptPreloadPropsForScript(scriptProps, preloadProps) {
      null == scriptProps.crossOrigin && (scriptProps.crossOrigin = preloadProps.crossOrigin);
      null == scriptProps.referrerPolicy && (scriptProps.referrerPolicy = preloadProps.referrerPolicy);
      null == scriptProps.integrity && (scriptProps.integrity = preloadProps.integrity);
    }
    var tagCaches = null;
    function getHydratableHoistableCache(type, keyAttribute, ownerDocument) {
      if (null === tagCaches) {
        var cache = /* @__PURE__ */ new Map();
        var caches = tagCaches = /* @__PURE__ */ new Map();
        caches.set(ownerDocument, cache);
      } else
        caches = tagCaches, cache = caches.get(ownerDocument), cache || (cache = /* @__PURE__ */ new Map(), caches.set(ownerDocument, cache));
      if (cache.has(type)) return cache;
      cache.set(type, null);
      ownerDocument = ownerDocument.getElementsByTagName(type);
      for (caches = 0; caches < ownerDocument.length; caches++) {
        var node2 = ownerDocument[caches];
        if (!(node2[internalHoistableMarker] || node2[internalInstanceKey] || "link" === type && "stylesheet" === node2.getAttribute("rel")) && "http://www.w3.org/2000/svg" !== node2.namespaceURI) {
          var nodeKey = node2.getAttribute(keyAttribute) || "";
          nodeKey = type + nodeKey;
          var existing = cache.get(nodeKey);
          existing ? existing.push(node2) : cache.set(nodeKey, [node2]);
        }
      }
      return cache;
    }
    function mountHoistable(hoistableRoot, type, instance) {
      hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
      hoistableRoot.head.insertBefore(
        instance,
        "title" === type ? hoistableRoot.querySelector("head > title") : null
      );
    }
    function isHostHoistableType(type, props, hostContext) {
      if (1 === hostContext || null != props.itemProp) return false;
      switch (type) {
        case "meta":
        case "title":
          return true;
        case "style":
          if ("string" !== typeof props.precedence || "string" !== typeof props.href || "" === props.href)
            break;
          return true;
        case "link":
          if ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href || props.onLoad || props.onError)
            break;
          switch (props.rel) {
            case "stylesheet":
              return type = props.disabled, "string" === typeof props.precedence && null == type;
            default:
              return true;
          }
        case "script":
          if (props.async && "function" !== typeof props.async && "symbol" !== typeof props.async && !props.onLoad && !props.onError && props.src && "string" === typeof props.src)
            return true;
      }
      return false;
    }
    function preloadResource(resource) {
      return "stylesheet" === resource.type && 0 === (resource.state.loading & 3) ? false : true;
    }
    var suspendedState = null;
    function noop() {
    }
    function suspendResource(hoistableRoot, resource, props) {
      if (null === suspendedState) throw Error(formatProdErrorMessage(475));
      var state = suspendedState;
      if ("stylesheet" === resource.type && ("string" !== typeof props.media || false !== matchMedia(props.media).matches) && 0 === (resource.state.loading & 4)) {
        if (null === resource.instance) {
          var key2 = getStyleKey(props.href), instance = hoistableRoot.querySelector(
            getStylesheetSelectorFromKey(key2)
          );
          if (instance) {
            hoistableRoot = instance._p;
            null !== hoistableRoot && "object" === typeof hoistableRoot && "function" === typeof hoistableRoot.then && (state.count++, state = onUnsuspend.bind(state), hoistableRoot.then(state, state));
            resource.state.loading |= 4;
            resource.instance = instance;
            markNodeAsHoistable(instance);
            return;
          }
          instance = hoistableRoot.ownerDocument || hoistableRoot;
          props = stylesheetPropsFromRawProps(props);
          (key2 = preloadPropsMap.get(key2)) && adoptPreloadPropsForStylesheet(props, key2);
          instance = instance.createElement("link");
          markNodeAsHoistable(instance);
          var linkInstance = instance;
          linkInstance._p = new Promise(function(resolve, reject) {
            linkInstance.onload = resolve;
            linkInstance.onerror = reject;
          });
          setInitialProperties(instance, "link", props);
          resource.instance = instance;
        }
        null === state.stylesheets && (state.stylesheets = /* @__PURE__ */ new Map());
        state.stylesheets.set(resource, hoistableRoot);
        (hoistableRoot = resource.state.preload) && 0 === (resource.state.loading & 3) && (state.count++, resource = onUnsuspend.bind(state), hoistableRoot.addEventListener("load", resource), hoistableRoot.addEventListener("error", resource));
      }
    }
    function waitForCommitToBeReady() {
      if (null === suspendedState) throw Error(formatProdErrorMessage(475));
      var state = suspendedState;
      state.stylesheets && 0 === state.count && insertSuspendedStylesheets(state, state.stylesheets);
      return 0 < state.count ? function(commit) {
        var stylesheetTimer = setTimeout(function() {
          state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets);
          if (state.unsuspend) {
            var unsuspend = state.unsuspend;
            state.unsuspend = null;
            unsuspend();
          }
        }, 6e4);
        state.unsuspend = commit;
        return function() {
          state.unsuspend = null;
          clearTimeout(stylesheetTimer);
        };
      } : null;
    }
    function onUnsuspend() {
      this.count--;
      if (0 === this.count) {
        if (this.stylesheets) insertSuspendedStylesheets(this, this.stylesheets);
        else if (this.unsuspend) {
          var unsuspend = this.unsuspend;
          this.unsuspend = null;
          unsuspend();
        }
      }
    }
    var precedencesByRoot = null;
    function insertSuspendedStylesheets(state, resources) {
      state.stylesheets = null;
      null !== state.unsuspend && (state.count++, precedencesByRoot = /* @__PURE__ */ new Map(), resources.forEach(insertStylesheetIntoRoot, state), precedencesByRoot = null, onUnsuspend.call(state));
    }
    function insertStylesheetIntoRoot(root2, resource) {
      if (!(resource.state.loading & 4)) {
        var precedences = precedencesByRoot.get(root2);
        if (precedences) var last = precedences.get(null);
        else {
          precedences = /* @__PURE__ */ new Map();
          precedencesByRoot.set(root2, precedences);
          for (var nodes = root2.querySelectorAll(
            "link[data-precedence],style[data-precedence]"
          ), i2 = 0; i2 < nodes.length; i2++) {
            var node2 = nodes[i2];
            if ("LINK" === node2.nodeName || "not all" !== node2.getAttribute("media"))
              precedences.set(node2.dataset.precedence, node2), last = node2;
          }
          last && precedences.set(null, last);
        }
        nodes = resource.instance;
        node2 = nodes.getAttribute("data-precedence");
        i2 = precedences.get(node2) || last;
        i2 === last && precedences.set(null, nodes);
        precedences.set(node2, nodes);
        this.count++;
        last = onUnsuspend.bind(this);
        nodes.addEventListener("load", last);
        nodes.addEventListener("error", last);
        i2 ? i2.parentNode.insertBefore(nodes, i2.nextSibling) : (root2 = 9 === root2.nodeType ? root2.head : root2, root2.insertBefore(nodes, root2.firstChild));
        resource.state.loading |= 4;
      }
    }
    var HostTransitionContext = {
      $$typeof: REACT_CONTEXT_TYPE,
      Provider: null,
      Consumer: null,
      _currentValue: sharedNotPendingObject,
      _currentValue2: sharedNotPendingObject,
      _threadCount: 0
    };
    function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, formState) {
      this.tag = 1;
      this.containerInfo = containerInfo;
      this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
      this.timeoutHandle = -1;
      this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
      this.callbackPriority = 0;
      this.expirationTimes = createLaneMap(-1);
      this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.finishedLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
      this.entanglements = createLaneMap(0);
      this.hiddenUpdates = createLaneMap(null);
      this.identifierPrefix = identifierPrefix;
      this.onUncaughtError = onUncaughtError;
      this.onCaughtError = onCaughtError;
      this.onRecoverableError = onRecoverableError;
      this.pooledCache = null;
      this.pooledCacheLanes = 0;
      this.formState = formState;
      this.incompleteTransitions = /* @__PURE__ */ new Map();
    }
    function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, transitionCallbacks, formState) {
      containerInfo = new FiberRootNode(
        containerInfo,
        tag,
        hydrate,
        identifierPrefix,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        formState
      );
      tag = 1;
      true === isStrictMode && (tag |= 24);
      isStrictMode = createFiberImplClass(3, null, null, tag);
      containerInfo.current = isStrictMode;
      isStrictMode.stateNode = containerInfo;
      tag = createCache();
      tag.refCount++;
      containerInfo.pooledCache = tag;
      tag.refCount++;
      isStrictMode.memoizedState = {
        element: initialChildren,
        isDehydrated: hydrate,
        cache: tag
      };
      initializeUpdateQueue(isStrictMode);
      return containerInfo;
    }
    function getContextForSubtree(parentComponent) {
      if (!parentComponent) return emptyContextObject;
      parentComponent = emptyContextObject;
      return parentComponent;
    }
    function updateContainerImpl(rootFiber, lane, element, container2, parentComponent, callback) {
      parentComponent = getContextForSubtree(parentComponent);
      null === container2.context ? container2.context = parentComponent : container2.pendingContext = parentComponent;
      container2 = createUpdate(lane);
      container2.payload = { element };
      callback = void 0 === callback ? null : callback;
      null !== callback && (container2.callback = callback);
      element = enqueueUpdate(rootFiber, container2, lane);
      null !== element && (scheduleUpdateOnFiber(element, rootFiber, lane), entangleTransitions(element, rootFiber, lane));
    }
    function markRetryLaneImpl(fiber, retryLane) {
      fiber = fiber.memoizedState;
      if (null !== fiber && null !== fiber.dehydrated) {
        var a = fiber.retryLane;
        fiber.retryLane = 0 !== a && a < retryLane ? a : retryLane;
      }
    }
    function markRetryLaneIfNotHydrated(fiber, retryLane) {
      markRetryLaneImpl(fiber, retryLane);
      (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
    }
    function attemptContinuousHydration(fiber) {
      if (13 === fiber.tag) {
        var root2 = enqueueConcurrentRenderForLane(fiber, 67108864);
        null !== root2 && scheduleUpdateOnFiber(root2, fiber, 67108864);
        markRetryLaneIfNotHydrated(fiber, 67108864);
      }
    }
    var _enabled = true;
    function dispatchDiscreteEvent(domEventName, eventSystemFlags, container2, nativeEvent) {
      var prevTransition = ReactSharedInternals.T;
      ReactSharedInternals.T = null;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = 2, dispatchEvent(domEventName, eventSystemFlags, container2, nativeEvent);
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
      }
    }
    function dispatchContinuousEvent(domEventName, eventSystemFlags, container2, nativeEvent) {
      var prevTransition = ReactSharedInternals.T;
      ReactSharedInternals.T = null;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = 8, dispatchEvent(domEventName, eventSystemFlags, container2, nativeEvent);
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
      }
    }
    function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      if (_enabled) {
        var blockedOn = findInstanceBlockingEvent(nativeEvent);
        if (null === blockedOn)
          dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            return_targetInst,
            targetContainer
          ), clearIfContinuousEvent(domEventName, nativeEvent);
        else if (queueIfContinuousEvent(
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        ))
          nativeEvent.stopPropagation();
        else if (clearIfContinuousEvent(domEventName, nativeEvent), eventSystemFlags & 4 && -1 < discreteReplayableEvents.indexOf(domEventName)) {
          for (; null !== blockedOn; ) {
            var fiber = getInstanceFromNode(blockedOn);
            if (null !== fiber)
              switch (fiber.tag) {
                case 3:
                  fiber = fiber.stateNode;
                  if (fiber.current.memoizedState.isDehydrated) {
                    var lanes = getHighestPriorityLanes(fiber.pendingLanes);
                    if (0 !== lanes) {
                      var root2 = fiber;
                      root2.pendingLanes |= 2;
                      for (root2.entangledLanes |= 2; lanes; ) {
                        var lane = 1 << 31 - clz32(lanes);
                        root2.entanglements[1] |= lane;
                        lanes &= ~lane;
                      }
                      ensureRootIsScheduled(fiber);
                      0 === (executionContext & 6) && (workInProgressRootRenderTargetTime = now() + 500, flushSyncWorkAcrossRoots_impl(0));
                    }
                  }
                  break;
                case 13:
                  root2 = enqueueConcurrentRenderForLane(fiber, 2), null !== root2 && scheduleUpdateOnFiber(root2, fiber, 2), flushSyncWork$1(), markRetryLaneIfNotHydrated(fiber, 2);
              }
            fiber = findInstanceBlockingEvent(nativeEvent);
            null === fiber && dispatchEventForPluginEventSystem(
              domEventName,
              eventSystemFlags,
              nativeEvent,
              return_targetInst,
              targetContainer
            );
            if (fiber === blockedOn) break;
            blockedOn = fiber;
          }
          null !== blockedOn && nativeEvent.stopPropagation();
        } else
          dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            null,
            targetContainer
          );
      }
    }
    function findInstanceBlockingEvent(nativeEvent) {
      nativeEvent = getEventTarget(nativeEvent);
      return findInstanceBlockingTarget(nativeEvent);
    }
    var return_targetInst = null;
    function findInstanceBlockingTarget(targetNode) {
      return_targetInst = null;
      targetNode = getClosestInstanceFromNode(targetNode);
      if (null !== targetNode) {
        var nearestMounted = getNearestMountedFiber(targetNode);
        if (null === nearestMounted) targetNode = null;
        else {
          var tag = nearestMounted.tag;
          if (13 === tag) {
            targetNode = getSuspenseInstanceFromFiber(nearestMounted);
            if (null !== targetNode) return targetNode;
            targetNode = null;
          } else if (3 === tag) {
            if (nearestMounted.stateNode.current.memoizedState.isDehydrated)
              return 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
            targetNode = null;
          } else nearestMounted !== targetNode && (targetNode = null);
        }
      }
      return_targetInst = targetNode;
      return null;
    }
    function getEventPriority(domEventName) {
      switch (domEventName) {
        case "beforetoggle":
        case "cancel":
        case "click":
        case "close":
        case "contextmenu":
        case "copy":
        case "cut":
        case "auxclick":
        case "dblclick":
        case "dragend":
        case "dragstart":
        case "drop":
        case "focusin":
        case "focusout":
        case "input":
        case "invalid":
        case "keydown":
        case "keypress":
        case "keyup":
        case "mousedown":
        case "mouseup":
        case "paste":
        case "pause":
        case "play":
        case "pointercancel":
        case "pointerdown":
        case "pointerup":
        case "ratechange":
        case "reset":
        case "resize":
        case "seeked":
        case "submit":
        case "toggle":
        case "touchcancel":
        case "touchend":
        case "touchstart":
        case "volumechange":
        case "change":
        case "selectionchange":
        case "textInput":
        case "compositionstart":
        case "compositionend":
        case "compositionupdate":
        case "beforeblur":
        case "afterblur":
        case "beforeinput":
        case "blur":
        case "fullscreenchange":
        case "focus":
        case "hashchange":
        case "popstate":
        case "select":
        case "selectstart":
          return 2;
        case "drag":
        case "dragenter":
        case "dragexit":
        case "dragleave":
        case "dragover":
        case "mousemove":
        case "mouseout":
        case "mouseover":
        case "pointermove":
        case "pointerout":
        case "pointerover":
        case "scroll":
        case "touchmove":
        case "wheel":
        case "mouseenter":
        case "mouseleave":
        case "pointerenter":
        case "pointerleave":
          return 8;
        case "message":
          switch (getCurrentPriorityLevel()) {
            case ImmediatePriority:
              return 2;
            case UserBlockingPriority:
              return 8;
            case NormalPriority$1:
            case LowPriority:
              return 32;
            case IdlePriority:
              return 268435456;
            default:
              return 32;
          }
        default:
          return 32;
      }
    }
    var hasScheduledReplayAttempt = false, queuedFocus = null, queuedDrag = null, queuedMouse = null, queuedPointers = /* @__PURE__ */ new Map(), queuedPointerCaptures = /* @__PURE__ */ new Map(), queuedExplicitHydrationTargets = [], discreteReplayableEvents = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(
      " "
    );
    function clearIfContinuousEvent(domEventName, nativeEvent) {
      switch (domEventName) {
        case "focusin":
        case "focusout":
          queuedFocus = null;
          break;
        case "dragenter":
        case "dragleave":
          queuedDrag = null;
          break;
        case "mouseover":
        case "mouseout":
          queuedMouse = null;
          break;
        case "pointerover":
        case "pointerout":
          queuedPointers.delete(nativeEvent.pointerId);
          break;
        case "gotpointercapture":
        case "lostpointercapture":
          queuedPointerCaptures.delete(nativeEvent.pointerId);
      }
    }
    function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      if (null === existingQueuedEvent || existingQueuedEvent.nativeEvent !== nativeEvent)
        return existingQueuedEvent = {
          blockedOn,
          domEventName,
          eventSystemFlags,
          nativeEvent,
          targetContainers: [targetContainer]
        }, null !== blockedOn && (blockedOn = getInstanceFromNode(blockedOn), null !== blockedOn && attemptContinuousHydration(blockedOn)), existingQueuedEvent;
      existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
      blockedOn = existingQueuedEvent.targetContainers;
      null !== targetContainer && -1 === blockedOn.indexOf(targetContainer) && blockedOn.push(targetContainer);
      return existingQueuedEvent;
    }
    function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      switch (domEventName) {
        case "focusin":
          return queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedFocus,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "dragenter":
          return queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedDrag,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "mouseover":
          return queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedMouse,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "pointerover":
          var pointerId = nativeEvent.pointerId;
          queuedPointers.set(
            pointerId,
            accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedPointers.get(pointerId) || null,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            )
          );
          return true;
        case "gotpointercapture":
          return pointerId = nativeEvent.pointerId, queuedPointerCaptures.set(
            pointerId,
            accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedPointerCaptures.get(pointerId) || null,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            )
          ), true;
      }
      return false;
    }
    function attemptExplicitHydrationTarget(queuedTarget) {
      var targetInst = getClosestInstanceFromNode(queuedTarget.target);
      if (null !== targetInst) {
        var nearestMounted = getNearestMountedFiber(targetInst);
        if (null !== nearestMounted) {
          if (targetInst = nearestMounted.tag, 13 === targetInst) {
            if (targetInst = getSuspenseInstanceFromFiber(nearestMounted), null !== targetInst) {
              queuedTarget.blockedOn = targetInst;
              runWithPriority(queuedTarget.priority, function() {
                if (13 === nearestMounted.tag) {
                  var lane = requestUpdateLane(), root2 = enqueueConcurrentRenderForLane(nearestMounted, lane);
                  null !== root2 && scheduleUpdateOnFiber(root2, nearestMounted, lane);
                  markRetryLaneIfNotHydrated(nearestMounted, lane);
                }
              });
              return;
            }
          } else if (3 === targetInst && nearestMounted.stateNode.current.memoizedState.isDehydrated) {
            queuedTarget.blockedOn = 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
            return;
          }
        }
      }
      queuedTarget.blockedOn = null;
    }
    function attemptReplayContinuousQueuedEvent(queuedEvent) {
      if (null !== queuedEvent.blockedOn) return false;
      for (var targetContainers = queuedEvent.targetContainers; 0 < targetContainers.length; ) {
        var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.nativeEvent);
        if (null === nextBlockedOn) {
          nextBlockedOn = queuedEvent.nativeEvent;
          var nativeEventClone = new nextBlockedOn.constructor(
            nextBlockedOn.type,
            nextBlockedOn
          );
          currentReplayingEvent = nativeEventClone;
          nextBlockedOn.target.dispatchEvent(nativeEventClone);
          currentReplayingEvent = null;
        } else
          return targetContainers = getInstanceFromNode(nextBlockedOn), null !== targetContainers && attemptContinuousHydration(targetContainers), queuedEvent.blockedOn = nextBlockedOn, false;
        targetContainers.shift();
      }
      return true;
    }
    function attemptReplayContinuousQueuedEventInMap(queuedEvent, key2, map2) {
      attemptReplayContinuousQueuedEvent(queuedEvent) && map2.delete(key2);
    }
    function replayUnblockedEvents() {
      hasScheduledReplayAttempt = false;
      null !== queuedFocus && attemptReplayContinuousQueuedEvent(queuedFocus) && (queuedFocus = null);
      null !== queuedDrag && attemptReplayContinuousQueuedEvent(queuedDrag) && (queuedDrag = null);
      null !== queuedMouse && attemptReplayContinuousQueuedEvent(queuedMouse) && (queuedMouse = null);
      queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
      queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
    }
    function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
      queuedEvent.blockedOn === unblocked && (queuedEvent.blockedOn = null, hasScheduledReplayAttempt || (hasScheduledReplayAttempt = true, Scheduler.unstable_scheduleCallback(
        Scheduler.unstable_NormalPriority,
        replayUnblockedEvents
      )));
    }
    var lastScheduledReplayQueue = null;
    function scheduleReplayQueueIfNeeded(formReplayingQueue) {
      lastScheduledReplayQueue !== formReplayingQueue && (lastScheduledReplayQueue = formReplayingQueue, Scheduler.unstable_scheduleCallback(
        Scheduler.unstable_NormalPriority,
        function() {
          lastScheduledReplayQueue === formReplayingQueue && (lastScheduledReplayQueue = null);
          for (var i2 = 0; i2 < formReplayingQueue.length; i2 += 3) {
            var form = formReplayingQueue[i2], submitterOrAction = formReplayingQueue[i2 + 1], formData = formReplayingQueue[i2 + 2];
            if ("function" !== typeof submitterOrAction)
              if (null === findInstanceBlockingTarget(submitterOrAction || form))
                continue;
              else break;
            var formInst = getInstanceFromNode(form);
            null !== formInst && (formReplayingQueue.splice(i2, 3), i2 -= 3, startHostTransition(
              formInst,
              {
                pending: true,
                data: formData,
                method: form.method,
                action: submitterOrAction
              },
              submitterOrAction,
              formData
            ));
          }
        }
      ));
    }
    function retryIfBlockedOn(unblocked) {
      function unblock(queuedEvent) {
        return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
      }
      null !== queuedFocus && scheduleCallbackIfUnblocked(queuedFocus, unblocked);
      null !== queuedDrag && scheduleCallbackIfUnblocked(queuedDrag, unblocked);
      null !== queuedMouse && scheduleCallbackIfUnblocked(queuedMouse, unblocked);
      queuedPointers.forEach(unblock);
      queuedPointerCaptures.forEach(unblock);
      for (var i2 = 0; i2 < queuedExplicitHydrationTargets.length; i2++) {
        var queuedTarget = queuedExplicitHydrationTargets[i2];
        queuedTarget.blockedOn === unblocked && (queuedTarget.blockedOn = null);
      }
      for (; 0 < queuedExplicitHydrationTargets.length && (i2 = queuedExplicitHydrationTargets[0], null === i2.blockedOn); )
        attemptExplicitHydrationTarget(i2), null === i2.blockedOn && queuedExplicitHydrationTargets.shift();
      i2 = (unblocked.ownerDocument || unblocked).$$reactFormReplay;
      if (null != i2)
        for (queuedTarget = 0; queuedTarget < i2.length; queuedTarget += 3) {
          var form = i2[queuedTarget], submitterOrAction = i2[queuedTarget + 1], formProps = form[internalPropsKey] || null;
          if ("function" === typeof submitterOrAction)
            formProps || scheduleReplayQueueIfNeeded(i2);
          else if (formProps) {
            var action = null;
            if (submitterOrAction && submitterOrAction.hasAttribute("formAction"))
              if (form = submitterOrAction, formProps = submitterOrAction[internalPropsKey] || null)
                action = formProps.formAction;
              else {
                if (null !== findInstanceBlockingTarget(form)) continue;
              }
            else action = formProps.action;
            "function" === typeof action ? i2[queuedTarget + 1] = action : (i2.splice(queuedTarget, 3), queuedTarget -= 3);
            scheduleReplayQueueIfNeeded(i2);
          }
        }
    }
    function ReactDOMRoot(internalRoot) {
      this._internalRoot = internalRoot;
    }
    ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children2) {
      var root2 = this._internalRoot;
      if (null === root2) throw Error(formatProdErrorMessage(409));
      var current = root2.current, lane = requestUpdateLane();
      updateContainerImpl(current, lane, children2, root2, null, null);
    };
    ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() {
      var root2 = this._internalRoot;
      if (null !== root2) {
        this._internalRoot = null;
        var container2 = root2.containerInfo;
        0 === root2.tag && flushPassiveEffects();
        updateContainerImpl(root2.current, 2, null, root2, null, null);
        flushSyncWork$1();
        container2[internalContainerInstanceKey] = null;
      }
    };
    function ReactDOMHydrationRoot(internalRoot) {
      this._internalRoot = internalRoot;
    }
    ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = function(target2) {
      if (target2) {
        var updatePriority = resolveUpdatePriority();
        target2 = { blockedOn: null, target: target2, priority: updatePriority };
        for (var i2 = 0; i2 < queuedExplicitHydrationTargets.length && 0 !== updatePriority && updatePriority < queuedExplicitHydrationTargets[i2].priority; i2++) ;
        queuedExplicitHydrationTargets.splice(i2, 0, target2);
        0 === i2 && attemptExplicitHydrationTarget(target2);
      }
    };
    var isomorphicReactPackageVersion$jscomp$inline_1686 = React.version;
    if ("19.0.0" !== isomorphicReactPackageVersion$jscomp$inline_1686)
      throw Error(
        formatProdErrorMessage(
          527,
          isomorphicReactPackageVersion$jscomp$inline_1686,
          "19.0.0"
        )
      );
    ReactDOMSharedInternals.findDOMNode = function(componentOrElement) {
      var fiber = componentOrElement._reactInternals;
      if (void 0 === fiber) {
        if ("function" === typeof componentOrElement.render)
          throw Error(formatProdErrorMessage(188));
        componentOrElement = Object.keys(componentOrElement).join(",");
        throw Error(formatProdErrorMessage(268, componentOrElement));
      }
      componentOrElement = findCurrentFiberUsingSlowPath(fiber);
      componentOrElement = null !== componentOrElement ? findCurrentHostFiberImpl(componentOrElement) : null;
      componentOrElement = null === componentOrElement ? null : componentOrElement.stateNode;
      return componentOrElement;
    };
    var internals$jscomp$inline_2165 = {
      bundleType: 0,
      version: "19.0.0",
      rendererPackageName: "react-dom",
      currentDispatcherRef: ReactSharedInternals,
      findFiberByHostInstance: getClosestInstanceFromNode,
      reconcilerVersion: "19.0.0"
    };
    if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
      var hook$jscomp$inline_2166 = __REACT_DEVTOOLS_GLOBAL_HOOK__;
      if (!hook$jscomp$inline_2166.isDisabled && hook$jscomp$inline_2166.supportsFiber)
        try {
          rendererID = hook$jscomp$inline_2166.inject(
            internals$jscomp$inline_2165
          ), injectedHook = hook$jscomp$inline_2166;
        } catch (err2) {
        }
    }
    reactDomClient_production.createRoot = function(container2, options2) {
      if (!isValidContainer(container2)) throw Error(formatProdErrorMessage(299));
      var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError, transitionCallbacks = null;
      null !== options2 && void 0 !== options2 && (true === options2.unstable_strictMode && (isStrictMode = true), void 0 !== options2.identifierPrefix && (identifierPrefix = options2.identifierPrefix), void 0 !== options2.onUncaughtError && (onUncaughtError = options2.onUncaughtError), void 0 !== options2.onCaughtError && (onCaughtError = options2.onCaughtError), void 0 !== options2.onRecoverableError && (onRecoverableError = options2.onRecoverableError), void 0 !== options2.unstable_transitionCallbacks && (transitionCallbacks = options2.unstable_transitionCallbacks));
      options2 = createFiberRoot(
        container2,
        1,
        false,
        null,
        null,
        isStrictMode,
        identifierPrefix,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        transitionCallbacks,
        null
      );
      container2[internalContainerInstanceKey] = options2.current;
      listenToAllSupportedEvents(
        8 === container2.nodeType ? container2.parentNode : container2
      );
      return new ReactDOMRoot(options2);
    };
    reactDomClient_production.hydrateRoot = function(container2, initialChildren, options2) {
      if (!isValidContainer(container2)) throw Error(formatProdErrorMessage(299));
      var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError, transitionCallbacks = null, formState = null;
      null !== options2 && void 0 !== options2 && (true === options2.unstable_strictMode && (isStrictMode = true), void 0 !== options2.identifierPrefix && (identifierPrefix = options2.identifierPrefix), void 0 !== options2.onUncaughtError && (onUncaughtError = options2.onUncaughtError), void 0 !== options2.onCaughtError && (onCaughtError = options2.onCaughtError), void 0 !== options2.onRecoverableError && (onRecoverableError = options2.onRecoverableError), void 0 !== options2.unstable_transitionCallbacks && (transitionCallbacks = options2.unstable_transitionCallbacks), void 0 !== options2.formState && (formState = options2.formState));
      initialChildren = createFiberRoot(
        container2,
        1,
        true,
        initialChildren,
        null != options2 ? options2 : null,
        isStrictMode,
        identifierPrefix,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        transitionCallbacks,
        formState
      );
      initialChildren.context = getContextForSubtree(null);
      options2 = initialChildren.current;
      isStrictMode = requestUpdateLane();
      identifierPrefix = createUpdate(isStrictMode);
      identifierPrefix.callback = null;
      enqueueUpdate(options2, identifierPrefix, isStrictMode);
      initialChildren.current.lanes = isStrictMode;
      markRootUpdated$1(initialChildren, isStrictMode);
      ensureRootIsScheduled(initialChildren);
      container2[internalContainerInstanceKey] = initialChildren.current;
      listenToAllSupportedEvents(container2);
      return new ReactDOMHydrationRoot(initialChildren);
    };
    reactDomClient_production.version = "19.0.0";
    function checkDCE() {
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
        return;
      }
      try {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
      } catch (err2) {
        console.error(err2);
      }
    }
    {
      checkDCE();
      client.exports = reactDomClient_production;
    }
    var clientExports = client.exports;
    var prism = { exports: {} };
    (function(module2) {
      var _self = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" && 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 Prism2 = function(_self2) {
        var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
        var uniqueId = 0;
        var plainTextGrammar = {};
        var _ = {
          /**
           * 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: _self2.Prism && _self2.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: _self2.Prism && _self2.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 encode2(tokens) {
              if (tokens instanceof Token2) {
                return new Token2(tokens.type, encode2(tokens.content), tokens.alias);
              } else if (Array.isArray(tokens)) {
                return tokens.map(encode2);
              } else {
                return tokens.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(o) {
              return Object.prototype.toString.call(o).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(obj) {
              if (!obj["__id"]) {
                Object.defineProperty(obj, "__id", { value: ++uniqueId });
              }
              return obj["__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 deepClone(o, visited) {
              visited = visited || {};
              var clone2;
              var id;
              switch (_.util.type(o)) {
                case "Object":
                  id = _.util.objId(o);
                  if (visited[id]) {
                    return visited[id];
                  }
                  clone2 = /** @type {Record<string, any>} */
                  {};
                  visited[id] = clone2;
                  for (var key2 in o) {
                    if (o.hasOwnProperty(key2)) {
                      clone2[key2] = deepClone(o[key2], visited);
                    }
                  }
                  return (
                    /** @type {any} */
                    clone2
                  );
                case "Array":
                  id = _.util.objId(o);
                  if (visited[id]) {
                    return visited[id];
                  }
                  clone2 = [];
                  visited[id] = clone2;
                  /** @type {Array} */
                  /** @type {any} */
                  o.forEach(function(v, i2) {
                    clone2[i2] = deepClone(v, visited);
                  });
                  return (
                    /** @type {any} */
                    clone2
                  );
                default:
                  return o;
              }
            },
            /**
             * 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(element) {
              while (element) {
                var m = lang.exec(element.className);
                if (m) {
                  return m[1].toLowerCase();
                }
                element = element.parentElement;
              }
              return "none";
            },
            /**
             * Sets the Prism `language-xxxx` class of the given element.
             *
             * @param {Element} element
             * @param {string} language
             * @returns {void}
             */
            setLanguage: function(element, language2) {
              element.className = element.className.replace(RegExp(lang, "gi"), "");
              element.classList.add("language-" + language2);
            },
            /**
             * Returns the script element that is currently executing.
             *
             * This does __not__ work for line script element.
             *
             * @returns {HTMLScriptElement | null}
             */
            currentScript: function() {
              if (typeof document === "undefined") {
                return null;
              }
              if (document.currentScript && document.currentScript.tagName === "SCRIPT" && 1 < 2) {
                return (
                  /** @type {any} */
                  document.currentScript
                );
              }
              try {
                throw new Error();
              } catch (err2) {
                var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err2.stack) || [])[1];
                if (src) {
                  var scripts = document.getElementsByTagName("script");
                  for (var i2 in scripts) {
                    if (scripts[i2].src == src) {
                      return scripts[i2];
                    }
                  }
                }
                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(element, className2, defaultActivation) {
              var no2 = "no-" + className2;
              while (element) {
                var classList = element.classList;
                if (classList.contains(className2)) {
                  return true;
                }
                if (classList.contains(no2)) {
                  return false;
                }
                element = element.parentElement;
              }
              return !!defaultActivation;
            }
          },
          /**
           * 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: plainTextGrammar,
            plaintext: plainTextGrammar,
            text: plainTextGrammar,
            txt: plainTextGrammar,
            /**
             * 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(id, redef) {
              var lang2 = _.util.clone(_.languages[id]);
              for (var key2 in redef) {
                lang2[key2] = redef[key2];
              }
              return lang2;
            },
            /**
             * 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(inside2, before, insert2, root2) {
              root2 = root2 || /** @type {any} */
              _.languages;
              var grammar = root2[inside2];
              var ret = {};
              for (var token2 in grammar) {
                if (grammar.hasOwnProperty(token2)) {
                  if (token2 == before) {
                    for (var newToken2 in insert2) {
                      if (insert2.hasOwnProperty(newToken2)) {
                        ret[newToken2] = insert2[newToken2];
                      }
                    }
                  }
                  if (!insert2.hasOwnProperty(token2)) {
                    ret[token2] = grammar[token2];
                  }
                }
              }
              var old = root2[inside2];
              root2[inside2] = ret;
              _.languages.DFS(_.languages, function(key2, value2) {
                if (value2 === old && key2 != inside2) {
                  this[key2] = ret;
                }
              });
              return ret;
            },
            // Traverse a language definition with Depth First Search
            DFS: function DFS(o, callback, type, visited) {
              visited = visited || {};
              var objId = _.util.objId;
              for (var i2 in o) {
                if (o.hasOwnProperty(i2)) {
                  callback.call(o, i2, o[i2], type || i2);
                  var property = o[i2];
                  var propertyType = _.util.type(property);
                  if (propertyType === "Object" && !visited[objId(property)]) {
                    visited[objId(property)] = true;
                    DFS(property, callback, null, visited);
                  } else if (propertyType === "Array" && !visited[objId(property)]) {
                    visited[objId(property)] = true;
                    DFS(property, callback, i2, visited);
                  }
                }
              }
            }
          },
          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(async, callback) {
            _.highlightAllUnder(document, async, callback);
          },
          /**
           * 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(container2, async, callback) {
            var env = {
              callback,
              container: container2,
              selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
            };
            _.hooks.run("before-highlightall", env);
            env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
            _.hooks.run("before-all-elements-highlight", env);
            for (var i2 = 0, element; element = env.elements[i2++]; ) {
              _.highlightElement(element, async === true, env.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(element, async, callback) {
            var language2 = _.util.getLanguage(element);
            var grammar = _.languages[language2];
            _.util.setLanguage(element, language2);
            var parent = element.parentElement;
            if (parent && parent.nodeName.toLowerCase() === "pre") {
              _.util.setLanguage(parent, language2);
            }
            var code2 = element.textContent;
            var env = {
              element,
              language: language2,
              grammar,
              code: code2
            };
            function insertHighlightedCode(highlightedCode) {
              env.highlightedCode = highlightedCode;
              _.hooks.run("before-insert", env);
              env.element.innerHTML = env.highlightedCode;
              _.hooks.run("after-highlight", env);
              _.hooks.run("complete", env);
              callback && callback.call(env.element);
            }
            _.hooks.run("before-sanity-check", env);
            parent = env.element.parentElement;
            if (parent && parent.nodeName.toLowerCase() === "pre" && !parent.hasAttribute("tabindex")) {
              parent.setAttribute("tabindex", "0");
            }
            if (!env.code) {
              _.hooks.run("complete", env);
              callback && callback.call(env.element);
              return;
            }
            _.hooks.run("before-highlight", env);
            if (!env.grammar) {
              insertHighlightedCode(_.util.encode(env.code));
              return;
            }
            if (async && _self2.Worker) {
              var worker = new Worker(_.filename);
              worker.onmessage = function(evt) {
                insertHighlightedCode(evt.data);
              };
              worker.postMessage(JSON.stringify({
                language: env.language,
                code: env.code,
                immediateClose: true
              }));
            } else {
              insertHighlightedCode(_.highlight(env.code, env.grammar, env.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(text2, grammar, language2) {
            var env = {
              code: text2,
              grammar,
              language: language2
            };
            _.hooks.run("before-tokenize", env);
            if (!env.grammar) {
              throw new Error('The language "' + env.language + '" has no grammar.');
            }
            env.tokens = _.tokenize(env.code, env.grammar);
            _.hooks.run("after-tokenize", env);
            return Token2.stringify(_.util.encode(env.tokens), env.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(text2, grammar) {
            var rest = grammar.rest;
            if (rest) {
              for (var token2 in rest) {
                grammar[token2] = rest[token2];
              }
              delete grammar.rest;
            }
            var tokenList = new LinkedList();
            addAfter(tokenList, tokenList.head, text2);
            matchGrammar(text2, tokenList, grammar, tokenList.head, 0);
            return toArray2(tokenList);
          },
          /**
           * @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(name2, callback) {
              var hooks = _.hooks.all;
              hooks[name2] = hooks[name2] || [];
              hooks[name2].push(callback);
            },
            /**
             * 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(name2, env) {
              var callbacks = _.hooks.all[name2];
              if (!callbacks || !callbacks.length) {
                return;
              }
              for (var i2 = 0, callback; callback = callbacks[i2++]; ) {
                callback(env);
              }
            }
          },
          Token: Token2
        };
        _self2.Prism = _;
        function Token2(type, content2, alias, matchedStr) {
          this.type = type;
          this.content = content2;
          this.alias = alias;
          this.length = (matchedStr || "").length | 0;
        }
        Token2.stringify = function stringify2(o, language2) {
          if (typeof o == "string") {
            return o;
          }
          if (Array.isArray(o)) {
            var s = "";
            o.forEach(function(e) {
              s += stringify2(e, language2);
            });
            return s;
          }
          var env = {
            type: o.type,
            content: stringify2(o.content, language2),
            tag: "span",
            classes: ["token", o.type],
            attributes: {},
            language: language2
          };
          var aliases2 = o.alias;
          if (aliases2) {
            if (Array.isArray(aliases2)) {
              Array.prototype.push.apply(env.classes, aliases2);
            } else {
              env.classes.push(aliases2);
            }
          }
          _.hooks.run("wrap", env);
          var attributes = "";
          for (var name2 in env.attributes) {
            attributes += " " + name2 + '="' + (env.attributes[name2] || "").replace(/"/g, "&quot;") + '"';
          }
          return "<" + env.tag + ' class="' + env.classes.join(" ") + '"' + attributes + ">" + env.content + "</" + env.tag + ">";
        };
        function matchPattern(pattern, pos2, text2, lookbehind) {
          pattern.lastIndex = pos2;
          var match = pattern.exec(text2);
          if (match && lookbehind && match[1]) {
            var lookbehindLength = match[1].length;
            match.index += lookbehindLength;
            match[0] = match[0].slice(lookbehindLength);
          }
          return match;
        }
        function matchGrammar(text2, tokenList, grammar, startNode, startPos, rematch) {
          for (var token2 in grammar) {
            if (!grammar.hasOwnProperty(token2) || !grammar[token2]) {
              continue;
            }
            var patterns = grammar[token2];
            patterns = Array.isArray(patterns) ? patterns : [patterns];
            for (var j2 = 0; j2 < patterns.length; ++j2) {
              if (rematch && rematch.cause == token2 + "," + j2) {
                return;
              }
              var patternObj = patterns[j2];
              var inside2 = patternObj.inside;
              var lookbehind = !!patternObj.lookbehind;
              var greedy = !!patternObj.greedy;
              var alias = patternObj.alias;
              if (greedy && !patternObj.pattern.global) {
                var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
                patternObj.pattern = RegExp(patternObj.pattern.source, flags + "g");
              }
              var pattern = patternObj.pattern || patternObj;
              for (var currentNode = startNode.next, pos2 = startPos; currentNode !== tokenList.tail; pos2 += currentNode.value.length, currentNode = currentNode.next) {
                if (rematch && pos2 >= rematch.reach) {
                  break;
                }
                var str2 = currentNode.value;
                if (tokenList.length > text2.length) {
                  return;
                }
                if (str2 instanceof Token2) {
                  continue;
                }
                var removeCount = 1;
                var match;
                if (greedy) {
                  match = matchPattern(pattern, pos2, text2, lookbehind);
                  if (!match || match.index >= text2.length) {
                    break;
                  }
                  var from = match.index;
                  var to2 = match.index + match[0].length;
                  var p = pos2;
                  p += currentNode.value.length;
                  while (from >= p) {
                    currentNode = currentNode.next;
                    p += currentNode.value.length;
                  }
                  p -= currentNode.value.length;
                  pos2 = p;
                  if (currentNode.value instanceof Token2) {
                    continue;
                  }
                  for (var k = currentNode; k !== tokenList.tail && (p < to2 || typeof k.value === "string"); k = k.next) {
                    removeCount++;
                    p += k.value.length;
                  }
                  removeCount--;
                  str2 = text2.slice(pos2, p);
                  match.index -= pos2;
                } else {
                  match = matchPattern(pattern, 0, str2, lookbehind);
                  if (!match) {
                    continue;
                  }
                }
                var from = match.index;
                var matchStr = match[0];
                var before = str2.slice(0, from);
                var after = str2.slice(from + matchStr.length);
                var reach = pos2 + str2.length;
                if (rematch && reach > rematch.reach) {
                  rematch.reach = reach;
                }
                var removeFrom = currentNode.prev;
                if (before) {
                  removeFrom = addAfter(tokenList, removeFrom, before);
                  pos2 += before.length;
                }
                removeRange(tokenList, removeFrom, removeCount);
                var wrapped = new Token2(token2, inside2 ? _.tokenize(matchStr, inside2) : matchStr, alias, matchStr);
                currentNode = addAfter(tokenList, removeFrom, wrapped);
                if (after) {
                  addAfter(tokenList, currentNode, after);
                }
                if (removeCount > 1) {
                  var nestedRematch = {
                    cause: token2 + "," + j2,
                    reach
                  };
                  matchGrammar(text2, tokenList, grammar, currentNode.prev, pos2, nestedRematch);
                  if (rematch && nestedRematch.reach > rematch.reach) {
                    rematch.reach = nestedRematch.reach;
                  }
                }
              }
            }
          }
        }
        function LinkedList() {
          var head = { value: null, prev: null, next: null };
          var tail = { value: null, prev: head, next: null };
          head.next = tail;
          this.head = head;
          this.tail = tail;
          this.length = 0;
        }
        function addAfter(list2, node2, value2) {
          var next = node2.next;
          var newNode = { value: value2, prev: node2, next };
          node2.next = newNode;
          next.prev = newNode;
          list2.length++;
          return newNode;
        }
        function removeRange(list2, node2, count) {
          var next = node2.next;
          for (var i2 = 0; i2 < count && next !== list2.tail; i2++) {
            next = next.next;
          }
          node2.next = next;
          next.prev = node2;
          list2.length -= i2;
        }
        function toArray2(list2) {
          var array = [];
          var node2 = list2.head.next;
          while (node2 !== list2.tail) {
            array.push(node2.value);
            node2 = node2.next;
          }
          return array;
        }
        if (!_self2.document) {
          if (!_self2.addEventListener) {
            return _;
          }
          if (!_.disableWorkerMessageHandler) {
            _self2.addEventListener("message", function(evt) {
              var message2 = JSON.parse(evt.data);
              var lang2 = message2.language;
              var code2 = message2.code;
              var immediateClose = message2.immediateClose;
              _self2.postMessage(_.highlight(code2, _.languages[lang2], lang2));
              if (immediateClose) {
                _self2.close();
              }
            }, false);
          }
          return _;
        }
        var script = _.util.currentScript();
        if (script) {
          _.filename = script.src;
          if (script.hasAttribute("data-manual")) {
            _.manual = true;
          }
        }
        function highlightAutomaticallyCallback() {
          if (!_.manual) {
            _.highlightAll();
          }
        }
        if (!_.manual) {
          var readyState = document.readyState;
          if (readyState === "loading" || readyState === "interactive" && script && script.defer) {
            document.addEventListener("DOMContentLoaded", highlightAutomaticallyCallback);
          } else {
            if (window.requestAnimationFrame) {
              window.requestAnimationFrame(highlightAutomaticallyCallback);
            } else {
              window.setTimeout(highlightAutomaticallyCallback, 16);
            }
          }
        }
        return _;
      }(_self);
      if (module2.exports) {
        module2.exports = Prism2;
      }
      if (typeof commonjsGlobal !== "undefined") {
        commonjsGlobal.Prism = Prism2;
      }
      Prism2.languages.markup = {
        "comment": {
          pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
          greedy: true
        },
        "prolog": {
          pattern: /<\?[\s\S]+?\?>/,
          greedy: true
        },
        "doctype": {
          // https://www.w3.org/TR/xml/#NT-doctypedecl
          pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
          greedy: true,
          inside: {
            "internal-subset": {
              pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
              lookbehind: true,
              greedy: true,
              inside: null
              // see below
            },
            "string": {
              pattern: /"[^"]*"|'[^']*'/,
              greedy: true
            },
            "punctuation": /^<!|>$|[[\]]/,
            "doctype-tag": /^DOCTYPE/i,
            "name": /[^\s<>'"]+/
          }
        },
        "cdata": {
          pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
          greedy: true
        },
        "tag": {
          pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
          greedy: true,
          inside: {
            "tag": {
              pattern: /^<\/?[^\s>\/]+/,
              inside: {
                "punctuation": /^<\/?/,
                "namespace": /^[^\s>\/:]+:/
              }
            },
            "special-attr": [],
            "attr-value": {
              pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
              inside: {
                "punctuation": [
                  {
                    pattern: /^=/,
                    alias: "attr-equals"
                  },
                  {
                    pattern: /^(\s*)["']|["']$/,
                    lookbehind: true
                  }
                ]
              }
            },
            "punctuation": /\/?>/,
            "attr-name": {
              pattern: /[^\s>\/]+/,
              inside: {
                "namespace": /^[^\s>\/:]+:/
              }
            }
          }
        },
        "entity": [
          {
            pattern: /&[\da-z]{1,8};/i,
            alias: "named-entity"
          },
          /&#x?[\da-f]{1,8};/i
        ]
      };
      Prism2.languages.markup["tag"].inside["attr-value"].inside["entity"] = Prism2.languages.markup["entity"];
      Prism2.languages.markup["doctype"].inside["internal-subset"].inside = Prism2.languages.markup;
      Prism2.hooks.add("wrap", function(env) {
        if (env.type === "entity") {
          env.attributes["title"] = env.content.replace(/&amp;/, "&");
        }
      });
      Object.defineProperty(Prism2.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 addInlined(tagName, lang) {
          var includedCdataInside = {};
          includedCdataInside["language-" + lang] = {
            pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
            lookbehind: true,
            inside: Prism2.languages[lang]
          };
          includedCdataInside["cdata"] = /^<!\[CDATA\[|\]\]>$/i;
          var inside2 = {
            "included-cdata": {
              pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
              inside: includedCdataInside
            }
          };
          inside2["language-" + lang] = {
            pattern: /[\s\S]+/,
            inside: Prism2.languages[lang]
          };
          var def = {};
          def[tagName] = {
            pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function() {
              return tagName;
            }), "i"),
            lookbehind: true,
            greedy: true,
            inside: inside2
          };
          Prism2.languages.insertBefore("markup", "cdata", def);
        }
      });
      Object.defineProperty(Prism2.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(attrName, lang) {
          Prism2.languages.markup.tag.inside["special-attr"].push({
            pattern: RegExp(
              /(^|["'\s])/.source + "(?:" + attrName + ")" + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
              "i"
            ),
            lookbehind: true,
            inside: {
              "attr-name": /^[^\s=]+/,
              "attr-value": {
                pattern: /=[\s\S]+/,
                inside: {
                  "value": {
                    pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
                    lookbehind: true,
                    alias: [lang, "language-" + lang],
                    inside: Prism2.languages[lang]
                  },
                  "punctuation": [
                    {
                      pattern: /^=/,
                      alias: "attr-equals"
                    },
                    /"|'/
                  ]
                }
              }
            }
          });
        }
      });
      Prism2.languages.html = Prism2.languages.markup;
      Prism2.languages.mathml = Prism2.languages.markup;
      Prism2.languages.svg = Prism2.languages.markup;
      Prism2.languages.xml = Prism2.languages.extend("markup", {});
      Prism2.languages.ssml = Prism2.languages.xml;
      Prism2.languages.atom = Prism2.languages.xml;
      Prism2.languages.rss = Prism2.languages.xml;
      (function(Prism3) {
        var string2 = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
        Prism3.languages.css = {
          "comment": /\/\*[\s\S]*?\*\//,
          "atrule": {
            pattern: RegExp("@[\\w-](?:" + /[^;{\s"']|\s+(?!\s)/.source + "|" + string2.source + ")*?" + /(?:;|(?=\s*\{))/.source),
            inside: {
              "rule": /^@[\w-]+/,
              "selector-function-argument": {
                pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
                lookbehind: true,
                alias: "selector"
              },
              "keyword": {
                pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
                lookbehind: true
              }
              // See rest below
            }
          },
          "url": {
            // https://drafts.csswg.org/css-values-3/#urls
            pattern: RegExp("\\burl\\((?:" + string2.source + "|" + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ")\\)", "i"),
            greedy: true,
            inside: {
              "function": /^url/i,
              "punctuation": /^\(|\)$/,
              "string": {
                pattern: RegExp("^" + string2.source + "$"),
                alias: "url"
              }
            }
          },
          "selector": {
            pattern: RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|` + string2.source + ")*(?=\\s*\\{)"),
            lookbehind: true
          },
          "string": {
            pattern: string2,
            greedy: true
          },
          "property": {
            pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
            lookbehind: true
          },
          "important": /!important\b/i,
          "function": {
            pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
            lookbehind: true
          },
          "punctuation": /[(){};:,]/
        };
        Prism3.languages.css["atrule"].inside.rest = Prism3.languages.css;
        var markup = Prism3.languages.markup;
        if (markup) {
          markup.tag.addInlined("style", "css");
          markup.tag.addAttribute("style", "css");
        }
      })(Prism2);
      Prism2.languages.clike = {
        "comment": [
          {
            pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
            lookbehind: true,
            greedy: true
          },
          {
            pattern: /(^|[^\\:])\/\/.*/,
            lookbehind: true,
            greedy: true
          }
        ],
        "string": {
          pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
          greedy: true
        },
        "class-name": {
          pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
          lookbehind: true,
          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": /[{}[\];(),.:]/
      };
      Prism2.languages.javascript = Prism2.languages.extend("clike", {
        "class-name": [
          Prism2.languages.clike["class-name"],
          {
            pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
            lookbehind: true
          }
        ],
        "keyword": [
          {
            pattern: /((?:^|\})\s*)catch\b/,
            lookbehind: true
          },
          {
            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: true
          }
        ],
        // 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: true
        },
        "operator": /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
      });
      Prism2.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
      Prism2.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: true,
          greedy: true,
          inside: {
            "regex-source": {
              pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
              lookbehind: true,
              alias: "language-regex",
              inside: Prism2.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: true,
            inside: Prism2.languages.javascript
          },
          {
            pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
            lookbehind: true,
            inside: Prism2.languages.javascript
          },
          {
            pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
            lookbehind: true,
            inside: Prism2.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: true,
            inside: Prism2.languages.javascript
          }
        ],
        "constant": /\b[A-Z](?:[A-Z_]|\dx?)*\b/
      });
      Prism2.languages.insertBefore("javascript", "string", {
        "hashbang": {
          pattern: /^#!.*/,
          greedy: true,
          alias: "comment"
        },
        "template-string": {
          pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
          greedy: true,
          inside: {
            "template-punctuation": {
              pattern: /^`|`$/,
              alias: "string"
            },
            "interpolation": {
              pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
              lookbehind: true,
              inside: {
                "interpolation-punctuation": {
                  pattern: /^\$\{|\}$/,
                  alias: "punctuation"
                },
                rest: Prism2.languages.javascript
              }
            },
            "string": /[\s\S]+/
          }
        },
        "string-property": {
          pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
          lookbehind: true,
          greedy: true,
          alias: "property"
        }
      });
      Prism2.languages.insertBefore("javascript", "operator", {
        "literal-property": {
          pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
          lookbehind: true,
          alias: "property"
        }
      });
      if (Prism2.languages.markup) {
        Prism2.languages.markup.tag.addInlined("script", "javascript");
        Prism2.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"
        );
      }
      Prism2.languages.js = Prism2.languages.javascript;
      (function() {
        if (typeof Prism2 === "undefined" || typeof document === "undefined") {
          return;
        }
        if (!Element.prototype.matches) {
          Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
        }
        var LOADING_MESSAGE = "Loading…";
        var FAILURE_MESSAGE = function(status, message2) {
          return "✖ Error " + status + " while fetching file: " + message2;
        };
        var FAILURE_EMPTY_MESSAGE = "✖ Error: File does not exist or is empty";
        var EXTENSIONS = {
          "js": "javascript",
          "py": "python",
          "rb": "ruby",
          "ps1": "powershell",
          "psm1": "powershell",
          "sh": "bash",
          "bat": "batch",
          "h": "c",
          "tex": "latex"
        };
        var STATUS_ATTR = "data-src-status";
        var STATUS_LOADING = "loading";
        var STATUS_LOADED = "loaded";
        var STATUS_FAILED = "failed";
        var SELECTOR = "pre[data-src]:not([" + STATUS_ATTR + '="' + STATUS_LOADED + '"]):not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
        function loadFile(src, success, error2) {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", src, true);
          xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
              if (xhr.status < 400 && xhr.responseText) {
                success(xhr.responseText);
              } else {
                if (xhr.status >= 400) {
                  error2(FAILURE_MESSAGE(xhr.status, xhr.statusText));
                } else {
                  error2(FAILURE_EMPTY_MESSAGE);
                }
              }
            }
          };
          xhr.send(null);
        }
        function parseRange(range) {
          var m = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || "");
          if (m) {
            var start = Number(m[1]);
            var comma = m[2];
            var end = m[3];
            if (!comma) {
              return [start, start];
            }
            if (!end) {
              return [start, void 0];
            }
            return [start, Number(end)];
          }
          return void 0;
        }
        Prism2.hooks.add("before-highlightall", function(env) {
          env.selector += ", " + SELECTOR;
        });
        Prism2.hooks.add("before-sanity-check", function(env) {
          var pre = (
            /** @type {HTMLPreElement} */
            env.element
          );
          if (pre.matches(SELECTOR)) {
            env.code = "";
            pre.setAttribute(STATUS_ATTR, STATUS_LOADING);
            var code2 = pre.appendChild(document.createElement("CODE"));
            code2.textContent = LOADING_MESSAGE;
            var src = pre.getAttribute("data-src");
            var language2 = env.language;
            if (language2 === "none") {
              var extension = (/\.(\w+)$/.exec(src) || [, "none"])[1];
              language2 = EXTENSIONS[extension] || extension;
            }
            Prism2.util.setLanguage(code2, language2);
            Prism2.util.setLanguage(pre, language2);
            var autoloader = Prism2.plugins.autoloader;
            if (autoloader) {
              autoloader.loadLanguages(language2);
            }
            loadFile(
              src,
              function(text2) {
                pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
                var range = parseRange(pre.getAttribute("data-range"));
                if (range) {
                  var lines = text2.split(/\r\n?|\n/g);
                  var start = range[0];
                  var end = range[1] == null ? lines.length : range[1];
                  if (start < 0) {
                    start += lines.length;
                  }
                  start = Math.max(0, Math.min(start - 1, lines.length));
                  if (end < 0) {
                    end += lines.length;
                  }
                  end = Math.max(0, Math.min(end, lines.length));
                  text2 = lines.slice(start, end).join("\n");
                  if (!pre.hasAttribute("data-start")) {
                    pre.setAttribute("data-start", String(start + 1));
                  }
                }
                code2.textContent = text2;
                Prism2.highlightElement(code2);
              },
              function(error2) {
                pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
                code2.textContent = error2;
              }
            );
          }
        });
        Prism2.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 highlight(container2) {
            var elements = (container2 || document).querySelectorAll(SELECTOR);
            for (var i2 = 0, element; element = elements[i2++]; ) {
              Prism2.highlightElement(element);
            }
          }
        };
        var logged = false;
        Prism2.fileHighlight = function() {
          if (!logged) {
            console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.");
            logged = true;
          }
          Prism2.plugins.fileHighlight.highlight.apply(this, arguments);
        };
      })();
    })(prism);
    var prismExports = prism.exports;
    (function(Prism2) {
      var envVars = "\\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";
      var commandAfterHeredoc = {
        pattern: /(^(["']?)\w+\2)[ \t]+\S.*/,
        lookbehind: true,
        alias: "punctuation",
        // this looks reasonably well in all themes
        inside: null
        // see below
      };
      var insideString = {
        "bash": commandAfterHeredoc,
        "environment": {
          pattern: RegExp("\\$" + envVars),
          alias: "constant"
        },
        "variable": [
          // [0]: Arithmetic Environment
          {
            pattern: /\$?\(\([\s\S]+?\)\)/,
            greedy: true,
            inside: {
              // If there is a $ sign at the beginning highlight $(( and )) as variable
              "variable": [
                {
                  pattern: /(^\$\(\([\s\S]+)\)\)/,
                  lookbehind: true
                },
                /^\$\(\(/
              ],
              "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: true,
            inside: {
              "variable": /^\$\(|^`|\)$|`$/
            }
          },
          // [2]: Brace expansion
          {
            pattern: /\$\{[^}]+\}/,
            greedy: true,
            inside: {
              "operator": /:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,
              "punctuation": /[\[\]]/,
              "environment": {
                pattern: RegExp("(\\{)" + envVars),
                lookbehind: true,
                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})/
      };
      Prism2.languages.bash = {
        "shebang": {
          pattern: /^#!\s*\/.*/,
          alias: "important"
        },
        "comment": {
          pattern: /(^|[^"{\\$])#.*/,
          lookbehind: true
        },
        "function-name": [
          // a) function foo {
          // b) foo() {
          // c) function foo() {
          // but not “foo {”
          {
            // a) and c)
            pattern: /(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,
            lookbehind: true,
            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: true
        },
        // Highlight variable names as variables in the left-hand part
        // of assignments (“=” and “+=”).
        "assign-left": {
          pattern: /(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,
          inside: {
            "environment": {
              pattern: RegExp("(^|[\\s;|&]|[<>]\\()" + envVars),
              lookbehind: true,
              alias: "constant"
            }
          },
          alias: "variable",
          lookbehind: true
        },
        // Highlight parameter names as variables
        "parameter": {
          pattern: /(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,
          alias: "variable",
          lookbehind: true
        },
        "string": [
          // Support for Here-documents https://en.wikipedia.org/wiki/Here_document
          {
            pattern: /((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,
            lookbehind: true,
            greedy: true,
            inside: insideString
          },
          // Here-document with quotes around the tag
          // → No expansion (so no “inside”).
          {
            pattern: /((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,
            lookbehind: true,
            greedy: true,
            inside: {
              "bash": commandAfterHeredoc
            }
          },
          // “Normal” string
          {
            // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
            pattern: /(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,
            lookbehind: true,
            greedy: true,
            inside: insideString
          },
          {
            // https://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html
            pattern: /(^|[^$\\])'[^']*'/,
            lookbehind: true,
            greedy: true
          },
          {
            // https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
            pattern: /\$'(?:[^'\\]|\\[\s\S])*'/,
            greedy: true,
            inside: {
              "entity": insideString.entity
            }
          }
        ],
        "environment": {
          pattern: RegExp("\\$?" + envVars),
          alias: "constant"
        },
        "variable": insideString.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: true
        },
        "keyword": {
          pattern: /(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,
          lookbehind: true
        },
        // 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: true,
          // Alias added to make those easier to distinguish from strings.
          alias: "class-name"
        },
        "boolean": {
          pattern: /(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,
          lookbehind: true
        },
        "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: true
        }
      };
      commandAfterHeredoc.inside = Prism2.languages.bash;
      var toBeCopied = [
        "comment",
        "function-name",
        "for-or-select",
        "assign-left",
        "parameter",
        "string",
        "environment",
        "function",
        "keyword",
        "builtin",
        "boolean",
        "file-descriptor",
        "operator",
        "punctuation",
        "number"
      ];
      var inside2 = insideString.variable[1].inside;
      for (var i2 = 0; i2 < toBeCopied.length; i2++) {
        inside2[toBeCopied[i2]] = Prism2.languages.bash[toBeCopied[i2]];
      }
      Prism2.languages.sh = Prism2.languages.bash;
      Prism2.languages.shell = Prism2.languages.bash;
    })(Prism);
    Prism.languages.clike = {
      "comment": [
        {
          pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
          lookbehind: true,
          greedy: true
        },
        {
          pattern: /(^|[^\\:])\/\/.*/,
          lookbehind: true,
          greedy: true
        }
      ],
      "string": {
        pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
        greedy: true
      },
      "class-name": {
        pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
        lookbehind: true,
        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": /[{}[\];(),.:]/
    };
    Prism.languages.javascript = Prism.languages.extend("clike", {
      "class-name": [
        Prism.languages.clike["class-name"],
        {
          pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
          lookbehind: true
        }
      ],
      "keyword": [
        {
          pattern: /((?:^|\})\s*)catch\b/,
          lookbehind: true
        },
        {
          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: true
        }
      ],
      // 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: true
      },
      "operator": /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
    });
    Prism.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
    Prism.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: true,
        greedy: true,
        inside: {
          "regex-source": {
            pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
            lookbehind: true,
            alias: "language-regex",
            inside: Prism.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: true,
          inside: Prism.languages.javascript
        },
        {
          pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
          lookbehind: true,
          inside: Prism.languages.javascript
        },
        {
          pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
          lookbehind: true,
          inside: Prism.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: true,
          inside: Prism.languages.javascript
        }
      ],
      "constant": /\b[A-Z](?:[A-Z_]|\dx?)*\b/
    });
    Prism.languages.insertBefore("javascript", "string", {
      "hashbang": {
        pattern: /^#!.*/,
        greedy: true,
        alias: "comment"
      },
      "template-string": {
        pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
        greedy: true,
        inside: {
          "template-punctuation": {
            pattern: /^`|`$/,
            alias: "string"
          },
          "interpolation": {
            pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
            lookbehind: true,
            inside: {
              "interpolation-punctuation": {
                pattern: /^\$\{|\}$/,
                alias: "punctuation"
              },
              rest: Prism.languages.javascript
            }
          },
          "string": /[\s\S]+/
        }
      },
      "string-property": {
        pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
        lookbehind: true,
        greedy: true,
        alias: "property"
      }
    });
    Prism.languages.insertBefore("javascript", "operator", {
      "literal-property": {
        pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
        lookbehind: true,
        alias: "property"
      }
    });
    if (Prism.languages.markup) {
      Prism.languages.markup.tag.addInlined("script", "javascript");
      Prism.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"
      );
    }
    Prism.languages.js = Prism.languages.javascript;
    Prism.languages.json = {
      "property": {
        pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
        lookbehind: true,
        greedy: true
      },
      "string": {
        pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
        lookbehind: true,
        greedy: true
      },
      "comment": {
        pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
        greedy: true
      },
      "number": /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
      "punctuation": /[{}[\],]/,
      "operator": /:/,
      "boolean": /\b(?:false|true)\b/,
      "null": {
        pattern: /\bnull\b/,
        alias: "keyword"
      }
    };
    Prism.languages.webmanifest = Prism.languages.json;
    Prism.languages.python = {
      "comment": {
        pattern: /(^|[^\\])#.*/,
        lookbehind: true,
        greedy: true
      },
      "string-interpolation": {
        pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
        greedy: true,
        inside: {
          "interpolation": {
            // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
            pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
            lookbehind: true,
            inside: {
              "format-spec": {
                pattern: /(:)[^:(){}]+(?=\}$)/,
                lookbehind: true
              },
              "conversion-option": {
                pattern: /![sra](?=[:}]$)/,
                alias: "punctuation"
              },
              rest: null
            }
          },
          "string": /[\s\S]+/
        }
      },
      "triple-quoted-string": {
        pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
        greedy: true,
        alias: "string"
      },
      "string": {
        pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
        greedy: true
      },
      "function": {
        pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
        lookbehind: true
      },
      "class-name": {
        pattern: /(\bclass\s+)\w+/i,
        lookbehind: true
      },
      "decorator": {
        pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
        lookbehind: true,
        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;
    const loggingIcons = {
      notset: "bi bi-card-text",
      debug: "bi bi-bug",
      http: "bi bi-download",
      info: "bi bi-info-square",
      warning: "bi bi-exclamation-triangle",
      error: "bi bi-x-circle",
      critical: "bi bi-fire"
    };
    const ApplicationIcons = {
      approve: "bi bi-shield",
      approvals: {
        approve: "bi bi-shield-check",
        reject: "bi bi-shield-x",
        terminate: "bi bi-shield-exclamation",
        escalate: "bi bi-box-arrow-up",
        modify: "bi bi-pencil-square"
      },
      arrows: {
        right: "bi bi-arrow-right",
        down: "bi bi-arrow-down",
        up: "bi bi-arrow-up"
      },
      chevron: {
        right: "bi bi-chevron-right",
        down: "bi bi-chevron-down"
      },
      collapse: {
        up: "bi bi-chevron-up"
      },
      close: "bi bi-x",
      config: "bi bi-gear",
      confirm: "bi bi-check",
      copy: "bi bi-copy",
      error: "bi bi-exclamation-circle",
      "expand-down": "bi bi-chevron-down",
      info: "bi bi-info-circle",
      input: "bi bi-terminal",
      limits: {
        messages: "bi bi-chat-right-text",
        custom: "bi bi-person-workspace",
        operator: "bi bi-person-workspace",
        tokens: "bi bi-list",
        time: "bi bi-clock",
        execution: "bi bi-stopwatch"
      },
      logging: loggingIcons,
      menu: "bi bi-list",
      metadata: "bi bi-table",
      model: "bi bi-grid-3x3-gap",
      next: "bi bi-chevron-right",
      play: "bi bi-play-fill",
      previous: "bi bi-chevron-left",
      refresh: "bi bi-arrow-clockwise",
      role: {
        user: "bi bi-person",
        system: "bi bi-cpu",
        assistant: "bi bi-robot",
        tool: "bi bi-tools",
        unknown: "bi bi-patch-question"
      },
      running: "bi bi-stars",
      sample: "bi bi-database",
      sandbox: "bi bi-box-seam",
      scorer: "bi bi-calculator",
      search: "bi bi-search",
      solvers: {
        use_tools: "bi bi-tools"
      },
      usage: "bi bi-stopwatch"
    };
    const ErrorPanel = ({ title: title2, error: error2 }) => {
      const message2 = error2.message;
      const stack2 = error2.stack;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "error-panel centered-flex", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "error-panel-heading centered-flex", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: `${ApplicationIcons.error} error-icon` }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: title2 || "" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "error-panel-body", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          "Error: ",
          message2 || "",
          stack2 && error2.displayStack !== false && /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "error-panel-stack", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("code", { children: [
            "at ",
            stack2
          ] }) })
        ] }) })
      ] });
    };
    class AppErrorBoundary extends reactExports.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
      static getDerivedStateFromError(error2) {
        return { hasError: true, error: error2 };
      }
      componentDidCatch(error2, errorInfo) {
        console.log({ error: error2, errorInfo });
      }
      render() {
        if (this.state.hasError) {
          console.error({ e: this.state.error });
          if (this.state.error) {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              ErrorPanel,
              {
                title: "An unexpected error occurred.",
                error: this.state.error
              }
            );
          } else {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "An unknown error with no additional information occured." });
          }
        }
        return this.props.children;
      }
    }
    const wrapper$4 = "_wrapper_1phwy_1";
    const container$d = "_container_1phwy_13";
    const animate = "_animate_1phwy_21";
    const styles$17 = {
      wrapper: wrapper$4,
      container: container$d,
      animate
    };
    const ProgressBar = ({ animating }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$17.wrapper, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: styles$17.container,
          role: "progressbar",
          "aria-label": "Basic example",
          "aria-valuenow": 25,
          "aria-valuemin": 0,
          "aria-valuemax": 100,
          children: animating && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$17.animate })
        }
      ) });
    };
    const clearDocumentSelection = () => {
      const sel = window.getSelection();
      if (sel) {
        if (sel.removeAllRanges) {
          sel.removeAllRanges();
        } else if (sel.empty) {
          sel.empty();
        }
      }
    };
    function sleep$1(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }
    function throttle$1(func, wait, options2 = {}) {
      let context;
      let args;
      let result2;
      let timeout = null;
      let previous = 0;
      const later = function() {
        previous = options2.leading === false ? 0 : Date.now();
        timeout = null;
        result2 = func.apply(context, args === null ? [] : args);
        if (!timeout) {
          context = null;
          args = null;
        }
      };
      return function(...callArgs) {
        const now2 = Date.now();
        if (!previous && options2.leading === false) {
          previous = now2;
        }
        const remaining = wait - (now2 - previous);
        context = this;
        args = callArgs;
        if (remaining <= 0 || remaining > wait) {
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          previous = now2;
          result2 = func.apply(context, args);
          if (!timeout) {
            context = null;
            args = null;
          }
        } else if (!timeout && options2.trailing !== false) {
          timeout = setTimeout(later, remaining);
        }
        return result2;
      };
    }
    function debounce$1(func, wait, options2 = {}) {
      let timeout = null;
      let context;
      let args;
      let result2;
      let lastCallTime = null;
      const later = () => {
        const last = Date.now() - (lastCallTime || 0);
        if (last < wait && last >= 0) {
          timeout = setTimeout(later, wait - last);
        } else {
          timeout = null;
          if (!options2.leading) {
            result2 = func.apply(context, args);
            if (!timeout) {
              context = null;
              args = null;
            }
          }
        }
      };
      return function(...callArgs) {
        context = this;
        args = callArgs;
        lastCallTime = Date.now();
        const callNow = options2.leading && !timeout;
        if (!timeout) {
          timeout = setTimeout(later, wait);
        }
        if (callNow) {
          result2 = func.apply(context, args);
          context = null;
          args = null;
        }
        return result2;
      };
    }
    const FindBand = ({ hideBand }) => {
      const searchBoxRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        setTimeout(() => {
          var _a2;
          (_a2 = searchBoxRef.current) == null ? void 0 : _a2.focus();
        }, 10);
      }, []);
      const getParentExpandablePanel = reactExports.useCallback(
        (selection) => {
          let node2 = selection.anchorNode;
          while (node2) {
            if (node2 instanceof HTMLElement && node2.classList.contains("expandable-panel")) {
              return node2;
            }
            node2 = node2.parentElement;
          }
          return void 0;
        },
        []
      );
      const handleSearch = reactExports.useCallback(
        (back = false) => {
          var _a2;
          const searchTerm = ((_a2 = searchBoxRef.current) == null ? void 0 : _a2.value) ?? "";
          const focusedElement = document.activeElement;
          const result2 = window.find(
            searchTerm,
            false,
            back,
            false,
            false,
            true,
            false
          );
          const noResultEl = document.getElementById("inspect-find-no-results");
          if (!noResultEl) return;
          noResultEl.style.opacity = result2 ? "0" : "1";
          if (result2) {
            const selection = window.getSelection();
            if (selection && selection.rangeCount > 0) {
              const parentPanel = getParentExpandablePanel(selection);
              if (parentPanel) {
                parentPanel.style.display = "block";
                parentPanel.style.webkitLineClamp = "";
                parentPanel.style.webkitBoxOrient = "";
              }
              const range = selection.getRangeAt(0);
              const element = range.startContainer.parentElement;
              if (element) {
                setTimeout(() => {
                  element.scrollIntoView({
                    behavior: "smooth",
                    block: "center"
                  });
                }, 100);
              }
            }
          }
          focusedElement == null ? void 0 : focusedElement.focus();
        },
        [getParentExpandablePanel]
      );
      const handleKeyDown = reactExports.useCallback(
        (e) => {
          if (e.key === "Escape") {
            hideBand();
          } else if (e.key === "Enter") {
            handleSearch(false);
          }
        },
        [hideBand, handleSearch]
      );
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "findBand", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            type: "text",
            ref: searchBoxRef,
            placeholder: "Find",
            onKeyDown: handleKeyDown
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { id: "inspect-find-no-results", children: "No results" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            title: "Previous match",
            className: "btn next",
            onClick: () => handleSearch(true),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.arrows.up })
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            title: "Next match",
            className: "btn prev",
            onClick: () => handleSearch(false),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.arrows.down })
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            title: "Close",
            className: "btn close",
            onClick: hideBand,
            children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.close })
          }
        )
      ] });
    };
    const kModelNone = "none/none";
    const kEvalWorkspaceTabId = "eval-tab";
    const kJsonWorkspaceTabId = "json-tab";
    const kInfoWorkspaceTabId = "plan-tab";
    const kSampleMessagesTabId = `sample-display-messages`;
    const kSampleTranscriptTabId = `sample-display-transcript`;
    const kSampleScoringTabId = `sample-display-scoring`;
    const kSampleMetdataTabId = `sample-display-metadata`;
    const kSampleErrorTabId = `sample-display-error`;
    const kSampleJsonTabId = `sample-display-json`;
    const kScoreTypePassFail = "passfail";
    const kScoreTypeCategorical = "categorical";
    const kScoreTypeNumeric = "numeric";
    const kScoreTypeOther = "other";
    const kScoreTypeObject = "object";
    const kScoreTypeBoolean = "boolean";
    const kSampleAscVal = "sample-asc";
    const kSampleDescVal = "sample-desc";
    const kEpochAscVal = "epoch-asc";
    const kEpochDescVal = "epoch-desc";
    const kScoreAscVal = "score-asc";
    const kScoreDescVal = "score-desc";
    const kDefaultSort = kSampleAscVal;
    const arrayToString = (val) => {
      val = Array.isArray(val) ? val : [val];
      return val.join(", ");
    };
    const inputString = (input2) => {
      if (typeof input2 === "string") {
        return [input2];
      } else {
        return input2.map((inp) => {
          if (typeof inp === "string") {
            return inp;
          } else {
            const content2 = inp.content;
            if (typeof content2 === "string") {
              return content2;
            } else {
              const result2 = content2.map((con) => {
                if (con.type === "text") {
                  return con.text;
                } else {
                  return "";
                }
              });
              return result2.join("\n");
            }
          }
        });
      }
    };
    const formatDataset = (samples, epochs, name2) => {
      const perEpochSamples = epochs > 0 ? samples / epochs : samples;
      const namePrefix = name2 ? `${name2} — ` : "";
      const terms = [
        namePrefix,
        String(perEpochSamples),
        epochs > 1 ? `x ${epochs} ` : "",
        samples === 1 ? "sample" : "samples"
      ];
      return terms.join(" ");
    };
    const formatTime$1 = (seconds) => {
      if (seconds < 60) {
        return `${formatPrettyDecimal(seconds, 1)} sec`;
      } else if (seconds < 60 * 60) {
        return `${Math.floor(seconds / 60)} min ${Math.floor(seconds % 60)} sec`;
      } else if (seconds < 60 * 60 * 24) {
        const hours = Math.floor(seconds / (60 * 60));
        const minutes = Math.floor(seconds % (60 * 60) / 60);
        const remainingSeconds = seconds % 60;
        return `${hours} hr ${minutes} min ${remainingSeconds} sec`;
      } else {
        const days = Math.floor(seconds / (60 * 60 * 24));
        const hours = Math.floor(seconds % (60 * 60 * 24) / (60 * 60));
        const minutes = Math.floor(seconds % (60 * 60) / 60);
        const remainingSeconds = seconds % 60;
        return `${days} days ${hours} hr ${minutes} min ${remainingSeconds} sec`;
      }
    };
    function formatPrettyDecimal(num2, maxDecimals = 3) {
      const numDecimalPlaces = num2.toString().includes(".") ? num2.toString().split(".")[1].length : 0;
      if (numDecimalPlaces === 0) {
        return num2.toFixed(1);
      } else if (numDecimalPlaces > maxDecimals) {
        return num2.toFixed(maxDecimals);
      } else {
        return num2.toString();
      }
    }
    function formatDecimalNoTrailingZeroes(num2) {
      if (typeof num2 !== "number") {
        return num2;
      }
      if (num2.toString().includes(".")) {
        const decimal = num2.toString().split(".")[1];
        const trimmed = decimal.replace(/\.?0+$/, "");
        return num2.toFixed(trimmed.length);
      } else {
        return num2.toFixed(0);
      }
    }
    function toTitleCase(str2) {
      return str2.split(" ").map((w2) => w2[0].toUpperCase() + w2.substr(1).toLowerCase()).join(" ");
    }
    function formatNoDecimal(num2) {
      if (typeof num2 !== "number") {
        return num2;
      }
      const rounded = Math.round(num2);
      return rounded.toFixed(0);
    }
    function formatNumber(num2) {
      return num2.toLocaleString(navigator.language, {
        minimumFractionDigits: 0,
        maximumFractionDigits: 5
      });
    }
    function formatDateTime(date) {
      const options2 = {
        year: "2-digit",
        month: "2-digit",
        day: "2-digit",
        hour: "numeric",
        minute: "2-digit",
        second: "2-digit",
        hour12: true
      };
      return new Intl.DateTimeFormat(void 0, options2).format(date);
    }
    function formatDuration(start, end) {
      const durationMs = end.getTime() - start.getTime();
      const durationSec = durationMs / 1e3;
      return formatTime$1(durationSec);
    }
    function r(e) {
      var t2, f, n = "";
      if ("string" == typeof e || "number" == typeof e) n += e;
      else if ("object" == typeof e) if (Array.isArray(e)) {
        var o = e.length;
        for (t2 = 0; t2 < o; t2++) e[t2] && (f = r(e[t2])) && (n && (n += " "), n += f);
      } else for (f in e) e[f] && (n && (n += " "), n += f);
      return n;
    }
    function clsx() {
      for (var e, t2, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t2 = r(e)) && (n && (n += " "), n += t2);
      return n;
    }
    const circle$1 = "_circle_upui3_1";
    const styles$16 = {
      circle: circle$1
    };
    const booleanScoreDescriptor = () => {
      return {
        scoreType: "boolean",
        compare: (a, b) => {
          return Number(a.value) - Number(b.value);
        },
        render: (score2) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: clsx(
                styles$16.circle,
                "text-size-small",
                score2 ? "green" : "red"
              ),
              children: String(score2)
            }
          );
        }
      };
    };
    const categoricalScoreDescriptor = (values) => {
      return {
        scoreType: kScoreTypeCategorical,
        categories: values,
        compare: (a, b) => {
          return String(a.value).localeCompare(String(b.value));
        },
        render: (score2) => {
          return String(score2);
        }
      };
    };
    const numericScoreDescriptor = (values) => {
      const onlyNumeric = values.filter((val) => {
        return typeof val === "number";
      });
      return {
        scoreType: kScoreTypeNumeric,
        min: Math.min(...onlyNumeric),
        max: Math.max(...onlyNumeric),
        compare: (a, b) => {
          if (typeof a.value === "number" && typeof b.value === "number") {
            return a.value - b.value;
          } else {
            console.warn("Comparing non-numerics using a numeric score descriptor");
            return 0;
          }
        },
        render: (score2) => {
          return formatDecimalNoTrailingZeroes(Number(score2));
        }
      };
    };
    const isNumeric = (n) => {
      return !isNaN(parseFloat(n)) && isFinite(n);
    };
    const toArray = (val) => {
      if (Array.isArray(val)) {
        return val;
      } else {
        return [val];
      }
    };
    const container$c = "_container_w37fs_1";
    const padded$2 = "_padded_w37fs_8";
    const key$1 = "_key_w37fs_12";
    const value$1 = "_value_w37fs_16";
    const styles$15 = {
      container: container$c,
      padded: padded$2,
      key: key$1,
      value: value$1
    };
    const objectScoreDescriptor = (values) => {
      const buckets = values.map((val) => {
        return JSON.stringify(val);
      });
      const vals = new Set(buckets);
      let categories = void 0;
      if (vals.size < 10) {
        categories = Array.from(vals).map((val) => {
          return {
            val,
            text: val
          };
        });
      }
      return {
        scoreType: kScoreTypeObject,
        categories,
        compare: () => {
          return 0;
        },
        render: (score2) => {
          if (score2 === null || score2 === void 0) {
            return "[null]";
          }
          const scores2 = [];
          const keys = Object.keys(score2);
          keys.forEach((key2, index2) => {
            if (typeof score2 !== "object" || Array.isArray(score2)) {
              throw new Error(
                "Unexpected us of object score descriptor for non-score object"
              );
            }
            const value2 = score2[key2];
            const formattedValue = value2 && isNumeric(value2) ? formatPrettyDecimal(
              typeof value2 === "number" ? value2 : parseFloat(value2 === true ? "1" : value2)
            ) : String(value2);
            scores2.push(
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  className: clsx(
                    styles$15.container,
                    index2 + 1 < keys.length ? styles$15.padded : void 0
                  ),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$15.key, "text-size-smaller"), children: key2 }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$15.value, "text-size-title"), children: formattedValue })
                  ]
                }
              )
            );
          });
          return scores2;
        }
      };
    };
    function commonjsRequire(path) {
      throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
    }
    var ansiOutput = { exports: {} };
    (function(module2, exports2) {
      (function(factory) {
        {
          var v = factory(commonjsRequire, exports2);
          if (v !== void 0) module2.exports = v;
        }
      })(function(require2, exports3) {
        Object.defineProperty(exports3, "__esModule", { value: true });
        exports3.ANSIOutput = exports3.ANSIColor = exports3.ANSIFont = exports3.ANSIStyle = void 0;
        let counter = 0;
        const generateId = () => {
          return `${++counter}`.padStart(16, "0");
        };
        var ANSIStyle;
        (function(ANSIStyle2) {
          ANSIStyle2["Bold"] = "ansiBold";
          ANSIStyle2["Dim"] = "ansiDim";
          ANSIStyle2["Italic"] = "ansiItalic";
          ANSIStyle2["Underlined"] = "ansiUnderlined";
          ANSIStyle2["SlowBlink"] = "ansiSlowBlink";
          ANSIStyle2["RapidBlink"] = "ansiRapidBlink";
          ANSIStyle2["Hidden"] = "ansiHidden";
          ANSIStyle2["CrossedOut"] = "ansiCrossedOut";
          ANSIStyle2["Fraktur"] = "ansiFraktur";
          ANSIStyle2["DoubleUnderlined"] = "ansiDoubleUnderlined";
          ANSIStyle2["Framed"] = "ansiFramed";
          ANSIStyle2["Encircled"] = "ansiEncircled";
          ANSIStyle2["Overlined"] = "ansiOverlined";
          ANSIStyle2["Superscript"] = "ansiSuperscript";
          ANSIStyle2["Subscript"] = "ansiSubscript";
        })(ANSIStyle || (exports3.ANSIStyle = ANSIStyle = {}));
        var ANSIFont;
        (function(ANSIFont2) {
          ANSIFont2["AlternativeFont1"] = "ansiAlternativeFont1";
          ANSIFont2["AlternativeFont2"] = "ansiAlternativeFont2";
          ANSIFont2["AlternativeFont3"] = "ansiAlternativeFont3";
          ANSIFont2["AlternativeFont4"] = "ansiAlternativeFont4";
          ANSIFont2["AlternativeFont5"] = "ansiAlternativeFont5";
          ANSIFont2["AlternativeFont6"] = "ansiAlternativeFont6";
          ANSIFont2["AlternativeFont7"] = "ansiAlternativeFont7";
          ANSIFont2["AlternativeFont8"] = "ansiAlternativeFont8";
          ANSIFont2["AlternativeFont9"] = "ansiAlternativeFont9";
        })(ANSIFont || (exports3.ANSIFont = ANSIFont = {}));
        var ANSIColor;
        (function(ANSIColor2) {
          ANSIColor2["Black"] = "ansiBlack";
          ANSIColor2["Red"] = "ansiRed";
          ANSIColor2["Green"] = "ansiGreen";
          ANSIColor2["Yellow"] = "ansiYellow";
          ANSIColor2["Blue"] = "ansiBlue";
          ANSIColor2["Magenta"] = "ansiMagenta";
          ANSIColor2["Cyan"] = "ansiCyan";
          ANSIColor2["White"] = "ansiWhite";
          ANSIColor2["BrightBlack"] = "ansiBrightBlack";
          ANSIColor2["BrightRed"] = "ansiBrightRed";
          ANSIColor2["BrightGreen"] = "ansiBrightGreen";
          ANSIColor2["BrightYellow"] = "ansiBrightYellow";
          ANSIColor2["BrightBlue"] = "ansiBrightBlue";
          ANSIColor2["BrightMagenta"] = "ansiBrightMagenta";
          ANSIColor2["BrightCyan"] = "ansiBrightCyan";
          ANSIColor2["BrightWhite"] = "ansiBrightWhite";
        })(ANSIColor || (exports3.ANSIColor = ANSIColor = {}));
        class ANSIOutput {
          constructor() {
            //#region Private Properties
            /**
             * Gets or sets the parser state.
             */
            __publicField(this, "_parserState", ParserState.BufferingOutput);
            /**
             * Gets or sets the control sequence that's being parsed.
             */
            __publicField(this, "_controlSequence", "");
            /**
             * Gets or sets the SGR state.
             */
            __publicField(this, "_sgrState");
            /**
             * Gets or sets the current set of output lines.
             */
            __publicField(this, "_outputLines", []);
            /**
             * Gets or sets the output line.
             */
            __publicField(this, "_outputLine", 0);
            /**
             * Gets or sets the output column.
             */
            __publicField(this, "_outputColumn", 0);
            /**
             * Gets or sets the buffer.
             */
            __publicField(this, "_buffer", "");
            /**
             * Gets or sets a value which indicates whether there is a pending newline.
             */
            __publicField(this, "_pendingNewline", false);
          }
          //#endregion Private Properties
          //#region Public Properties
          /**
           * Gets the output lines.
           */
          get outputLines() {
            this.flushBuffer();
            return this._outputLines;
          }
          //#endregion Public Properties
          //#region Public Static Methods
          /**
           * Processes output and returns the ANSIOutput lines of the output.
           * @param output The output to process.
           * @returns The ANSIOutput lines of the output.
           */
          static processOutput(output2) {
            const ansiOutput2 = new ANSIOutput();
            ansiOutput2.processOutput(output2);
            return ansiOutput2.outputLines;
          }
          //#endregion Public Static Methods
          //#region Public Methods
          /**
           * Processes output.
           * @param output The output to process.
           */
          processOutput(output2) {
            for (let i2 = 0; i2 < output2.length; i2++) {
              if (this._pendingNewline) {
                this.flushBuffer();
                this._outputLine++;
                this._outputColumn = 0;
                this._pendingNewline = false;
              }
              const char = output2.charAt(i2);
              if (this._parserState === ParserState.BufferingOutput) {
                if (char === "\x1B") {
                  this.flushBuffer();
                  this._parserState = ParserState.ControlSequenceStarted;
                } else if (char === "") {
                  this.flushBuffer();
                  this._parserState = ParserState.ParsingControlSequence;
                } else {
                  this.processCharacter(char);
                }
              } else if (this._parserState === ParserState.ControlSequenceStarted) {
                if (char === "[") {
                  this._parserState = ParserState.ParsingControlSequence;
                } else {
                  this._parserState = ParserState.BufferingOutput;
                  this.processCharacter(char);
                }
              } else if (this._parserState === ParserState.ParsingControlSequence) {
                this._controlSequence += char;
                if (char.match(/^[A-Za-z]$/)) {
                  this.processControlSequence();
                }
              }
            }
            this.flushBuffer();
          }
          //#endregion Public Methods
          //#region Private Methods
          /**
           * Flushes the buffer to the output line.
           */
          flushBuffer() {
            for (let i2 = this._outputLines.length; i2 < this._outputLine + 1; i2++) {
              this._outputLines.push(new OutputLine());
            }
            if (this._buffer) {
              const outputLine = this._outputLines[this._outputLine];
              outputLine.insert(this._buffer, this._outputColumn, this._sgrState);
              this._outputColumn += this._buffer.length;
              this._buffer = "";
            }
          }
          /**
           * Processes a character.
           * @param char The character.
           */
          processCharacter(char) {
            switch (char) {
              case "\n":
                this._pendingNewline = true;
                break;
              case "\r":
                this.flushBuffer();
                this._outputColumn = 0;
                break;
              default:
                this._buffer += char;
                break;
            }
          }
          /**
           * Processes a control sequence.
           */
          processControlSequence() {
            switch (this._controlSequence.charAt(this._controlSequence.length - 1)) {
              case "A":
                this.processCUU();
                break;
              case "B":
                this.processCUD();
                break;
              case "C":
                this.processCUF();
                break;
              case "D":
                this.processCUB();
                break;
              case "H":
                this.processCUP();
                break;
              case "J":
                this.processED();
                break;
              case "K":
                this.processEL();
                break;
              case "m":
                this.processSGR();
                break;
            }
            this._controlSequence = "";
            this._parserState = ParserState.BufferingOutput;
          }
          /**
           * Processes a CUU (Cursor Up) control sequence.
           */
          processCUU() {
            const match = this._controlSequence.match(/^([0-9]*)A$/);
            if (match) {
              this._outputLine = Math.max(this._outputLine - rangeParam(match[1], 1, 1), 0);
            }
          }
          /**
           * Processes a CUD (Cursor Down) control sequence.
           */
          processCUD() {
            const match = this._controlSequence.match(/^([0-9]*)B$/);
            if (match) {
              this._outputLine = this._outputLine + rangeParam(match[1], 1, 1);
            }
          }
          /**
           * Processes a CUF (Cursor Forward) control sequence.
           */
          processCUF() {
            const match = this._controlSequence.match(/^([0-9]*)C$/);
            if (match) {
              this._outputColumn = this._outputColumn + rangeParam(match[1], 1, 1);
            }
          }
          /**
           * Processes a CUB (Cursor Backward) control sequence.
           */
          processCUB() {
            const match = this._controlSequence.match(/^([0-9]*)D$/);
            if (match) {
              this._outputColumn = Math.max(this._outputColumn - rangeParam(match[1], 1, 1), 0);
            }
          }
          /**
           * Processes a CUP (Cursor Position) control sequence.
           */
          processCUP() {
            const match = this._controlSequence.match(/^([0-9]*)(?:;?([0-9]*))H$/);
            if (match) {
              this._outputLine = rangeParam(match[1], 1, 1) - 1;
              this._outputColumn = rangeParam(match[2], 1, 1) - 1;
            }
          }
          /**
           * Processes an ED (Erase in Display) control sequence.
           */
          processED() {
            const match = this._controlSequence.match(/^([0-9]*)J$/);
            if (match) {
              switch (getParam(match[1], 0)) {
                case 0:
                  this._outputLines[this._outputLine].clearToEndOfLine(this._outputColumn);
                  for (let i2 = this._outputLine + 1; i2 < this._outputLines.length; i2++) {
                    this._outputLines[i2].clearEntireLine();
                  }
                  break;
                case 1:
                  this._outputLines[this._outputLine].clearToBeginningOfLine(this._outputColumn);
                  for (let i2 = 0; i2 < this._outputLine; i2++) {
                    this._outputLines[i2].clearEntireLine();
                  }
                  break;
                case 2:
                  for (let i2 = 0; i2 < this._outputLines.length; i2++) {
                    this._outputLines[i2].clearEntireLine();
                  }
                  break;
              }
            }
          }
          /**
           * Processes an EL (Erase in Line) control sequence.
           */
          processEL() {
            const match = this._controlSequence.match(/^([0-9]*)K$/);
            if (match) {
              const outputLine = this._outputLines[this._outputLine];
              switch (getParam(match[1], 0)) {
                case 0:
                  outputLine.clearToEndOfLine(this._outputColumn);
                  break;
                case 1:
                  outputLine.clearToBeginningOfLine(this._outputColumn);
                  break;
                case 2:
                  outputLine.clearEntireLine();
                  break;
              }
            }
          }
          /**
           * Processes an SGR (Select Graphic Rendition) control sequence.
           */
          processSGR() {
            const sgrState = this._sgrState ? this._sgrState.copy() : new SGRState();
            const sgrParams = this._controlSequence.slice(0, -1).split(";").map((sgrParam) => sgrParam === "" ? SGRParam.Reset : parseInt(sgrParam, 10));
            for (let index2 = 0; index2 < sgrParams.length; index2++) {
              const sgrParam = sgrParams[index2];
              const processSetColor = () => {
                if (index2 + 1 === sgrParams.length) {
                  return void 0;
                }
                switch (sgrParams[++index2]) {
                  case SGRParamColor.Color256: {
                    if (index2 + 1 === sgrParams.length) {
                      return void 0;
                    }
                    const colorIndex = sgrParams[++index2];
                    switch (colorIndex) {
                      case SGRParamIndexedColor.Black:
                        return ANSIColor.Black;
                      case SGRParamIndexedColor.Red:
                        return ANSIColor.Red;
                      case SGRParamIndexedColor.Green:
                        return ANSIColor.Green;
                      case SGRParamIndexedColor.Yellow:
                        return ANSIColor.Yellow;
                      case SGRParamIndexedColor.Blue:
                        return ANSIColor.Blue;
                      case SGRParamIndexedColor.Magenta:
                        return ANSIColor.Magenta;
                      case SGRParamIndexedColor.Cyan:
                        return ANSIColor.Cyan;
                      case SGRParamIndexedColor.White:
                        return ANSIColor.White;
                      case SGRParamIndexedColor.BrightBlack:
                        return ANSIColor.BrightBlack;
                      case SGRParamIndexedColor.BrightRed:
                        return ANSIColor.BrightRed;
                      case SGRParamIndexedColor.BrightGreen:
                        return ANSIColor.BrightGreen;
                      case SGRParamIndexedColor.BrightYellow:
                        return ANSIColor.BrightYellow;
                      case SGRParamIndexedColor.BrightBlue:
                        return ANSIColor.BrightBlue;
                      case SGRParamIndexedColor.BrightMagenta:
                        return ANSIColor.BrightMagenta;
                      case SGRParamIndexedColor.BrightCyan:
                        return ANSIColor.BrightCyan;
                      case SGRParamIndexedColor.BrightWhite:
                        return ANSIColor.BrightWhite;
                      default:
                        if (colorIndex % 1 !== 0) {
                          return void 0;
                        }
                        if (colorIndex >= 16 && colorIndex <= 231) {
                          let colorNumber = colorIndex - 16;
                          let blue = colorNumber % 6;
                          colorNumber = (colorNumber - blue) / 6;
                          let green2 = colorNumber % 6;
                          colorNumber = (colorNumber - green2) / 6;
                          let red2 = colorNumber;
                          blue = Math.round(blue * 255 / 5);
                          green2 = Math.round(green2 * 255 / 5);
                          red2 = Math.round(red2 * 255 / 5);
                          return "#" + twoDigitHex(red2) + twoDigitHex(green2) + twoDigitHex(blue);
                        } else if (colorIndex >= 232 && colorIndex <= 255) {
                          const rgb = Math.round((colorIndex - 232) / 23 * 255);
                          const grayscale = twoDigitHex(rgb);
                          return "#" + grayscale + grayscale + grayscale;
                        } else {
                          return void 0;
                        }
                    }
                  }
                  case SGRParamColor.ColorRGB: {
                    const rgb = [0, 0, 0];
                    for (let i2 = 0; i2 < 3 && index2 + 1 < sgrParams.length; i2++) {
                      rgb[i2] = sgrParams[++index2];
                    }
                    return "#" + twoDigitHex(rgb[0]) + twoDigitHex(rgb[1]) + twoDigitHex(rgb[2]);
                  }
                }
                return void 0;
              };
              switch (sgrParam) {
                case SGRParam.Reset:
                  sgrState.reset();
                  break;
                case SGRParam.Bold:
                  sgrState.setStyle(ANSIStyle.Bold);
                  break;
                case SGRParam.Dim:
                  sgrState.setStyle(ANSIStyle.Dim);
                  break;
                case SGRParam.Italic:
                  sgrState.setStyle(ANSIStyle.Italic);
                  break;
                case SGRParam.Underlined:
                  sgrState.setStyle(ANSIStyle.Underlined, ANSIStyle.DoubleUnderlined);
                  break;
                case SGRParam.SlowBlink:
                  sgrState.setStyle(ANSIStyle.SlowBlink, ANSIStyle.RapidBlink);
                  break;
                case SGRParam.RapidBlink:
                  sgrState.setStyle(ANSIStyle.RapidBlink, ANSIStyle.SlowBlink);
                  break;
                case SGRParam.Reversed:
                  sgrState.setReversed(true);
                  break;
                case SGRParam.Hidden:
                  sgrState.setStyle(ANSIStyle.Hidden);
                  break;
                case SGRParam.CrossedOut:
                  sgrState.setStyle(ANSIStyle.CrossedOut);
                  break;
                case SGRParam.PrimaryFont:
                  sgrState.setFont();
                  break;
                case SGRParam.AlternativeFont1:
                  sgrState.setFont(ANSIFont.AlternativeFont1);
                  break;
                case SGRParam.AlternativeFont2:
                  sgrState.setFont(ANSIFont.AlternativeFont2);
                  break;
                case SGRParam.AlternativeFont3:
                  sgrState.setFont(ANSIFont.AlternativeFont3);
                  break;
                case SGRParam.AlternativeFont4:
                  sgrState.setFont(ANSIFont.AlternativeFont4);
                  break;
                case SGRParam.AlternativeFont5:
                  sgrState.setFont(ANSIFont.AlternativeFont5);
                  break;
                case SGRParam.AlternativeFont6:
                  sgrState.setFont(ANSIFont.AlternativeFont6);
                  break;
                case SGRParam.AlternativeFont7:
                  sgrState.setFont(ANSIFont.AlternativeFont7);
                  break;
                case SGRParam.AlternativeFont8:
                  sgrState.setFont(ANSIFont.AlternativeFont8);
                  break;
                case SGRParam.AlternativeFont9:
                  sgrState.setFont(ANSIFont.AlternativeFont9);
                  break;
                case SGRParam.Fraktur:
                  sgrState.setStyle(ANSIStyle.Fraktur);
                  break;
                case SGRParam.DoubleUnderlined:
                  sgrState.setStyle(ANSIStyle.DoubleUnderlined, ANSIStyle.Underlined);
                  break;
                case SGRParam.NormalIntensity:
                  sgrState.deleteStyles(ANSIStyle.Bold, ANSIStyle.Dim);
                  break;
                case SGRParam.NotItalicNotFraktur:
                  sgrState.deleteStyles(ANSIStyle.Italic, ANSIStyle.Fraktur);
                  break;
                case SGRParam.NotUnderlined:
                  sgrState.deleteStyles(ANSIStyle.Underlined, ANSIStyle.DoubleUnderlined);
                  break;
                case SGRParam.NotBlinking:
                  sgrState.deleteStyles(ANSIStyle.SlowBlink, ANSIStyle.RapidBlink);
                  break;
                case SGRParam.ProportionalSpacing:
                  break;
                case SGRParam.NotReversed:
                  sgrState.setReversed(false);
                  break;
                case SGRParam.Reveal:
                  sgrState.deleteStyles(ANSIStyle.Hidden);
                  break;
                case SGRParam.NotCrossedOut:
                  sgrState.deleteStyles(ANSIStyle.CrossedOut);
                  break;
                case SGRParam.ForegroundBlack:
                  sgrState.setForegroundColor(ANSIColor.Black);
                  break;
                case SGRParam.ForegroundRed:
                  sgrState.setForegroundColor(ANSIColor.Red);
                  break;
                case SGRParam.ForegroundGreen:
                  sgrState.setForegroundColor(ANSIColor.Green);
                  break;
                case SGRParam.ForegroundYellow:
                  sgrState.setForegroundColor(ANSIColor.Yellow);
                  break;
                case SGRParam.ForegroundBlue:
                  sgrState.setForegroundColor(ANSIColor.Blue);
                  break;
                case SGRParam.ForegroundMagenta:
                  sgrState.setForegroundColor(ANSIColor.Magenta);
                  break;
                case SGRParam.ForegroundCyan:
                  sgrState.setForegroundColor(ANSIColor.Cyan);
                  break;
                case SGRParam.ForegroundWhite:
                  sgrState.setForegroundColor(ANSIColor.White);
                  break;
                case SGRParam.SetForeground: {
                  const foregroundColor = processSetColor();
                  if (foregroundColor) {
                    sgrState.setForegroundColor(foregroundColor);
                  }
                  break;
                }
                case SGRParam.DefaultForeground:
                  sgrState.setForegroundColor();
                  break;
                case SGRParam.BackgroundBlack:
                  sgrState.setBackgroundColor(ANSIColor.Black);
                  break;
                case SGRParam.BackgroundRed:
                  sgrState.setBackgroundColor(ANSIColor.Red);
                  break;
                case SGRParam.BackgroundGreen:
                  sgrState.setBackgroundColor(ANSIColor.Green);
                  break;
                case SGRParam.BackgroundYellow:
                  sgrState.setBackgroundColor(ANSIColor.Yellow);
                  break;
                case SGRParam.BackgroundBlue:
                  sgrState.setBackgroundColor(ANSIColor.Blue);
                  break;
                case SGRParam.BackgroundMagenta:
                  sgrState.setBackgroundColor(ANSIColor.Magenta);
                  break;
                case SGRParam.BackgroundCyan:
                  sgrState.setBackgroundColor(ANSIColor.Cyan);
                  break;
                case SGRParam.BackgroundWhite:
                  sgrState.setBackgroundColor(ANSIColor.White);
                  break;
                case SGRParam.SetBackground: {
                  const backgroundColor = processSetColor();
                  if (backgroundColor) {
                    sgrState.setBackgroundColor(backgroundColor);
                  }
                  break;
                }
                case SGRParam.DefaultBackground:
                  sgrState.setBackgroundColor();
                  break;
                case SGRParam.ForegroundBrightBlack:
                  sgrState.setForegroundColor(ANSIColor.BrightBlack);
                  break;
                case SGRParam.ForegroundBrightRed:
                  sgrState.setForegroundColor(ANSIColor.BrightRed);
                  break;
                case SGRParam.ForegroundBrightGreen:
                  sgrState.setForegroundColor(ANSIColor.BrightGreen);
                  break;
                case SGRParam.ForegroundBrightYellow:
                  sgrState.setForegroundColor(ANSIColor.BrightYellow);
                  break;
                case SGRParam.ForegroundBrightBlue:
                  sgrState.setForegroundColor(ANSIColor.BrightBlue);
                  break;
                case SGRParam.ForegroundBrightMagenta:
                  sgrState.setForegroundColor(ANSIColor.BrightMagenta);
                  break;
                case SGRParam.ForegroundBrightCyan:
                  sgrState.setForegroundColor(ANSIColor.BrightCyan);
                  break;
                case SGRParam.ForegroundBrightWhite:
                  sgrState.setForegroundColor(ANSIColor.BrightWhite);
                  break;
                case SGRParam.BackgroundBrightBlack:
                  sgrState.setBackgroundColor(ANSIColor.BrightBlack);
                  break;
                case SGRParam.BackgroundBrightRed:
                  sgrState.setBackgroundColor(ANSIColor.BrightRed);
                  break;
                case SGRParam.BackgroundBrightGreen:
                  sgrState.setBackgroundColor(ANSIColor.BrightGreen);
                  break;
                case SGRParam.BackgroundBrightYellow:
                  sgrState.setBackgroundColor(ANSIColor.BrightYellow);
                  break;
                case SGRParam.BackgroundBrightBlue:
                  sgrState.setBackgroundColor(ANSIColor.BrightBlue);
                  break;
                case SGRParam.BackgroundBrightMagenta:
                  sgrState.setBackgroundColor(ANSIColor.BrightMagenta);
                  break;
                case SGRParam.BackgroundBrightCyan:
                  sgrState.setBackgroundColor(ANSIColor.BrightCyan);
                  break;
                case SGRParam.BackgroundBrightWhite:
                  sgrState.setBackgroundColor(ANSIColor.BrightWhite);
                  break;
              }
            }
            if (!SGRState.equivalent(sgrState, this._sgrState)) {
              this._sgrState = sgrState;
            }
          }
        }
        exports3.ANSIOutput = ANSIOutput;
        var SGRParam;
        (function(SGRParam2) {
          SGRParam2[SGRParam2["Reset"] = 0] = "Reset";
          SGRParam2[SGRParam2["Bold"] = 1] = "Bold";
          SGRParam2[SGRParam2["Dim"] = 2] = "Dim";
          SGRParam2[SGRParam2["Italic"] = 3] = "Italic";
          SGRParam2[SGRParam2["Underlined"] = 4] = "Underlined";
          SGRParam2[SGRParam2["SlowBlink"] = 5] = "SlowBlink";
          SGRParam2[SGRParam2["RapidBlink"] = 6] = "RapidBlink";
          SGRParam2[SGRParam2["Reversed"] = 7] = "Reversed";
          SGRParam2[SGRParam2["Hidden"] = 8] = "Hidden";
          SGRParam2[SGRParam2["CrossedOut"] = 9] = "CrossedOut";
          SGRParam2[SGRParam2["PrimaryFont"] = 10] = "PrimaryFont";
          SGRParam2[SGRParam2["AlternativeFont1"] = 11] = "AlternativeFont1";
          SGRParam2[SGRParam2["AlternativeFont2"] = 12] = "AlternativeFont2";
          SGRParam2[SGRParam2["AlternativeFont3"] = 13] = "AlternativeFont3";
          SGRParam2[SGRParam2["AlternativeFont4"] = 14] = "AlternativeFont4";
          SGRParam2[SGRParam2["AlternativeFont5"] = 15] = "AlternativeFont5";
          SGRParam2[SGRParam2["AlternativeFont6"] = 16] = "AlternativeFont6";
          SGRParam2[SGRParam2["AlternativeFont7"] = 17] = "AlternativeFont7";
          SGRParam2[SGRParam2["AlternativeFont8"] = 18] = "AlternativeFont8";
          SGRParam2[SGRParam2["AlternativeFont9"] = 19] = "AlternativeFont9";
          SGRParam2[SGRParam2["Fraktur"] = 20] = "Fraktur";
          SGRParam2[SGRParam2["DoubleUnderlined"] = 21] = "DoubleUnderlined";
          SGRParam2[SGRParam2["NormalIntensity"] = 22] = "NormalIntensity";
          SGRParam2[SGRParam2["NotItalicNotFraktur"] = 23] = "NotItalicNotFraktur";
          SGRParam2[SGRParam2["NotUnderlined"] = 24] = "NotUnderlined";
          SGRParam2[SGRParam2["NotBlinking"] = 25] = "NotBlinking";
          SGRParam2[SGRParam2["ProportionalSpacing"] = 26] = "ProportionalSpacing";
          SGRParam2[SGRParam2["NotReversed"] = 27] = "NotReversed";
          SGRParam2[SGRParam2["Reveal"] = 28] = "Reveal";
          SGRParam2[SGRParam2["NotCrossedOut"] = 29] = "NotCrossedOut";
          SGRParam2[SGRParam2["ForegroundBlack"] = 30] = "ForegroundBlack";
          SGRParam2[SGRParam2["ForegroundRed"] = 31] = "ForegroundRed";
          SGRParam2[SGRParam2["ForegroundGreen"] = 32] = "ForegroundGreen";
          SGRParam2[SGRParam2["ForegroundYellow"] = 33] = "ForegroundYellow";
          SGRParam2[SGRParam2["ForegroundBlue"] = 34] = "ForegroundBlue";
          SGRParam2[SGRParam2["ForegroundMagenta"] = 35] = "ForegroundMagenta";
          SGRParam2[SGRParam2["ForegroundCyan"] = 36] = "ForegroundCyan";
          SGRParam2[SGRParam2["ForegroundWhite"] = 37] = "ForegroundWhite";
          SGRParam2[SGRParam2["SetForeground"] = 38] = "SetForeground";
          SGRParam2[SGRParam2["DefaultForeground"] = 39] = "DefaultForeground";
          SGRParam2[SGRParam2["BackgroundBlack"] = 40] = "BackgroundBlack";
          SGRParam2[SGRParam2["BackgroundRed"] = 41] = "BackgroundRed";
          SGRParam2[SGRParam2["BackgroundGreen"] = 42] = "BackgroundGreen";
          SGRParam2[SGRParam2["BackgroundYellow"] = 43] = "BackgroundYellow";
          SGRParam2[SGRParam2["BackgroundBlue"] = 44] = "BackgroundBlue";
          SGRParam2[SGRParam2["BackgroundMagenta"] = 45] = "BackgroundMagenta";
          SGRParam2[SGRParam2["BackgroundCyan"] = 46] = "BackgroundCyan";
          SGRParam2[SGRParam2["BackgroundWhite"] = 47] = "BackgroundWhite";
          SGRParam2[SGRParam2["SetBackground"] = 48] = "SetBackground";
          SGRParam2[SGRParam2["DefaultBackground"] = 49] = "DefaultBackground";
          SGRParam2[SGRParam2["DisableProportionalSpacing"] = 50] = "DisableProportionalSpacing";
          SGRParam2[SGRParam2["Framed"] = 51] = "Framed";
          SGRParam2[SGRParam2["Encircled"] = 52] = "Encircled";
          SGRParam2[SGRParam2["Overlined"] = 53] = "Overlined";
          SGRParam2[SGRParam2["NotFramedNotEncircled"] = 54] = "NotFramedNotEncircled";
          SGRParam2[SGRParam2["NotOverlined"] = 55] = "NotOverlined";
          SGRParam2[SGRParam2["SetUnderline"] = 58] = "SetUnderline";
          SGRParam2[SGRParam2["DefaultUnderline"] = 59] = "DefaultUnderline";
          SGRParam2[SGRParam2["IdeogramUnderlineOrRightSideLine"] = 60] = "IdeogramUnderlineOrRightSideLine";
          SGRParam2[SGRParam2["IdeogramDoubleUnderlineOrDoubleRightSideLine"] = 61] = "IdeogramDoubleUnderlineOrDoubleRightSideLine";
          SGRParam2[SGRParam2["IdeogramOverlineOrLeftSideLine"] = 62] = "IdeogramOverlineOrLeftSideLine";
          SGRParam2[SGRParam2["IdeogramDoubleOverlineOrDoubleLeftSideLine"] = 63] = "IdeogramDoubleOverlineOrDoubleLeftSideLine";
          SGRParam2[SGRParam2["IdeogramStressMarking"] = 64] = "IdeogramStressMarking";
          SGRParam2[SGRParam2["NoIdeogramAttributes"] = 65] = "NoIdeogramAttributes";
          SGRParam2[SGRParam2["Superscript"] = 73] = "Superscript";
          SGRParam2[SGRParam2["Subscript"] = 74] = "Subscript";
          SGRParam2[SGRParam2["NotSuperscriptNotSubscript"] = 75] = "NotSuperscriptNotSubscript";
          SGRParam2[SGRParam2["ForegroundBrightBlack"] = 90] = "ForegroundBrightBlack";
          SGRParam2[SGRParam2["ForegroundBrightRed"] = 91] = "ForegroundBrightRed";
          SGRParam2[SGRParam2["ForegroundBrightGreen"] = 92] = "ForegroundBrightGreen";
          SGRParam2[SGRParam2["ForegroundBrightYellow"] = 93] = "ForegroundBrightYellow";
          SGRParam2[SGRParam2["ForegroundBrightBlue"] = 94] = "ForegroundBrightBlue";
          SGRParam2[SGRParam2["ForegroundBrightMagenta"] = 95] = "ForegroundBrightMagenta";
          SGRParam2[SGRParam2["ForegroundBrightCyan"] = 96] = "ForegroundBrightCyan";
          SGRParam2[SGRParam2["ForegroundBrightWhite"] = 97] = "ForegroundBrightWhite";
          SGRParam2[SGRParam2["BackgroundBrightBlack"] = 100] = "BackgroundBrightBlack";
          SGRParam2[SGRParam2["BackgroundBrightRed"] = 101] = "BackgroundBrightRed";
          SGRParam2[SGRParam2["BackgroundBrightGreen"] = 102] = "BackgroundBrightGreen";
          SGRParam2[SGRParam2["BackgroundBrightYellow"] = 103] = "BackgroundBrightYellow";
          SGRParam2[SGRParam2["BackgroundBrightBlue"] = 104] = "BackgroundBrightBlue";
          SGRParam2[SGRParam2["BackgroundBrightMagenta"] = 105] = "BackgroundBrightMagenta";
          SGRParam2[SGRParam2["BackgroundBrightCyan"] = 106] = "BackgroundBrightCyan";
          SGRParam2[SGRParam2["BackgroundBrightWhite"] = 107] = "BackgroundBrightWhite";
        })(SGRParam || (SGRParam = {}));
        var SGRParamColor;
        (function(SGRParamColor2) {
          SGRParamColor2[SGRParamColor2["Color256"] = 5] = "Color256";
          SGRParamColor2[SGRParamColor2["ColorRGB"] = 2] = "ColorRGB";
        })(SGRParamColor || (SGRParamColor = {}));
        var SGRParamIndexedColor;
        (function(SGRParamIndexedColor2) {
          SGRParamIndexedColor2[SGRParamIndexedColor2["Black"] = 0] = "Black";
          SGRParamIndexedColor2[SGRParamIndexedColor2["Red"] = 1] = "Red";
          SGRParamIndexedColor2[SGRParamIndexedColor2["Green"] = 2] = "Green";
          SGRParamIndexedColor2[SGRParamIndexedColor2["Yellow"] = 3] = "Yellow";
          SGRParamIndexedColor2[SGRParamIndexedColor2["Blue"] = 4] = "Blue";
          SGRParamIndexedColor2[SGRParamIndexedColor2["Magenta"] = 5] = "Magenta";
          SGRParamIndexedColor2[SGRParamIndexedColor2["Cyan"] = 6] = "Cyan";
          SGRParamIndexedColor2[SGRParamIndexedColor2["White"] = 7] = "White";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightBlack"] = 8] = "BrightBlack";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightRed"] = 9] = "BrightRed";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightGreen"] = 10] = "BrightGreen";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightYellow"] = 11] = "BrightYellow";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightBlue"] = 12] = "BrightBlue";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightMagenta"] = 13] = "BrightMagenta";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightCyan"] = 14] = "BrightCyan";
          SGRParamIndexedColor2[SGRParamIndexedColor2["BrightWhite"] = 15] = "BrightWhite";
        })(SGRParamIndexedColor || (SGRParamIndexedColor = {}));
        var ParserState;
        (function(ParserState2) {
          ParserState2[ParserState2["BufferingOutput"] = 0] = "BufferingOutput";
          ParserState2[ParserState2["ControlSequenceStarted"] = 1] = "ControlSequenceStarted";
          ParserState2[ParserState2["ParsingControlSequence"] = 2] = "ParsingControlSequence";
        })(ParserState || (ParserState = {}));
        class SGRState {
          constructor() {
            //#region Private Properties.
            /**
             * Gets or sets the styles.
             */
            __publicField(this, "_styles");
            /**
             * Gets or sets the foreground color.
             */
            __publicField(this, "_foregroundColor");
            /**
             * Gets or sets the background color.
             */
            __publicField(this, "_backgroundColor");
            /**
             * Gets or sets the underlined color.
             */
            __publicField(this, "_underlinedColor");
            /**
             * Gets or sets a value which indicates whether the foreground and background colors are
             * reversed.
             */
            __publicField(this, "_reversed");
            /**
             * Gets or sets the font.
             */
            __publicField(this, "_font");
          }
          //#endregion Private Properties.
          //#region Public Methods
          /**
           * Resets the SGRState.
           */
          reset() {
            this._styles = void 0;
            this._foregroundColor = void 0;
            this._backgroundColor = void 0;
            this._underlinedColor = void 0;
            this._reversed = void 0;
            this._font = void 0;
          }
          /**
           * Creates a copy of the SGRState.
           * @returns The copy of the SGRState.
           */
          copy() {
            const copy = new SGRState();
            if (this._styles && this._styles.size) {
              const styles2 = /* @__PURE__ */ new Set();
              this._styles.forEach((style2) => styles2.add(style2));
              copy._styles = styles2;
            }
            copy._foregroundColor = this._foregroundColor;
            copy._backgroundColor = this._backgroundColor;
            copy._underlinedColor = this._underlinedColor;
            copy._reversed = this._reversed;
            copy._font = this._font;
            return copy;
          }
          /**
           * Sets a style.
           * @param style The style to set.
           * @param stylesToDelete The styles to delete.
           */
          setStyle(style2, ...stylesToDelete) {
            if (this._styles) {
              for (const style3 of stylesToDelete) {
                this._styles.delete(style3);
              }
            } else {
              this._styles = /* @__PURE__ */ new Set();
            }
            this._styles.add(style2);
          }
          /**
           * Deletes styles.
           * @param stylesToDelete The styles to delete.
           */
          deleteStyles(...stylesToDelete) {
            if (this._styles) {
              for (const style2 of stylesToDelete) {
                this._styles.delete(style2);
              }
              if (!this._styles.size) {
                this._styles = void 0;
              }
            }
          }
          /**
           * Sets the foreground color.
           * @param color The foreground color.
           */
          setForegroundColor(color) {
            if (!this._reversed) {
              this._foregroundColor = color;
            } else {
              this._backgroundColor = color;
            }
          }
          /**
           * Sets the background color.
           * @param color The background color.
           */
          setBackgroundColor(color) {
            if (!this._reversed) {
              this._backgroundColor = color;
            } else {
              this._foregroundColor = color;
            }
          }
          /**
           * Sets reversed.
           * @param reversed A value which indicates whether the foreground and background colors are
           * reversed.
           */
          setReversed(reversed) {
            if (reversed) {
              if (!this._reversed) {
                this._reversed = true;
                this.reverseForegroundAndBackgroundColors();
              }
            } else {
              if (this._reversed) {
                this._reversed = void 0;
                this.reverseForegroundAndBackgroundColors();
              }
            }
          }
          /**
           * Sets the font.
           * @param font The font.
           */
          setFont(font) {
            this._font = font;
          }
          /**
           *
           * @param left
           * @param right
           * @returns
           */
          static equivalent(left, right) {
            const setReplacer = (_, value2) => value2 instanceof Set ? !value2.size ? void 0 : [...value2] : value2;
            return left === right || JSON.stringify(left, setReplacer) === JSON.stringify(right, setReplacer);
          }
          //#endregion Public Methods
          //#region ANSIFormat Implementation
          /**
           * Gets the styles.
           */
          get styles() {
            return !this._styles ? void 0 : [...this._styles];
          }
          /**
           * Gets the foreground color.
           */
          get foregroundColor() {
            if (this._backgroundColor && !this._foregroundColor) {
              switch (this._backgroundColor) {
                case ANSIColor.Black:
                case ANSIColor.BrightBlack:
                case ANSIColor.Red:
                case ANSIColor.BrightRed:
                  return ANSIColor.White;
                case ANSIColor.Green:
                case ANSIColor.BrightGreen:
                case ANSIColor.Yellow:
                case ANSIColor.BrightYellow:
                case ANSIColor.Blue:
                case ANSIColor.BrightBlue:
                case ANSIColor.Magenta:
                case ANSIColor.BrightMagenta:
                case ANSIColor.Cyan:
                case ANSIColor.BrightCyan:
                case ANSIColor.White:
                case ANSIColor.BrightWhite:
                  return ANSIColor.Black;
              }
            }
            return this._foregroundColor;
          }
          /**
           * Gets the background color.
           */
          get backgroundColor() {
            return this._backgroundColor;
          }
          /**
           * Gets the underlined color.
           */
          get underlinedColor() {
            return this._underlinedColor;
          }
          /**
           * Gets the font.
           */
          get font() {
            return this._font;
          }
          //#endregion ANSIFormat Implementation
          //#region Private Methods
          /**
           * Reverses the foreground and background colors.
           */
          reverseForegroundAndBackgroundColors() {
            const foregroundColor = this._foregroundColor;
            this._foregroundColor = this._backgroundColor;
            this._backgroundColor = foregroundColor;
          }
        }
        class OutputLine {
          constructor() {
            //#region Private Properties
            /**
             * Gets the identifier.
             */
            __publicField(this, "_id", generateId());
            /**
             * Gets or sets the output runs.
             */
            __publicField(this, "_outputRuns", []);
            /**
             * Gets or sets the total length.
             */
            __publicField(this, "_totalLength", 0);
          }
          //#endregion Private Properties
          //#region Public Methods
          /**
           * Clears the entire output line.
           */
          clearEntireLine() {
            if (this._totalLength) {
              this._outputRuns = [new OutputRun2(" ".repeat(this._totalLength))];
            }
          }
          /**
           * Clears to the end of the output line.
           * @param column The column at which to clear from.
           */
          clearToEndOfLine(column2) {
            column2 = Math.max(column2, 0);
            if (column2 >= this._totalLength) {
              return;
            }
            if (column2 === 0) {
              this.clearEntireLine();
              return;
            }
            let leftOffset = 0;
            let leftOutputRun;
            let leftOutputRunIndex = void 0;
            for (let index2 = 0; index2 < this._outputRuns.length; index2++) {
              const outputRun = this._outputRuns[index2];
              if (column2 < leftOffset + outputRun.text.length) {
                leftOutputRun = outputRun;
                leftOutputRunIndex = index2;
                break;
              }
              leftOffset += outputRun.text.length;
            }
            if (leftOutputRun === void 0 || leftOutputRunIndex === void 0) {
              return;
            }
            const leftTextLength = column2 - leftOffset;
            const erasureText = " ".repeat(this._totalLength - column2);
            const outputRuns = [];
            if (!leftTextLength) {
              outputRuns.push(new OutputRun2(erasureText));
            } else {
              const leftText = leftOutputRun.text.slice(0, leftTextLength);
              outputRuns.push(new OutputRun2(leftText, leftOutputRun.sgrState));
              outputRuns.push(new OutputRun2(erasureText));
            }
            this.outputRuns.splice(leftOutputRunIndex, this._outputRuns.length - leftOutputRunIndex, ...outputRuns);
          }
          /**
           * Clears to the beginning of the output line.
           * @param column The column at which to clear from.
           */
          clearToBeginningOfLine(column2) {
            column2 = Math.max(column2, 0);
            if (column2 === 0) {
              return;
            }
            if (column2 >= this._totalLength) {
              this.clearEntireLine();
              return;
            }
            let rightOffset = 0;
            let rightOutputRun;
            let rightOutputRunIndex = void 0;
            for (let index2 = this._outputRuns.length - 1; index2 >= 0; index2--) {
              const outputRun = this._outputRuns[index2];
              if (column2 >= rightOffset - outputRun.text.length) {
                rightOutputRun = outputRun;
                rightOutputRunIndex = index2;
                break;
              }
              rightOffset -= outputRun.text.length;
            }
            if (rightOutputRun === void 0 || rightOutputRunIndex === void 0) {
              return;
            }
            const rightTextLength = rightOffset - column2;
            const erasureText = " ".repeat(column2);
            const outputRuns = [new OutputRun2(erasureText)];
            if (rightTextLength) {
              const rightOutputRunText = rightOutputRun.text.slice(-rightTextLength);
              outputRuns.push(new OutputRun2(rightOutputRunText, rightOutputRun.sgrState));
            }
            this.outputRuns.splice(0, this._outputRuns.length - rightOutputRunIndex, ...outputRuns);
          }
          /**
           * Inserts text into the output line.
           * @param text The text to insert.
           * @param column The column at which to insert the text.
           * @param sgrState The SGR state.
           */
          insert(text2, column2, sgrState) {
            if (!text2.length) {
              return;
            }
            if (column2 === this._totalLength) {
              this._totalLength += text2.length;
              if (this._outputRuns.length) {
                const lastOutputRun = this._outputRuns[this._outputRuns.length - 1];
                if (SGRState.equivalent(lastOutputRun.sgrState, sgrState)) {
                  lastOutputRun.appendText(text2);
                  return;
                }
              }
              this._outputRuns.push(new OutputRun2(text2, sgrState));
              return;
            }
            if (column2 > this._totalLength) {
              const spacer = " ".repeat(column2 - this._totalLength);
              this._totalLength += spacer.length + text2.length;
              if (!sgrState && this._outputRuns.length) {
                const lastOutputRun = this._outputRuns[this._outputRuns.length - 1];
                if (!lastOutputRun.sgrState) {
                  lastOutputRun.appendText(spacer);
                  lastOutputRun.appendText(text2);
                  return;
                }
              }
              if (!sgrState) {
                this._outputRuns.push(new OutputRun2(spacer + text2));
              } else {
                this._outputRuns.push(new OutputRun2(spacer));
                this._outputRuns.push(new OutputRun2(text2, sgrState));
              }
            }
            let leftOffset = 0;
            let leftOutputRunIndex = void 0;
            for (let index2 = 0; index2 < this._outputRuns.length; index2++) {
              const outputRun = this._outputRuns[index2];
              if (column2 < leftOffset + outputRun.text.length) {
                leftOutputRunIndex = index2;
                break;
              }
              leftOffset += outputRun.text.length;
            }
            if (leftOutputRunIndex === void 0) {
              this._outputRuns.push(new OutputRun2(text2, sgrState));
              return;
            }
            if (column2 + text2.length >= this._totalLength) {
              const leftTextLength = column2 - leftOffset;
              const outputRuns2 = [];
              if (!leftTextLength) {
                outputRuns2.push(new OutputRun2(text2, sgrState));
              } else {
                const leftOutputRun = this._outputRuns[leftOutputRunIndex];
                const leftText = leftOutputRun.text.slice(0, leftTextLength);
                if (SGRState.equivalent(leftOutputRun.sgrState, sgrState)) {
                  outputRuns2.push(new OutputRun2(leftText + text2, sgrState));
                } else {
                  outputRuns2.push(new OutputRun2(leftText, leftOutputRun.sgrState));
                  outputRuns2.push(new OutputRun2(text2, sgrState));
                }
              }
              this.outputRuns.splice(leftOutputRunIndex, 1, ...outputRuns2);
              this._totalLength = leftOffset + leftTextLength + text2.length;
              return;
            }
            let rightOffset = this._totalLength;
            let rightOutputRunIndex = void 0;
            for (let index2 = this._outputRuns.length - 1; index2 >= 0; index2--) {
              const outputRun = this._outputRuns[index2];
              if (column2 + text2.length > rightOffset - outputRun.text.length) {
                rightOutputRunIndex = index2;
                break;
              }
              rightOffset -= outputRun.text.length;
            }
            if (rightOutputRunIndex === void 0) {
              this._outputRuns.push(new OutputRun2(text2, sgrState));
              return;
            }
            const outputRuns = [];
            const leftOutputRunTextLength = column2 - leftOffset;
            if (leftOutputRunTextLength) {
              const leftOutputRun = this._outputRuns[leftOutputRunIndex];
              const leftOutputRunText = leftOutputRun.text.slice(0, leftOutputRunTextLength);
              outputRuns.push(new OutputRun2(leftOutputRunText, leftOutputRun.sgrState));
            }
            outputRuns.push(new OutputRun2(text2, sgrState));
            const rightOutputRunTextLength = rightOffset - (column2 + text2.length);
            if (rightOutputRunTextLength) {
              const rightOutputRun = this._outputRuns[rightOutputRunIndex];
              const rightOutputRunText = rightOutputRun.text.slice(-rightOutputRunTextLength);
              outputRuns.push(new OutputRun2(rightOutputRunText, rightOutputRun.sgrState));
            }
            this._outputRuns.splice(leftOutputRunIndex, rightOutputRunIndex - leftOutputRunIndex + 1, ...outputRuns);
            if (this._outputRuns.length > 1) {
              this._outputRuns = OutputRun2.optimizeOutputRuns(this._outputRuns);
            }
            this._totalLength = this._outputRuns.reduce((totalLength, outputRun) => totalLength + outputRun.text.length, 0);
          }
          //#endregion Public Methods
          //#region ANSIOutputLine Implementation
          /**
           * Gets the identifier.
           */
          get id() {
            return this._id;
          }
          /**
           * Gets the output runs.
           */
          get outputRuns() {
            return this._outputRuns;
          }
        }
        class OutputRun2 {
          //#endregion Public Properties
          //#region Constructor
          /**
           * Constructor.
           * @param text The text.
           * @param sgrState The SGR state.
           */
          constructor(text2, sgrState) {
            //#region Private Properties
            /**
             * Gets the identifier.
             */
            __publicField(this, "_id", generateId());
            /**
             * Gets the SGR state.
             */
            __publicField(this, "_sgrState");
            /**
             * Gets or sets the text.
             */
            __publicField(this, "_text");
            this._sgrState = sgrState;
            this._text = text2;
          }
          //#endregion Private Properties
          //#region Public Properties
          get sgrState() {
            return this._sgrState;
          }
          //#endregion Constructor
          //#region Public Methods
          /**
           * Optimizes a an array of output runs by combining adjacent output runs with equivalent SGR
           * states.
           * @param outputRunsIn The output runs to optimize.
           * @returns The optimized output runs.
           */
          static optimizeOutputRuns(outputRunsIn) {
            const outputRunsOut = [outputRunsIn[0]];
            for (let i2 = 1, o = 0; i2 < outputRunsIn.length; i2++) {
              const outputRun = outputRunsIn[i2];
              if (SGRState.equivalent(outputRunsOut[o].sgrState, outputRun.sgrState)) {
                outputRunsOut[o]._text += outputRun.text;
              } else {
                outputRunsOut[++o] = outputRun;
              }
            }
            return outputRunsOut;
          }
          /**
           * Appends text to the end of the output run.
           * @param text The text to append.
           */
          appendText(text2) {
            this._text += text2;
          }
          //#endregion Public Methods
          //#region ANSIOutputRun Implementation
          /**
           * Gets the identifier.
           */
          get id() {
            return this._id;
          }
          /**
           * Gets the format.
           */
          get format() {
            return this._sgrState;
          }
          /**
           * Gets the text.
           */
          get text() {
            return this._text;
          }
        }
        const rangeParam = (value2, defaultValue, minValue) => {
          const param = getParam(value2, defaultValue);
          return Math.max(param, minValue);
        };
        const getParam = (value2, defaultValue) => {
          const param = parseInt(value2);
          return Number.isNaN(param) ? defaultValue : param;
        };
        const twoDigitHex = (value2) => {
          const hex = Math.max(Math.min(255, value2), 0).toString(16);
          return hex.length === 2 ? hex : "0" + hex;
        };
      });
    })(ansiOutput, ansiOutput.exports);
    var ansiOutputExports = ansiOutput.exports;
    const ANSIDisplay = ({
      output: output2,
      style: style2,
      className: className2
    }) => {
      const ansiOutput2 = new ansiOutputExports.ANSIOutput();
      ansiOutput2.processOutput(output2);
      let firstOutput = false;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("ansi-display", className2), style: { ...style2 }, children: ansiOutput2.outputLines.map((line2, index2) => {
        firstOutput = firstOutput || !!line2.outputRuns.length;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ansi-display-line", children: !line2.outputRuns.length ? firstOutput ? /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}) : null : line2.outputRuns.map((outputRun) => /* @__PURE__ */ jsxRuntimeExports.jsx(OutputRun, { run: outputRun }, outputRun.id)) }, index2);
      }) });
    };
    const kForeground = 0;
    const kBackground = 1;
    const OutputRun = ({ run }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: computeCSSProperties(run), children: run.text });
    };
    const computeCSSProperties = (outputRun) => {
      return !outputRun.format ? {} : {
        ...computeStyles(outputRun.format.styles || []),
        ...computeForegroundBackgroundColor(
          kForeground,
          outputRun.format.foregroundColor
        ),
        ...computeForegroundBackgroundColor(
          kBackground,
          outputRun.format.backgroundColor
        )
      };
    };
    const computeStyles = (styles2) => {
      let cssProperties = {};
      if (styles2) {
        styles2.forEach((style2) => {
          switch (style2) {
            case ansiOutputExports.ANSIStyle.Bold:
              cssProperties = { ...cssProperties, ...{ fontWeight: "bold" } };
              break;
            case ansiOutputExports.ANSIStyle.Dim:
              cssProperties = { ...cssProperties, ...{ fontWeight: "lighter" } };
              break;
            case ansiOutputExports.ANSIStyle.Italic:
              cssProperties = { ...cssProperties, ...{ fontStyle: "italic" } };
              break;
            case ansiOutputExports.ANSIStyle.Underlined:
              cssProperties = {
                ...cssProperties,
                ...{
                  textDecorationLine: "underline",
                  textDecorationStyle: "solid"
                }
              };
              break;
            case ansiOutputExports.ANSIStyle.SlowBlink:
              cssProperties = {
                ...cssProperties,
                ...{ animation: "ansi-display-run-blink 1s linear infinite" }
              };
              break;
            case ansiOutputExports.ANSIStyle.RapidBlink:
              cssProperties = {
                ...cssProperties,
                ...{ animation: "ansi-display-run-blink 0.5s linear infinite" }
              };
              break;
            case ansiOutputExports.ANSIStyle.Hidden:
              cssProperties = { ...cssProperties, ...{ visibility: "hidden" } };
              break;
            case ansiOutputExports.ANSIStyle.CrossedOut:
              cssProperties = {
                ...cssProperties,
                ...{
                  textDecorationLine: "line-through",
                  textDecorationStyle: "solid"
                }
              };
              break;
            case ansiOutputExports.ANSIStyle.DoubleUnderlined:
              cssProperties = {
                ...cssProperties,
                ...{
                  textDecorationLine: "underline",
                  textDecorationStyle: "double"
                }
              };
              break;
          }
        });
      }
      return cssProperties;
    };
    const computeForegroundBackgroundColor = (colorType, color) => {
      switch (color) {
        case void 0:
          return {};
        case ansiOutputExports.ANSIColor.Black:
        case ansiOutputExports.ANSIColor.Red:
        case ansiOutputExports.ANSIColor.Green:
        case ansiOutputExports.ANSIColor.Yellow:
        case ansiOutputExports.ANSIColor.Blue:
        case ansiOutputExports.ANSIColor.Magenta:
        case ansiOutputExports.ANSIColor.Cyan:
        case ansiOutputExports.ANSIColor.White:
        case ansiOutputExports.ANSIColor.BrightBlack:
        case ansiOutputExports.ANSIColor.BrightRed:
        case ansiOutputExports.ANSIColor.BrightGreen:
        case ansiOutputExports.ANSIColor.BrightYellow:
        case ansiOutputExports.ANSIColor.BrightBlue:
        case ansiOutputExports.ANSIColor.BrightMagenta:
        case ansiOutputExports.ANSIColor.BrightCyan:
        case ansiOutputExports.ANSIColor.BrightWhite:
          if (colorType === kForeground) {
            return { color: `var(--${color})` };
          } else {
            return { background: `var(--${color})` };
          }
        default:
          if (colorType === kForeground) {
            return { color };
          } else {
            return { background: color };
          }
      }
    };
    const visible = "_visible_tm52u_1";
    const hidden$2 = "_hidden_tm52u_5";
    const pills = "_pills_tm52u_9";
    const pill = "_pill_tm52u_9";
    const styles$14 = {
      visible,
      hidden: hidden$2,
      pills,
      pill
    };
    const NavPills = ({ children: children2 }) => {
      const [activeItem, setActiveItem] = reactExports.useState(
        children2 ? children2[0].props["title"] : null
      );
      if (!activeItem || !children2) {
        return void 0;
      }
      const navPills = children2.map((nav2, idx) => {
        var _a2;
        const title2 = typeof nav2 === "object" ? ((_a2 = nav2["props"]) == null ? void 0 : _a2.title) || `Tab ${idx}` : `Tab ${idx}`;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          NavPill,
          {
            title: title2,
            activeItem,
            setActiveItem
          },
          `nav-pill-contents-${idx}`
        );
      });
      const navBodies = children2.map((child, idx) => {
        var _a2;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: ((_a2 = child["props"]) == null ? void 0 : _a2.title) === activeItem ? styles$14.visible : styles$14.hidden,
            children: child
          },
          `nav-pill-container-${idx}`
        );
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "ul",
          {
            className: clsx("nav", "nav-pills", styles$14.pills),
            role: "tablist",
            "aria-orientation": "horizontal",
            children: navPills
          }
        ),
        navBodies
      ] });
    };
    const NavPill = ({
      title: title2,
      activeItem,
      setActiveItem,
      children: children2
    }) => {
      const active2 = activeItem === title2;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "nav-item", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            role: "tab",
            "aria-selected": active2,
            className: clsx(
              "nav-link",
              "text-style-label",
              active2 ? "active " : "",
              styles$14.pill
            ),
            onClick: () => {
              setActiveItem(title2);
            },
            children: title2
          }
        ),
        children2
      ] });
    };
    const Buckets = {
      first: 0,
      intermediate: 10,
      final: 1e3
    };
    const useResizeObserver = (callback) => {
      const elementRef = reactExports.useRef(null);
      const observerRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        const element = elementRef.current;
        if (!element) return;
        observerRef.current = new ResizeObserver((entries) => {
          if (entries[0]) {
            callback(entries[0]);
          }
        });
        observerRef.current.observe(element);
        return () => {
          if (observerRef.current) {
            observerRef.current.disconnect();
          }
        };
      }, [callback]);
      return elementRef;
    };
    const ExpandablePanel = ({
      collapse,
      border,
      lines = 15,
      children: children2,
      className: className2
    }) => {
      const [isCollapsed, setIsCollapsed] = reactExports.useState(collapse);
      const [showToggle, setShowToggle] = reactExports.useState(false);
      const lineHeightRef = reactExports.useRef(0);
      reactExports.useEffect(() => {
        setIsCollapsed(collapse);
      }, [collapse]);
      const checkOverflow = reactExports.useCallback(
        (entry2) => {
          const element = entry2.target;
          if (!lineHeightRef.current) {
            const computedStyle = window.getComputedStyle(element);
            lineHeightRef.current = parseInt(computedStyle.lineHeight) || 16;
          }
          const maxCollapsedHeight = lines * lineHeightRef.current;
          const contentHeight = element.scrollHeight;
          setShowToggle(contentHeight > maxCollapsedHeight);
        },
        [lines]
      );
      const contentRef = useResizeObserver(checkOverflow);
      const baseStyles = {
        overflow: "hidden",
        ...isCollapsed && {
          maxHeight: `${lines}em`
        }
      };
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(className2), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            style: baseStyles,
            ref: contentRef,
            className: clsx(
              "expandable-panel",
              isCollapsed ? "expandable-collapsed" : void 0,
              border ? "expandable-bordered" : void 0
            ),
            children: children2
          }
        ),
        showToggle && /* @__PURE__ */ jsxRuntimeExports.jsx(
          MoreToggle,
          {
            collapsed: isCollapsed,
            setCollapsed: setIsCollapsed,
            border: !border
          }
        )
      ] });
    };
    const MoreToggle = ({
      collapsed,
      border,
      setCollapsed,
      style: style2
    }) => {
      const text2 = collapsed ? "more" : "less";
      const icon = collapsed ? ApplicationIcons["expand-down"] : ApplicationIcons.collapse.up;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `more-toggle ${border ? "bordered" : ""}`, style: style2, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "more-toggle-container", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          className: "btn more-toggle-button",
          onClick: () => setCollapsed(!collapsed),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: icon }),
            text2
          ]
        }
      ) }) });
    };
    const message$1 = "_message_xh8qq_1";
    const systemRole = "_systemRole_xh8qq_9";
    const messageGrid = "_messageGrid_xh8qq_13";
    const messageContents = "_messageContents_xh8qq_21";
    const indented = "_indented_xh8qq_26";
    const styles$13 = {
      message: message$1,
      systemRole,
      messageGrid,
      messageContents,
      indented
    };
    const decodeCache = {};
    function getDecodeCache(exclude) {
      let cache = decodeCache[exclude];
      if (cache) {
        return cache;
      }
      cache = decodeCache[exclude] = [];
      for (let i2 = 0; i2 < 128; i2++) {
        const ch3 = String.fromCharCode(i2);
        cache.push(ch3);
      }
      for (let i2 = 0; i2 < exclude.length; i2++) {
        const ch3 = exclude.charCodeAt(i2);
        cache[ch3] = "%" + ("0" + ch3.toString(16).toUpperCase()).slice(-2);
      }
      return cache;
    }
    function decode$1(string2, exclude) {
      if (typeof exclude !== "string") {
        exclude = decode$1.defaultChars;
      }
      const cache = getDecodeCache(exclude);
      return string2.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
        let result2 = "";
        for (let i2 = 0, l = seq.length; i2 < l; i2 += 3) {
          const b1 = parseInt(seq.slice(i2 + 1, i2 + 3), 16);
          if (b1 < 128) {
            result2 += cache[b1];
            continue;
          }
          if ((b1 & 224) === 192 && i2 + 3 < l) {
            const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
            if ((b2 & 192) === 128) {
              const chr = b1 << 6 & 1984 | b2 & 63;
              if (chr < 128) {
                result2 += "��";
              } else {
                result2 += String.fromCharCode(chr);
              }
              i2 += 3;
              continue;
            }
          }
          if ((b1 & 240) === 224 && i2 + 6 < l) {
            const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
            const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
            if ((b2 & 192) === 128 && (b3 & 192) === 128) {
              const chr = b1 << 12 & 61440 | b2 << 6 & 4032 | b3 & 63;
              if (chr < 2048 || chr >= 55296 && chr <= 57343) {
                result2 += "���";
              } else {
                result2 += String.fromCharCode(chr);
              }
              i2 += 6;
              continue;
            }
          }
          if ((b1 & 248) === 240 && i2 + 9 < l) {
            const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
            const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
            const b4 = parseInt(seq.slice(i2 + 10, i2 + 12), 16);
            if ((b2 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
              let chr = b1 << 18 & 1835008 | b2 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
              if (chr < 65536 || chr > 1114111) {
                result2 += "����";
              } else {
                chr -= 65536;
                result2 += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
              }
              i2 += 9;
              continue;
            }
          }
          result2 += "�";
        }
        return result2;
      });
    }
    decode$1.defaultChars = ";/?:@&=+$,#";
    decode$1.componentChars = "";
    const encodeCache = {};
    function getEncodeCache(exclude) {
      let cache = encodeCache[exclude];
      if (cache) {
        return cache;
      }
      cache = encodeCache[exclude] = [];
      for (let i2 = 0; i2 < 128; i2++) {
        const ch3 = String.fromCharCode(i2);
        if (/^[0-9a-z]$/i.test(ch3)) {
          cache.push(ch3);
        } else {
          cache.push("%" + ("0" + i2.toString(16).toUpperCase()).slice(-2));
        }
      }
      for (let i2 = 0; i2 < exclude.length; i2++) {
        cache[exclude.charCodeAt(i2)] = exclude[i2];
      }
      return cache;
    }
    function encode$1(string2, exclude, keepEscaped) {
      if (typeof exclude !== "string") {
        keepEscaped = exclude;
        exclude = encode$1.defaultChars;
      }
      if (typeof keepEscaped === "undefined") {
        keepEscaped = true;
      }
      const cache = getEncodeCache(exclude);
      let result2 = "";
      for (let i2 = 0, l = string2.length; i2 < l; i2++) {
        const code2 = string2.charCodeAt(i2);
        if (keepEscaped && code2 === 37 && i2 + 2 < l) {
          if (/^[0-9a-f]{2}$/i.test(string2.slice(i2 + 1, i2 + 3))) {
            result2 += string2.slice(i2, i2 + 3);
            i2 += 2;
            continue;
          }
        }
        if (code2 < 128) {
          result2 += cache[code2];
          continue;
        }
        if (code2 >= 55296 && code2 <= 57343) {
          if (code2 >= 55296 && code2 <= 56319 && i2 + 1 < l) {
            const nextCode = string2.charCodeAt(i2 + 1);
            if (nextCode >= 56320 && nextCode <= 57343) {
              result2 += encodeURIComponent(string2[i2] + string2[i2 + 1]);
              i2++;
              continue;
            }
          }
          result2 += "%EF%BF%BD";
          continue;
        }
        result2 += encodeURIComponent(string2[i2]);
      }
      return result2;
    }
    encode$1.defaultChars = ";/?:@&=+$,-_.!~*'()#";
    encode$1.componentChars = "-_.!~*'()";
    function format$1(url) {
      let result2 = "";
      result2 += url.protocol || "";
      result2 += url.slashes ? "//" : "";
      result2 += url.auth ? url.auth + "@" : "";
      if (url.hostname && url.hostname.indexOf(":") !== -1) {
        result2 += "[" + url.hostname + "]";
      } else {
        result2 += url.hostname || "";
      }
      result2 += url.port ? ":" + url.port : "";
      result2 += url.pathname || "";
      result2 += url.search || "";
      result2 += url.hash || "";
      return result2;
    }
    function Url() {
      this.protocol = null;
      this.slashes = null;
      this.auth = null;
      this.port = null;
      this.hostname = null;
      this.hash = null;
      this.search = null;
      this.pathname = null;
    }
    const protocolPattern = /^([a-z0-9.+-]+:)/i;
    const portPattern = /:[0-9]*$/;
    const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
    const delims = ["<", ">", '"', "`", " ", "\r", "\n", "	"];
    const unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims);
    const autoEscape = ["'"].concat(unwise);
    const nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape);
    const hostEndingChars = ["/", "?", "#"];
    const hostnameMaxLen = 255;
    const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/;
    const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
    const hostlessProtocol = {
      javascript: true,
      "javascript:": true
    };
    const slashedProtocol = {
      http: true,
      https: true,
      ftp: true,
      gopher: true,
      file: true,
      "http:": true,
      "https:": true,
      "ftp:": true,
      "gopher:": true,
      "file:": true
    };
    function urlParse(url, slashesDenoteHost) {
      if (url && url instanceof Url) return url;
      const u = new Url();
      u.parse(url, slashesDenoteHost);
      return u;
    }
    Url.prototype.parse = function(url, slashesDenoteHost) {
      let lowerProto, hec, slashes;
      let rest = url;
      rest = rest.trim();
      if (!slashesDenoteHost && url.split("#").length === 1) {
        const simplePath = simplePathPattern.exec(rest);
        if (simplePath) {
          this.pathname = simplePath[1];
          if (simplePath[2]) {
            this.search = simplePath[2];
          }
          return this;
        }
      }
      let proto = protocolPattern.exec(rest);
      if (proto) {
        proto = proto[0];
        lowerProto = proto.toLowerCase();
        this.protocol = proto;
        rest = rest.substr(proto.length);
      }
      if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
        slashes = rest.substr(0, 2) === "//";
        if (slashes && !(proto && hostlessProtocol[proto])) {
          rest = rest.substr(2);
          this.slashes = true;
        }
      }
      if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
        let hostEnd = -1;
        for (let i2 = 0; i2 < hostEndingChars.length; i2++) {
          hec = rest.indexOf(hostEndingChars[i2]);
          if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
            hostEnd = hec;
          }
        }
        let auth, atSign;
        if (hostEnd === -1) {
          atSign = rest.lastIndexOf("@");
        } else {
          atSign = rest.lastIndexOf("@", hostEnd);
        }
        if (atSign !== -1) {
          auth = rest.slice(0, atSign);
          rest = rest.slice(atSign + 1);
          this.auth = auth;
        }
        hostEnd = -1;
        for (let i2 = 0; i2 < nonHostChars.length; i2++) {
          hec = rest.indexOf(nonHostChars[i2]);
          if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
            hostEnd = hec;
          }
        }
        if (hostEnd === -1) {
          hostEnd = rest.length;
        }
        if (rest[hostEnd - 1] === ":") {
          hostEnd--;
        }
        const host = rest.slice(0, hostEnd);
        rest = rest.slice(hostEnd);
        this.parseHost(host);
        this.hostname = this.hostname || "";
        const ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
        if (!ipv6Hostname) {
          const hostparts = this.hostname.split(/\./);
          for (let i2 = 0, l = hostparts.length; i2 < l; i2++) {
            const part = hostparts[i2];
            if (!part) {
              continue;
            }
            if (!part.match(hostnamePartPattern)) {
              let newpart = "";
              for (let j2 = 0, k = part.length; j2 < k; j2++) {
                if (part.charCodeAt(j2) > 127) {
                  newpart += "x";
                } else {
                  newpart += part[j2];
                }
              }
              if (!newpart.match(hostnamePartPattern)) {
                const validParts = hostparts.slice(0, i2);
                const notHost = hostparts.slice(i2 + 1);
                const bit = part.match(hostnamePartStart);
                if (bit) {
                  validParts.push(bit[1]);
                  notHost.unshift(bit[2]);
                }
                if (notHost.length) {
                  rest = notHost.join(".") + rest;
                }
                this.hostname = validParts.join(".");
                break;
              }
            }
          }
        }
        if (this.hostname.length > hostnameMaxLen) {
          this.hostname = "";
        }
        if (ipv6Hostname) {
          this.hostname = this.hostname.substr(1, this.hostname.length - 2);
        }
      }
      const hash = rest.indexOf("#");
      if (hash !== -1) {
        this.hash = rest.substr(hash);
        rest = rest.slice(0, hash);
      }
      const qm = rest.indexOf("?");
      if (qm !== -1) {
        this.search = rest.substr(qm);
        rest = rest.slice(0, qm);
      }
      if (rest) {
        this.pathname = rest;
      }
      if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
        this.pathname = "";
      }
      return this;
    };
    Url.prototype.parseHost = function(host) {
      let port = portPattern.exec(host);
      if (port) {
        port = port[0];
        if (port !== ":") {
          this.port = port.substr(1);
        }
        host = host.substr(0, host.length - port.length);
      }
      if (host) {
        this.hostname = host;
      }
    };
    const mdurl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
      __proto__: null,
      decode: decode$1,
      encode: encode$1,
      format: format$1,
      parse: urlParse
    }, Symbol.toStringTag, { value: "Module" }));
    const Any = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
    const Cc = /[\0-\x1F\x7F-\x9F]/;
    const regex$1 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;
    const P = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/;
    const regex = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/;
    const Z$1 = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
    const ucmicro = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
      __proto__: null,
      Any,
      Cc,
      Cf: regex$1,
      P,
      S: regex,
      Z: Z$1
    }, Symbol.toStringTag, { value: "Module" }));
    const htmlDecodeTree = new Uint16Array(
      // prettier-ignore
      'ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTǇǋǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉ǲኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻ǲᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤĳạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ﬃɩᾹ\0\0᾽g;耀ﬀig;耀ﬄ;쀀𝔣lig;耀ﬁlig;쀀fjƀaltῙ῜ῡt;晭ig;耀ﬂns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒α‚‰‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସǳ⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗǈⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼ǲ㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map((c2) => c2.charCodeAt(0))
    );
    const xmlDecodeTree = new Uint16Array(
      // prettier-ignore
      "Ȁaglq	\x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map((c2) => c2.charCodeAt(0))
    );
    var _a$2;
    const decodeMap = /* @__PURE__ */ new Map([
      [0, 65533],
      // C1 Unicode control character reference replacements
      [128, 8364],
      [130, 8218],
      [131, 402],
      [132, 8222],
      [133, 8230],
      [134, 8224],
      [135, 8225],
      [136, 710],
      [137, 8240],
      [138, 352],
      [139, 8249],
      [140, 338],
      [142, 381],
      [145, 8216],
      [146, 8217],
      [147, 8220],
      [148, 8221],
      [149, 8226],
      [150, 8211],
      [151, 8212],
      [152, 732],
      [153, 8482],
      [154, 353],
      [155, 8250],
      [156, 339],
      [158, 382],
      [159, 376]
    ]);
    const fromCodePoint$2 = (
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
      (_a$2 = String.fromCodePoint) !== null && _a$2 !== void 0 ? _a$2 : function(codePoint) {
        let output2 = "";
        if (codePoint > 65535) {
          codePoint -= 65536;
          output2 += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
          codePoint = 56320 | codePoint & 1023;
        }
        output2 += String.fromCharCode(codePoint);
        return output2;
      }
    );
    function replaceCodePoint(codePoint) {
      var _a2;
      if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
        return 65533;
      }
      return (_a2 = decodeMap.get(codePoint)) !== null && _a2 !== void 0 ? _a2 : codePoint;
    }
    var CharCodes;
    (function(CharCodes2) {
      CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
      CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
      CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
      CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
      CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
      CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
      CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F";
      CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
      CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z";
      CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A";
      CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F";
      CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z";
    })(CharCodes || (CharCodes = {}));
    const TO_LOWER_BIT = 32;
    var BinTrieFlags;
    (function(BinTrieFlags2) {
      BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
      BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
      BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
    })(BinTrieFlags || (BinTrieFlags = {}));
    function isNumber(code2) {
      return code2 >= CharCodes.ZERO && code2 <= CharCodes.NINE;
    }
    function isHexadecimalCharacter(code2) {
      return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_F || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_F;
    }
    function isAsciiAlphaNumeric(code2) {
      return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_Z || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_Z || isNumber(code2);
    }
    function isEntityInAttributeInvalidEnd(code2) {
      return code2 === CharCodes.EQUALS || isAsciiAlphaNumeric(code2);
    }
    var EntityDecoderState;
    (function(EntityDecoderState2) {
      EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
      EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
      EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
      EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
      EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
    })(EntityDecoderState || (EntityDecoderState = {}));
    var DecodingMode;
    (function(DecodingMode2) {
      DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
      DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
      DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
    })(DecodingMode || (DecodingMode = {}));
    class EntityDecoder {
      constructor(decodeTree, emitCodePoint, errors2) {
        this.decodeTree = decodeTree;
        this.emitCodePoint = emitCodePoint;
        this.errors = errors2;
        this.state = EntityDecoderState.EntityStart;
        this.consumed = 1;
        this.result = 0;
        this.treeIndex = 0;
        this.excess = 1;
        this.decodeMode = DecodingMode.Strict;
      }
      /** Resets the instance to make it reusable. */
      startEntity(decodeMode) {
        this.decodeMode = decodeMode;
        this.state = EntityDecoderState.EntityStart;
        this.result = 0;
        this.treeIndex = 0;
        this.excess = 1;
        this.consumed = 1;
      }
      /**
       * Write an entity to the decoder. This can be called multiple times with partial entities.
       * If the entity is incomplete, the decoder will return -1.
       *
       * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
       * entity is incomplete, and resume when the next string is written.
       *
       * @param string The string containing the entity (or a continuation of the entity).
       * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      write(str2, offset) {
        switch (this.state) {
          case EntityDecoderState.EntityStart: {
            if (str2.charCodeAt(offset) === CharCodes.NUM) {
              this.state = EntityDecoderState.NumericStart;
              this.consumed += 1;
              return this.stateNumericStart(str2, offset + 1);
            }
            this.state = EntityDecoderState.NamedEntity;
            return this.stateNamedEntity(str2, offset);
          }
          case EntityDecoderState.NumericStart: {
            return this.stateNumericStart(str2, offset);
          }
          case EntityDecoderState.NumericDecimal: {
            return this.stateNumericDecimal(str2, offset);
          }
          case EntityDecoderState.NumericHex: {
            return this.stateNumericHex(str2, offset);
          }
          case EntityDecoderState.NamedEntity: {
            return this.stateNamedEntity(str2, offset);
          }
        }
      }
      /**
       * Switches between the numeric decimal and hexadecimal states.
       *
       * Equivalent to the `Numeric character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNumericStart(str2, offset) {
        if (offset >= str2.length) {
          return -1;
        }
        if ((str2.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
          this.state = EntityDecoderState.NumericHex;
          this.consumed += 1;
          return this.stateNumericHex(str2, offset + 1);
        }
        this.state = EntityDecoderState.NumericDecimal;
        return this.stateNumericDecimal(str2, offset);
      }
      addToNumericResult(str2, start, end, base2) {
        if (start !== end) {
          const digitCount = end - start;
          this.result = this.result * Math.pow(base2, digitCount) + parseInt(str2.substr(start, digitCount), base2);
          this.consumed += digitCount;
        }
      }
      /**
       * Parses a hexadecimal numeric entity.
       *
       * Equivalent to the `Hexademical character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNumericHex(str2, offset) {
        const startIdx = offset;
        while (offset < str2.length) {
          const char = str2.charCodeAt(offset);
          if (isNumber(char) || isHexadecimalCharacter(char)) {
            offset += 1;
          } else {
            this.addToNumericResult(str2, startIdx, offset, 16);
            return this.emitNumericEntity(char, 3);
          }
        }
        this.addToNumericResult(str2, startIdx, offset, 16);
        return -1;
      }
      /**
       * Parses a decimal numeric entity.
       *
       * Equivalent to the `Decimal character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNumericDecimal(str2, offset) {
        const startIdx = offset;
        while (offset < str2.length) {
          const char = str2.charCodeAt(offset);
          if (isNumber(char)) {
            offset += 1;
          } else {
            this.addToNumericResult(str2, startIdx, offset, 10);
            return this.emitNumericEntity(char, 2);
          }
        }
        this.addToNumericResult(str2, startIdx, offset, 10);
        return -1;
      }
      /**
       * Validate and emit a numeric entity.
       *
       * Implements the logic from the `Hexademical character reference start
       * state` and `Numeric character reference end state` in the HTML spec.
       *
       * @param lastCp The last code point of the entity. Used to see if the
       *               entity was terminated with a semicolon.
       * @param expectedLength The minimum number of characters that should be
       *                       consumed. Used to validate that at least one digit
       *                       was consumed.
       * @returns The number of characters that were consumed.
       */
      emitNumericEntity(lastCp, expectedLength) {
        var _a2;
        if (this.consumed <= expectedLength) {
          (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
          return 0;
        }
        if (lastCp === CharCodes.SEMI) {
          this.consumed += 1;
        } else if (this.decodeMode === DecodingMode.Strict) {
          return 0;
        }
        this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
        if (this.errors) {
          if (lastCp !== CharCodes.SEMI) {
            this.errors.missingSemicolonAfterCharacterReference();
          }
          this.errors.validateNumericCharacterReference(this.result);
        }
        return this.consumed;
      }
      /**
       * Parses a named entity.
       *
       * Equivalent to the `Named character reference state` in the HTML spec.
       *
       * @param str The string containing the entity (or a continuation of the entity).
       * @param offset The current offset.
       * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
       */
      stateNamedEntity(str2, offset) {
        const { decodeTree } = this;
        let current = decodeTree[this.treeIndex];
        let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
        for (; offset < str2.length; offset++, this.excess++) {
          const char = str2.charCodeAt(offset);
          this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
          if (this.treeIndex < 0) {
            return this.result === 0 || // If we are parsing an attribute
            this.decodeMode === DecodingMode.Attribute && // We shouldn't have consumed any characters after the entity,
            (valueLength === 0 || // And there should be no invalid characters.
            isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
          }
          current = decodeTree[this.treeIndex];
          valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
          if (valueLength !== 0) {
            if (char === CharCodes.SEMI) {
              return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
            }
            if (this.decodeMode !== DecodingMode.Strict) {
              this.result = this.treeIndex;
              this.consumed += this.excess;
              this.excess = 0;
            }
          }
        }
        return -1;
      }
      /**
       * Emit a named entity that was not terminated with a semicolon.
       *
       * @returns The number of characters consumed.
       */
      emitNotTerminatedNamedEntity() {
        var _a2;
        const { result: result2, decodeTree } = this;
        const valueLength = (decodeTree[result2] & BinTrieFlags.VALUE_LENGTH) >> 14;
        this.emitNamedEntityData(result2, valueLength, this.consumed);
        (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.missingSemicolonAfterCharacterReference();
        return this.consumed;
      }
      /**
       * Emit a named entity.
       *
       * @param result The index of the entity in the decode tree.
       * @param valueLength The number of bytes in the entity.
       * @param consumed The number of characters consumed.
       *
       * @returns The number of characters consumed.
       */
      emitNamedEntityData(result2, valueLength, consumed) {
        const { decodeTree } = this;
        this.emitCodePoint(valueLength === 1 ? decodeTree[result2] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result2 + 1], consumed);
        if (valueLength === 3) {
          this.emitCodePoint(decodeTree[result2 + 2], consumed);
        }
        return consumed;
      }
      /**
       * Signal to the parser that the end of the input was reached.
       *
       * Remaining data will be emitted and relevant errors will be produced.
       *
       * @returns The number of characters consumed.
       */
      end() {
        var _a2;
        switch (this.state) {
          case EntityDecoderState.NamedEntity: {
            return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
          }
          case EntityDecoderState.NumericDecimal: {
            return this.emitNumericEntity(0, 2);
          }
          case EntityDecoderState.NumericHex: {
            return this.emitNumericEntity(0, 3);
          }
          case EntityDecoderState.NumericStart: {
            (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
            return 0;
          }
          case EntityDecoderState.EntityStart: {
            return 0;
          }
        }
      }
    }
    function getDecoder(decodeTree) {
      let ret = "";
      const decoder = new EntityDecoder(decodeTree, (str2) => ret += fromCodePoint$2(str2));
      return function decodeWithTrie(str2, decodeMode) {
        let lastIndex = 0;
        let offset = 0;
        while ((offset = str2.indexOf("&", offset)) >= 0) {
          ret += str2.slice(lastIndex, offset);
          decoder.startEntity(decodeMode);
          const len = decoder.write(
            str2,
            // Skip the "&"
            offset + 1
          );
          if (len < 0) {
            lastIndex = offset + decoder.end();
            break;
          }
          lastIndex = offset + len;
          offset = len === 0 ? lastIndex + 1 : lastIndex;
        }
        const result2 = ret + str2.slice(lastIndex);
        ret = "";
        return result2;
      };
    }
    function determineBranch(decodeTree, current, nodeIdx, char) {
      const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
      const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
      if (branchCount === 0) {
        return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
      }
      if (jumpOffset) {
        const value2 = char - jumpOffset;
        return value2 < 0 || value2 >= branchCount ? -1 : decodeTree[nodeIdx + value2] - 1;
      }
      let lo2 = nodeIdx;
      let hi = lo2 + branchCount - 1;
      while (lo2 <= hi) {
        const mid = lo2 + hi >>> 1;
        const midVal = decodeTree[mid];
        if (midVal < char) {
          lo2 = mid + 1;
        } else if (midVal > char) {
          hi = mid - 1;
        } else {
          return decodeTree[mid + branchCount];
        }
      }
      return -1;
    }
    const htmlDecoder = getDecoder(htmlDecodeTree);
    getDecoder(xmlDecodeTree);
    function decodeHTML(str2, mode = DecodingMode.Legacy) {
      return htmlDecoder(str2, mode);
    }
    function _class$1(obj) {
      return Object.prototype.toString.call(obj);
    }
    function isString$1(obj) {
      return _class$1(obj) === "[object String]";
    }
    const _hasOwnProperty = Object.prototype.hasOwnProperty;
    function has(object, key2) {
      return _hasOwnProperty.call(object, key2);
    }
    function assign$1(obj) {
      const sources = Array.prototype.slice.call(arguments, 1);
      sources.forEach(function(source2) {
        if (!source2) {
          return;
        }
        if (typeof source2 !== "object") {
          throw new TypeError(source2 + "must be object");
        }
        Object.keys(source2).forEach(function(key2) {
          obj[key2] = source2[key2];
        });
      });
      return obj;
    }
    function arrayReplaceAt(src, pos2, newElements) {
      return [].concat(src.slice(0, pos2), newElements, src.slice(pos2 + 1));
    }
    function isValidEntityCode(c2) {
      if (c2 >= 55296 && c2 <= 57343) {
        return false;
      }
      if (c2 >= 64976 && c2 <= 65007) {
        return false;
      }
      if ((c2 & 65535) === 65535 || (c2 & 65535) === 65534) {
        return false;
      }
      if (c2 >= 0 && c2 <= 8) {
        return false;
      }
      if (c2 === 11) {
        return false;
      }
      if (c2 >= 14 && c2 <= 31) {
        return false;
      }
      if (c2 >= 127 && c2 <= 159) {
        return false;
      }
      if (c2 > 1114111) {
        return false;
      }
      return true;
    }
    function fromCodePoint$1(c2) {
      if (c2 > 65535) {
        c2 -= 65536;
        const surrogate1 = 55296 + (c2 >> 10);
        const surrogate2 = 56320 + (c2 & 1023);
        return String.fromCharCode(surrogate1, surrogate2);
      }
      return String.fromCharCode(c2);
    }
    const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
    const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;
    const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, "gi");
    const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;
    function replaceEntityPattern(match, name2) {
      if (name2.charCodeAt(0) === 35 && DIGITAL_ENTITY_TEST_RE.test(name2)) {
        const code2 = name2[1].toLowerCase() === "x" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
        if (isValidEntityCode(code2)) {
          return fromCodePoint$1(code2);
        }
        return match;
      }
      const decoded = decodeHTML(match);
      if (decoded !== match) {
        return decoded;
      }
      return match;
    }
    function unescapeMd(str2) {
      if (str2.indexOf("\\") < 0) {
        return str2;
      }
      return str2.replace(UNESCAPE_MD_RE, "$1");
    }
    function unescapeAll(str2) {
      if (str2.indexOf("\\") < 0 && str2.indexOf("&") < 0) {
        return str2;
      }
      return str2.replace(UNESCAPE_ALL_RE, function(match, escaped, entity2) {
        if (escaped) {
          return escaped;
        }
        return replaceEntityPattern(match, entity2);
      });
    }
    const HTML_ESCAPE_TEST_RE = /[&<>"]/;
    const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
    const HTML_REPLACEMENTS = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;"
    };
    function replaceUnsafeChar(ch3) {
      return HTML_REPLACEMENTS[ch3];
    }
    function escapeHtml(str2) {
      if (HTML_ESCAPE_TEST_RE.test(str2)) {
        return str2.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
      }
      return str2;
    }
    const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g;
    function escapeRE$1(str2) {
      return str2.replace(REGEXP_ESCAPE_RE, "\\$&");
    }
    function isSpace(code2) {
      switch (code2) {
        case 9:
        case 32:
          return true;
      }
      return false;
    }
    function isWhiteSpace(code2) {
      if (code2 >= 8192 && code2 <= 8202) {
        return true;
      }
      switch (code2) {
        case 9:
        case 10:
        case 11:
        case 12:
        case 13:
        case 32:
        case 160:
        case 5760:
        case 8239:
        case 8287:
        case 12288:
          return true;
      }
      return false;
    }
    function isPunctChar(ch3) {
      return P.test(ch3) || regex.test(ch3);
    }
    function isMdAsciiPunct(ch3) {
      switch (ch3) {
        case 33:
        case 34:
        case 35:
        case 36:
        case 37:
        case 38:
        case 39:
        case 40:
        case 41:
        case 42:
        case 43:
        case 44:
        case 45:
        case 46:
        case 47:
        case 58:
        case 59:
        case 60:
        case 61:
        case 62:
        case 63:
        case 64:
        case 91:
        case 92:
        case 93:
        case 94:
        case 95:
        case 96:
        case 123:
        case 124:
        case 125:
        case 126:
          return true;
        default:
          return false;
      }
    }
    function normalizeReference(str2) {
      str2 = str2.trim().replace(/\s+/g, " ");
      if ("ẞ".toLowerCase() === "Ṿ") {
        str2 = str2.replace(/ẞ/g, "ß");
      }
      return str2.toLowerCase().toUpperCase();
    }
    const lib$1 = { mdurl, ucmicro };
    const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
      __proto__: null,
      arrayReplaceAt,
      assign: assign$1,
      escapeHtml,
      escapeRE: escapeRE$1,
      fromCodePoint: fromCodePoint$1,
      has,
      isMdAsciiPunct,
      isPunctChar,
      isSpace,
      isString: isString$1,
      isValidEntityCode,
      isWhiteSpace,
      lib: lib$1,
      normalizeReference,
      unescapeAll,
      unescapeMd
    }, Symbol.toStringTag, { value: "Module" }));
    function parseLinkLabel(state, start, disableNested) {
      let level, found, marker, prevPos;
      const max2 = state.posMax;
      const oldPos = state.pos;
      state.pos = start + 1;
      level = 1;
      while (state.pos < max2) {
        marker = state.src.charCodeAt(state.pos);
        if (marker === 93) {
          level--;
          if (level === 0) {
            found = true;
            break;
          }
        }
        prevPos = state.pos;
        state.md.inline.skipToken(state);
        if (marker === 91) {
          if (prevPos === state.pos - 1) {
            level++;
          } else if (disableNested) {
            state.pos = oldPos;
            return -1;
          }
        }
      }
      let labelEnd = -1;
      if (found) {
        labelEnd = state.pos;
      }
      state.pos = oldPos;
      return labelEnd;
    }
    function parseLinkDestination(str2, start, max2) {
      let code2;
      let pos2 = start;
      const result2 = {
        ok: false,
        pos: 0,
        str: ""
      };
      if (str2.charCodeAt(pos2) === 60) {
        pos2++;
        while (pos2 < max2) {
          code2 = str2.charCodeAt(pos2);
          if (code2 === 10) {
            return result2;
          }
          if (code2 === 60) {
            return result2;
          }
          if (code2 === 62) {
            result2.pos = pos2 + 1;
            result2.str = unescapeAll(str2.slice(start + 1, pos2));
            result2.ok = true;
            return result2;
          }
          if (code2 === 92 && pos2 + 1 < max2) {
            pos2 += 2;
            continue;
          }
          pos2++;
        }
        return result2;
      }
      let level = 0;
      while (pos2 < max2) {
        code2 = str2.charCodeAt(pos2);
        if (code2 === 32) {
          break;
        }
        if (code2 < 32 || code2 === 127) {
          break;
        }
        if (code2 === 92 && pos2 + 1 < max2) {
          if (str2.charCodeAt(pos2 + 1) === 32) {
            break;
          }
          pos2 += 2;
          continue;
        }
        if (code2 === 40) {
          level++;
          if (level > 32) {
            return result2;
          }
        }
        if (code2 === 41) {
          if (level === 0) {
            break;
          }
          level--;
        }
        pos2++;
      }
      if (start === pos2) {
        return result2;
      }
      if (level !== 0) {
        return result2;
      }
      result2.str = unescapeAll(str2.slice(start, pos2));
      result2.pos = pos2;
      result2.ok = true;
      return result2;
    }
    function parseLinkTitle(str2, start, max2, prev_state) {
      let code2;
      let pos2 = start;
      const state = {
        // if `true`, this is a valid link title
        ok: false,
        // if `true`, this link can be continued on the next line
        can_continue: false,
        // if `ok`, it's the position of the first character after the closing marker
        pos: 0,
        // if `ok`, it's the unescaped title
        str: "",
        // expected closing marker character code
        marker: 0
      };
      if (prev_state) {
        state.str = prev_state.str;
        state.marker = prev_state.marker;
      } else {
        if (pos2 >= max2) {
          return state;
        }
        let marker = str2.charCodeAt(pos2);
        if (marker !== 34 && marker !== 39 && marker !== 40) {
          return state;
        }
        start++;
        pos2++;
        if (marker === 40) {
          marker = 41;
        }
        state.marker = marker;
      }
      while (pos2 < max2) {
        code2 = str2.charCodeAt(pos2);
        if (code2 === state.marker) {
          state.pos = pos2 + 1;
          state.str += unescapeAll(str2.slice(start, pos2));
          state.ok = true;
          return state;
        } else if (code2 === 40 && state.marker === 41) {
          return state;
        } else if (code2 === 92 && pos2 + 1 < max2) {
          pos2++;
        }
        pos2++;
      }
      state.can_continue = true;
      state.str += unescapeAll(str2.slice(start, pos2));
      return state;
    }
    const helpers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
      __proto__: null,
      parseLinkDestination,
      parseLinkLabel,
      parseLinkTitle
    }, Symbol.toStringTag, { value: "Module" }));
    const default_rules = {};
    default_rules.code_inline = function(tokens, idx, options2, env, slf) {
      const token2 = tokens[idx];
      return "<code" + slf.renderAttrs(token2) + ">" + escapeHtml(token2.content) + "</code>";
    };
    default_rules.code_block = function(tokens, idx, options2, env, slf) {
      const token2 = tokens[idx];
      return "<pre" + slf.renderAttrs(token2) + "><code>" + escapeHtml(tokens[idx].content) + "</code></pre>\n";
    };
    default_rules.fence = function(tokens, idx, options2, env, slf) {
      const token2 = tokens[idx];
      const info = token2.info ? unescapeAll(token2.info).trim() : "";
      let langName = "";
      let langAttrs = "";
      if (info) {
        const arr2 = info.split(/(\s+)/g);
        langName = arr2[0];
        langAttrs = arr2.slice(2).join("");
      }
      let highlighted;
      if (options2.highlight) {
        highlighted = options2.highlight(token2.content, langName, langAttrs) || escapeHtml(token2.content);
      } else {
        highlighted = escapeHtml(token2.content);
      }
      if (highlighted.indexOf("<pre") === 0) {
        return highlighted + "\n";
      }
      if (info) {
        const i2 = token2.attrIndex("class");
        const tmpAttrs = token2.attrs ? token2.attrs.slice() : [];
        if (i2 < 0) {
          tmpAttrs.push(["class", options2.langPrefix + langName]);
        } else {
          tmpAttrs[i2] = tmpAttrs[i2].slice();
          tmpAttrs[i2][1] += " " + options2.langPrefix + langName;
        }
        const tmpToken = {
          attrs: tmpAttrs
        };
        return `<pre><code${slf.renderAttrs(tmpToken)}>${highlighted}</code></pre>
`;
      }
      return `<pre><code${slf.renderAttrs(token2)}>${highlighted}</code></pre>
`;
    };
    default_rules.image = function(tokens, idx, options2, env, slf) {
      const token2 = tokens[idx];
      token2.attrs[token2.attrIndex("alt")][1] = slf.renderInlineAsText(token2.children, options2, env);
      return slf.renderToken(tokens, idx, options2);
    };
    default_rules.hardbreak = function(tokens, idx, options2) {
      return options2.xhtmlOut ? "<br />\n" : "<br>\n";
    };
    default_rules.softbreak = function(tokens, idx, options2) {
      return options2.breaks ? options2.xhtmlOut ? "<br />\n" : "<br>\n" : "\n";
    };
    default_rules.text = function(tokens, idx) {
      return escapeHtml(tokens[idx].content);
    };
    default_rules.html_block = function(tokens, idx) {
      return tokens[idx].content;
    };
    default_rules.html_inline = function(tokens, idx) {
      return tokens[idx].content;
    };
    function Renderer() {
      this.rules = assign$1({}, default_rules);
    }
    Renderer.prototype.renderAttrs = function renderAttrs(token2) {
      let i2, l, result2;
      if (!token2.attrs) {
        return "";
      }
      result2 = "";
      for (i2 = 0, l = token2.attrs.length; i2 < l; i2++) {
        result2 += " " + escapeHtml(token2.attrs[i2][0]) + '="' + escapeHtml(token2.attrs[i2][1]) + '"';
      }
      return result2;
    };
    Renderer.prototype.renderToken = function renderToken(tokens, idx, options2) {
      const token2 = tokens[idx];
      let result2 = "";
      if (token2.hidden) {
        return "";
      }
      if (token2.block && token2.nesting !== -1 && idx && tokens[idx - 1].hidden) {
        result2 += "\n";
      }
      result2 += (token2.nesting === -1 ? "</" : "<") + token2.tag;
      result2 += this.renderAttrs(token2);
      if (token2.nesting === 0 && options2.xhtmlOut) {
        result2 += " /";
      }
      let needLf = false;
      if (token2.block) {
        needLf = true;
        if (token2.nesting === 1) {
          if (idx + 1 < tokens.length) {
            const nextToken2 = tokens[idx + 1];
            if (nextToken2.type === "inline" || nextToken2.hidden) {
              needLf = false;
            } else if (nextToken2.nesting === -1 && nextToken2.tag === token2.tag) {
              needLf = false;
            }
          }
        }
      }
      result2 += needLf ? ">\n" : ">";
      return result2;
    };
    Renderer.prototype.renderInline = function(tokens, options2, env) {
      let result2 = "";
      const rules = this.rules;
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        const type = tokens[i2].type;
        if (typeof rules[type] !== "undefined") {
          result2 += rules[type](tokens, i2, options2, env, this);
        } else {
          result2 += this.renderToken(tokens, i2, options2);
        }
      }
      return result2;
    };
    Renderer.prototype.renderInlineAsText = function(tokens, options2, env) {
      let result2 = "";
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        switch (tokens[i2].type) {
          case "text":
            result2 += tokens[i2].content;
            break;
          case "image":
            result2 += this.renderInlineAsText(tokens[i2].children, options2, env);
            break;
          case "html_inline":
          case "html_block":
            result2 += tokens[i2].content;
            break;
          case "softbreak":
          case "hardbreak":
            result2 += "\n";
            break;
        }
      }
      return result2;
    };
    Renderer.prototype.render = function(tokens, options2, env) {
      let result2 = "";
      const rules = this.rules;
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        const type = tokens[i2].type;
        if (type === "inline") {
          result2 += this.renderInline(tokens[i2].children, options2, env);
        } else if (typeof rules[type] !== "undefined") {
          result2 += rules[type](tokens, i2, options2, env, this);
        } else {
          result2 += this.renderToken(tokens, i2, options2, env);
        }
      }
      return result2;
    };
    function Ruler() {
      this.__rules__ = [];
      this.__cache__ = null;
    }
    Ruler.prototype.__find__ = function(name2) {
      for (let i2 = 0; i2 < this.__rules__.length; i2++) {
        if (this.__rules__[i2].name === name2) {
          return i2;
        }
      }
      return -1;
    };
    Ruler.prototype.__compile__ = function() {
      const self2 = this;
      const chains = [""];
      self2.__rules__.forEach(function(rule) {
        if (!rule.enabled) {
          return;
        }
        rule.alt.forEach(function(altName) {
          if (chains.indexOf(altName) < 0) {
            chains.push(altName);
          }
        });
      });
      self2.__cache__ = {};
      chains.forEach(function(chain) {
        self2.__cache__[chain] = [];
        self2.__rules__.forEach(function(rule) {
          if (!rule.enabled) {
            return;
          }
          if (chain && rule.alt.indexOf(chain) < 0) {
            return;
          }
          self2.__cache__[chain].push(rule.fn);
        });
      });
    };
    Ruler.prototype.at = function(name2, fn2, options2) {
      const index2 = this.__find__(name2);
      const opt = options2 || {};
      if (index2 === -1) {
        throw new Error("Parser rule not found: " + name2);
      }
      this.__rules__[index2].fn = fn2;
      this.__rules__[index2].alt = opt.alt || [];
      this.__cache__ = null;
    };
    Ruler.prototype.before = function(beforeName, ruleName, fn2, options2) {
      const index2 = this.__find__(beforeName);
      const opt = options2 || {};
      if (index2 === -1) {
        throw new Error("Parser rule not found: " + beforeName);
      }
      this.__rules__.splice(index2, 0, {
        name: ruleName,
        enabled: true,
        fn: fn2,
        alt: opt.alt || []
      });
      this.__cache__ = null;
    };
    Ruler.prototype.after = function(afterName, ruleName, fn2, options2) {
      const index2 = this.__find__(afterName);
      const opt = options2 || {};
      if (index2 === -1) {
        throw new Error("Parser rule not found: " + afterName);
      }
      this.__rules__.splice(index2 + 1, 0, {
        name: ruleName,
        enabled: true,
        fn: fn2,
        alt: opt.alt || []
      });
      this.__cache__ = null;
    };
    Ruler.prototype.push = function(ruleName, fn2, options2) {
      const opt = options2 || {};
      this.__rules__.push({
        name: ruleName,
        enabled: true,
        fn: fn2,
        alt: opt.alt || []
      });
      this.__cache__ = null;
    };
    Ruler.prototype.enable = function(list2, ignoreInvalid) {
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      const result2 = [];
      list2.forEach(function(name2) {
        const idx = this.__find__(name2);
        if (idx < 0) {
          if (ignoreInvalid) {
            return;
          }
          throw new Error("Rules manager: invalid rule name " + name2);
        }
        this.__rules__[idx].enabled = true;
        result2.push(name2);
      }, this);
      this.__cache__ = null;
      return result2;
    };
    Ruler.prototype.enableOnly = function(list2, ignoreInvalid) {
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      this.__rules__.forEach(function(rule) {
        rule.enabled = false;
      });
      this.enable(list2, ignoreInvalid);
    };
    Ruler.prototype.disable = function(list2, ignoreInvalid) {
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      const result2 = [];
      list2.forEach(function(name2) {
        const idx = this.__find__(name2);
        if (idx < 0) {
          if (ignoreInvalid) {
            return;
          }
          throw new Error("Rules manager: invalid rule name " + name2);
        }
        this.__rules__[idx].enabled = false;
        result2.push(name2);
      }, this);
      this.__cache__ = null;
      return result2;
    };
    Ruler.prototype.getRules = function(chainName) {
      if (this.__cache__ === null) {
        this.__compile__();
      }
      return this.__cache__[chainName] || [];
    };
    function Token(type, tag, nesting) {
      this.type = type;
      this.tag = tag;
      this.attrs = null;
      this.map = null;
      this.nesting = nesting;
      this.level = 0;
      this.children = null;
      this.content = "";
      this.markup = "";
      this.info = "";
      this.meta = null;
      this.block = false;
      this.hidden = false;
    }
    Token.prototype.attrIndex = function attrIndex(name2) {
      if (!this.attrs) {
        return -1;
      }
      const attrs = this.attrs;
      for (let i2 = 0, len = attrs.length; i2 < len; i2++) {
        if (attrs[i2][0] === name2) {
          return i2;
        }
      }
      return -1;
    };
    Token.prototype.attrPush = function attrPush(attrData) {
      if (this.attrs) {
        this.attrs.push(attrData);
      } else {
        this.attrs = [attrData];
      }
    };
    Token.prototype.attrSet = function attrSet(name2, value2) {
      const idx = this.attrIndex(name2);
      const attrData = [name2, value2];
      if (idx < 0) {
        this.attrPush(attrData);
      } else {
        this.attrs[idx] = attrData;
      }
    };
    Token.prototype.attrGet = function attrGet(name2) {
      const idx = this.attrIndex(name2);
      let value2 = null;
      if (idx >= 0) {
        value2 = this.attrs[idx][1];
      }
      return value2;
    };
    Token.prototype.attrJoin = function attrJoin(name2, value2) {
      const idx = this.attrIndex(name2);
      if (idx < 0) {
        this.attrPush([name2, value2]);
      } else {
        this.attrs[idx][1] = this.attrs[idx][1] + " " + value2;
      }
    };
    function StateCore(src, md, env) {
      this.src = src;
      this.env = env;
      this.tokens = [];
      this.inlineMode = false;
      this.md = md;
    }
    StateCore.prototype.Token = Token;
    const NEWLINES_RE = /\r\n?|\n/g;
    const NULL_RE = /\0/g;
    function normalize(state) {
      let str2;
      str2 = state.src.replace(NEWLINES_RE, "\n");
      str2 = str2.replace(NULL_RE, "�");
      state.src = str2;
    }
    function block(state) {
      let token2;
      if (state.inlineMode) {
        token2 = new state.Token("inline", "", 0);
        token2.content = state.src;
        token2.map = [0, 1];
        token2.children = [];
        state.tokens.push(token2);
      } else {
        state.md.block.parse(state.src, state.md, state.env, state.tokens);
      }
    }
    function inline(state) {
      const tokens = state.tokens;
      for (let i2 = 0, l = tokens.length; i2 < l; i2++) {
        const tok = tokens[i2];
        if (tok.type === "inline") {
          state.md.inline.parse(tok.content, state.md, state.env, tok.children);
        }
      }
    }
    function isLinkOpen$1(str2) {
      return /^<a[>\s]/i.test(str2);
    }
    function isLinkClose$1(str2) {
      return /^<\/a\s*>/i.test(str2);
    }
    function linkify$1(state) {
      const blockTokens = state.tokens;
      if (!state.md.options.linkify) {
        return;
      }
      for (let j2 = 0, l = blockTokens.length; j2 < l; j2++) {
        if (blockTokens[j2].type !== "inline" || !state.md.linkify.pretest(blockTokens[j2].content)) {
          continue;
        }
        let tokens = blockTokens[j2].children;
        let htmlLinkLevel = 0;
        for (let i2 = tokens.length - 1; i2 >= 0; i2--) {
          const currentToken = tokens[i2];
          if (currentToken.type === "link_close") {
            i2--;
            while (tokens[i2].level !== currentToken.level && tokens[i2].type !== "link_open") {
              i2--;
            }
            continue;
          }
          if (currentToken.type === "html_inline") {
            if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) {
              htmlLinkLevel--;
            }
            if (isLinkClose$1(currentToken.content)) {
              htmlLinkLevel++;
            }
          }
          if (htmlLinkLevel > 0) {
            continue;
          }
          if (currentToken.type === "text" && state.md.linkify.test(currentToken.content)) {
            const text2 = currentToken.content;
            let links = state.md.linkify.match(text2);
            const nodes = [];
            let level = currentToken.level;
            let lastPos = 0;
            if (links.length > 0 && links[0].index === 0 && i2 > 0 && tokens[i2 - 1].type === "text_special") {
              links = links.slice(1);
            }
            for (let ln2 = 0; ln2 < links.length; ln2++) {
              const url = links[ln2].url;
              const fullUrl = state.md.normalizeLink(url);
              if (!state.md.validateLink(fullUrl)) {
                continue;
              }
              let urlText = links[ln2].text;
              if (!links[ln2].schema) {
                urlText = state.md.normalizeLinkText("http://" + urlText).replace(/^http:\/\//, "");
              } else if (links[ln2].schema === "mailto:" && !/^mailto:/i.test(urlText)) {
                urlText = state.md.normalizeLinkText("mailto:" + urlText).replace(/^mailto:/, "");
              } else {
                urlText = state.md.normalizeLinkText(urlText);
              }
              const pos2 = links[ln2].index;
              if (pos2 > lastPos) {
                const token2 = new state.Token("text", "", 0);
                token2.content = text2.slice(lastPos, pos2);
                token2.level = level;
                nodes.push(token2);
              }
              const token_o = new state.Token("link_open", "a", 1);
              token_o.attrs = [["href", fullUrl]];
              token_o.level = level++;
              token_o.markup = "linkify";
              token_o.info = "auto";
              nodes.push(token_o);
              const token_t = new state.Token("text", "", 0);
              token_t.content = urlText;
              token_t.level = level;
              nodes.push(token_t);
              const token_c = new state.Token("link_close", "a", -1);
              token_c.level = --level;
              token_c.markup = "linkify";
              token_c.info = "auto";
              nodes.push(token_c);
              lastPos = links[ln2].lastIndex;
            }
            if (lastPos < text2.length) {
              const token2 = new state.Token("text", "", 0);
              token2.content = text2.slice(lastPos);
              token2.level = level;
              nodes.push(token2);
            }
            blockTokens[j2].children = tokens = arrayReplaceAt(tokens, i2, nodes);
          }
        }
      }
    }
    const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
    const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i;
    const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig;
    const SCOPED_ABBR = {
      c: "©",
      r: "®",
      tm: "™"
    };
    function replaceFn(match, name2) {
      return SCOPED_ABBR[name2.toLowerCase()];
    }
    function replace_scoped(inlineTokens) {
      let inside_autolink = 0;
      for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
        const token2 = inlineTokens[i2];
        if (token2.type === "text" && !inside_autolink) {
          token2.content = token2.content.replace(SCOPED_ABBR_RE, replaceFn);
        }
        if (token2.type === "link_open" && token2.info === "auto") {
          inside_autolink--;
        }
        if (token2.type === "link_close" && token2.info === "auto") {
          inside_autolink++;
        }
      }
    }
    function replace_rare(inlineTokens) {
      let inside_autolink = 0;
      for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
        const token2 = inlineTokens[i2];
        if (token2.type === "text" && !inside_autolink) {
          if (RARE_RE.test(token2.content)) {
            token2.content = token2.content.replace(/\+-/g, "±").replace(/\.{2,}/g, "…").replace(/([?!])…/g, "$1..").replace(/([?!]){4,}/g, "$1$1$1").replace(/,{2,}/g, ",").replace(/(^|[^-])---(?=[^-]|$)/mg, "$1—").replace(/(^|\s)--(?=\s|$)/mg, "$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, "$1–");
          }
        }
        if (token2.type === "link_open" && token2.info === "auto") {
          inside_autolink--;
        }
        if (token2.type === "link_close" && token2.info === "auto") {
          inside_autolink++;
        }
      }
    }
    function replace$1(state) {
      let blkIdx;
      if (!state.md.options.typographer) {
        return;
      }
      for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
        if (state.tokens[blkIdx].type !== "inline") {
          continue;
        }
        if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
          replace_scoped(state.tokens[blkIdx].children);
        }
        if (RARE_RE.test(state.tokens[blkIdx].content)) {
          replace_rare(state.tokens[blkIdx].children);
        }
      }
    }
    const QUOTE_TEST_RE = /['"]/;
    const QUOTE_RE = /['"]/g;
    const APOSTROPHE = "’";
    function replaceAt(str2, index2, ch3) {
      return str2.slice(0, index2) + ch3 + str2.slice(index2 + 1);
    }
    function process_inlines(tokens, state) {
      let j2;
      const stack2 = [];
      for (let i2 = 0; i2 < tokens.length; i2++) {
        const token2 = tokens[i2];
        const thisLevel = tokens[i2].level;
        for (j2 = stack2.length - 1; j2 >= 0; j2--) {
          if (stack2[j2].level <= thisLevel) {
            break;
          }
        }
        stack2.length = j2 + 1;
        if (token2.type !== "text") {
          continue;
        }
        let text2 = token2.content;
        let pos2 = 0;
        let max2 = text2.length;
        OUTER:
          while (pos2 < max2) {
            QUOTE_RE.lastIndex = pos2;
            const t2 = QUOTE_RE.exec(text2);
            if (!t2) {
              break;
            }
            let canOpen = true;
            let canClose = true;
            pos2 = t2.index + 1;
            const isSingle = t2[0] === "'";
            let lastChar = 32;
            if (t2.index - 1 >= 0) {
              lastChar = text2.charCodeAt(t2.index - 1);
            } else {
              for (j2 = i2 - 1; j2 >= 0; j2--) {
                if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
                if (!tokens[j2].content) continue;
                lastChar = tokens[j2].content.charCodeAt(tokens[j2].content.length - 1);
                break;
              }
            }
            let nextChar = 32;
            if (pos2 < max2) {
              nextChar = text2.charCodeAt(pos2);
            } else {
              for (j2 = i2 + 1; j2 < tokens.length; j2++) {
                if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
                if (!tokens[j2].content) continue;
                nextChar = tokens[j2].content.charCodeAt(0);
                break;
              }
            }
            const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
            const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
            const isLastWhiteSpace = isWhiteSpace(lastChar);
            const isNextWhiteSpace = isWhiteSpace(nextChar);
            if (isNextWhiteSpace) {
              canOpen = false;
            } else if (isNextPunctChar) {
              if (!(isLastWhiteSpace || isLastPunctChar)) {
                canOpen = false;
              }
            }
            if (isLastWhiteSpace) {
              canClose = false;
            } else if (isLastPunctChar) {
              if (!(isNextWhiteSpace || isNextPunctChar)) {
                canClose = false;
              }
            }
            if (nextChar === 34 && t2[0] === '"') {
              if (lastChar >= 48 && lastChar <= 57) {
                canClose = canOpen = false;
              }
            }
            if (canOpen && canClose) {
              canOpen = isLastPunctChar;
              canClose = isNextPunctChar;
            }
            if (!canOpen && !canClose) {
              if (isSingle) {
                token2.content = replaceAt(token2.content, t2.index, APOSTROPHE);
              }
              continue;
            }
            if (canClose) {
              for (j2 = stack2.length - 1; j2 >= 0; j2--) {
                let item2 = stack2[j2];
                if (stack2[j2].level < thisLevel) {
                  break;
                }
                if (item2.single === isSingle && stack2[j2].level === thisLevel) {
                  item2 = stack2[j2];
                  let openQuote;
                  let closeQuote;
                  if (isSingle) {
                    openQuote = state.md.options.quotes[2];
                    closeQuote = state.md.options.quotes[3];
                  } else {
                    openQuote = state.md.options.quotes[0];
                    closeQuote = state.md.options.quotes[1];
                  }
                  token2.content = replaceAt(token2.content, t2.index, closeQuote);
                  tokens[item2.token].content = replaceAt(
                    tokens[item2.token].content,
                    item2.pos,
                    openQuote
                  );
                  pos2 += closeQuote.length - 1;
                  if (item2.token === i2) {
                    pos2 += openQuote.length - 1;
                  }
                  text2 = token2.content;
                  max2 = text2.length;
                  stack2.length = j2;
                  continue OUTER;
                }
              }
            }
            if (canOpen) {
              stack2.push({
                token: i2,
                pos: t2.index,
                single: isSingle,
                level: thisLevel
              });
            } else if (canClose && isSingle) {
              token2.content = replaceAt(token2.content, t2.index, APOSTROPHE);
            }
          }
      }
    }
    function smartquotes(state) {
      if (!state.md.options.typographer) {
        return;
      }
      for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
        if (state.tokens[blkIdx].type !== "inline" || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
          continue;
        }
        process_inlines(state.tokens[blkIdx].children, state);
      }
    }
    function text_join(state) {
      let curr, last;
      const blockTokens = state.tokens;
      const l = blockTokens.length;
      for (let j2 = 0; j2 < l; j2++) {
        if (blockTokens[j2].type !== "inline") continue;
        const tokens = blockTokens[j2].children;
        const max2 = tokens.length;
        for (curr = 0; curr < max2; curr++) {
          if (tokens[curr].type === "text_special") {
            tokens[curr].type = "text";
          }
        }
        for (curr = last = 0; curr < max2; curr++) {
          if (tokens[curr].type === "text" && curr + 1 < max2 && tokens[curr + 1].type === "text") {
            tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
          } else {
            if (curr !== last) {
              tokens[last] = tokens[curr];
            }
            last++;
          }
        }
        if (curr !== last) {
          tokens.length = last;
        }
      }
    }
    const _rules$2 = [
      ["normalize", normalize],
      ["block", block],
      ["inline", inline],
      ["linkify", linkify$1],
      ["replacements", replace$1],
      ["smartquotes", smartquotes],
      // `text_join` finds `text_special` tokens (for escape sequences)
      // and joins them with the rest of the text
      ["text_join", text_join]
    ];
    function Core$1() {
      this.ruler = new Ruler();
      for (let i2 = 0; i2 < _rules$2.length; i2++) {
        this.ruler.push(_rules$2[i2][0], _rules$2[i2][1]);
      }
    }
    Core$1.prototype.process = function(state) {
      const rules = this.ruler.getRules("");
      for (let i2 = 0, l = rules.length; i2 < l; i2++) {
        rules[i2](state);
      }
    };
    Core$1.prototype.State = StateCore;
    function StateBlock(src, md, env, tokens) {
      this.src = src;
      this.md = md;
      this.env = env;
      this.tokens = tokens;
      this.bMarks = [];
      this.eMarks = [];
      this.tShift = [];
      this.sCount = [];
      this.bsCount = [];
      this.blkIndent = 0;
      this.line = 0;
      this.lineMax = 0;
      this.tight = false;
      this.ddIndent = -1;
      this.listIndent = -1;
      this.parentType = "root";
      this.level = 0;
      const s = this.src;
      for (let start = 0, pos2 = 0, indent = 0, offset = 0, len = s.length, indent_found = false; pos2 < len; pos2++) {
        const ch3 = s.charCodeAt(pos2);
        if (!indent_found) {
          if (isSpace(ch3)) {
            indent++;
            if (ch3 === 9) {
              offset += 4 - offset % 4;
            } else {
              offset++;
            }
            continue;
          } else {
            indent_found = true;
          }
        }
        if (ch3 === 10 || pos2 === len - 1) {
          if (ch3 !== 10) {
            pos2++;
          }
          this.bMarks.push(start);
          this.eMarks.push(pos2);
          this.tShift.push(indent);
          this.sCount.push(offset);
          this.bsCount.push(0);
          indent_found = false;
          indent = 0;
          offset = 0;
          start = pos2 + 1;
        }
      }
      this.bMarks.push(s.length);
      this.eMarks.push(s.length);
      this.tShift.push(0);
      this.sCount.push(0);
      this.bsCount.push(0);
      this.lineMax = this.bMarks.length - 1;
    }
    StateBlock.prototype.push = function(type, tag, nesting) {
      const token2 = new Token(type, tag, nesting);
      token2.block = true;
      if (nesting < 0) this.level--;
      token2.level = this.level;
      if (nesting > 0) this.level++;
      this.tokens.push(token2);
      return token2;
    };
    StateBlock.prototype.isEmpty = function isEmpty(line2) {
      return this.bMarks[line2] + this.tShift[line2] >= this.eMarks[line2];
    };
    StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) {
      for (let max2 = this.lineMax; from < max2; from++) {
        if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) {
          break;
        }
      }
      return from;
    };
    StateBlock.prototype.skipSpaces = function skipSpaces(pos2) {
      for (let max2 = this.src.length; pos2 < max2; pos2++) {
        const ch3 = this.src.charCodeAt(pos2);
        if (!isSpace(ch3)) {
          break;
        }
      }
      return pos2;
    };
    StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos2, min2) {
      if (pos2 <= min2) {
        return pos2;
      }
      while (pos2 > min2) {
        if (!isSpace(this.src.charCodeAt(--pos2))) {
          return pos2 + 1;
        }
      }
      return pos2;
    };
    StateBlock.prototype.skipChars = function skipChars(pos2, code2) {
      for (let max2 = this.src.length; pos2 < max2; pos2++) {
        if (this.src.charCodeAt(pos2) !== code2) {
          break;
        }
      }
      return pos2;
    };
    StateBlock.prototype.skipCharsBack = function skipCharsBack(pos2, code2, min2) {
      if (pos2 <= min2) {
        return pos2;
      }
      while (pos2 > min2) {
        if (code2 !== this.src.charCodeAt(--pos2)) {
          return pos2 + 1;
        }
      }
      return pos2;
    };
    StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) {
      if (begin >= end) {
        return "";
      }
      const queue = new Array(end - begin);
      for (let i2 = 0, line2 = begin; line2 < end; line2++, i2++) {
        let lineIndent = 0;
        const lineStart = this.bMarks[line2];
        let first2 = lineStart;
        let last;
        if (line2 + 1 < end || keepLastLF) {
          last = this.eMarks[line2] + 1;
        } else {
          last = this.eMarks[line2];
        }
        while (first2 < last && lineIndent < indent) {
          const ch3 = this.src.charCodeAt(first2);
          if (isSpace(ch3)) {
            if (ch3 === 9) {
              lineIndent += 4 - (lineIndent + this.bsCount[line2]) % 4;
            } else {
              lineIndent++;
            }
          } else if (first2 - lineStart < this.tShift[line2]) {
            lineIndent++;
          } else {
            break;
          }
          first2++;
        }
        if (lineIndent > indent) {
          queue[i2] = new Array(lineIndent - indent + 1).join(" ") + this.src.slice(first2, last);
        } else {
          queue[i2] = this.src.slice(first2, last);
        }
      }
      return queue.join("");
    };
    StateBlock.prototype.Token = Token;
    const MAX_AUTOCOMPLETED_CELLS = 65536;
    function getLine(state, line2) {
      const pos2 = state.bMarks[line2] + state.tShift[line2];
      const max2 = state.eMarks[line2];
      return state.src.slice(pos2, max2);
    }
    function escapedSplit(str2) {
      const result2 = [];
      const max2 = str2.length;
      let pos2 = 0;
      let ch3 = str2.charCodeAt(pos2);
      let isEscaped = false;
      let lastPos = 0;
      let current = "";
      while (pos2 < max2) {
        if (ch3 === 124) {
          if (!isEscaped) {
            result2.push(current + str2.substring(lastPos, pos2));
            current = "";
            lastPos = pos2 + 1;
          } else {
            current += str2.substring(lastPos, pos2 - 1);
            lastPos = pos2;
          }
        }
        isEscaped = ch3 === 92;
        pos2++;
        ch3 = str2.charCodeAt(pos2);
      }
      result2.push(current + str2.substring(lastPos));
      return result2;
    }
    function table$2(state, startLine, endLine, silent) {
      if (startLine + 2 > endLine) {
        return false;
      }
      let nextLine = startLine + 1;
      if (state.sCount[nextLine] < state.blkIndent) {
        return false;
      }
      if (state.sCount[nextLine] - state.blkIndent >= 4) {
        return false;
      }
      let pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
      if (pos2 >= state.eMarks[nextLine]) {
        return false;
      }
      const firstCh = state.src.charCodeAt(pos2++);
      if (firstCh !== 124 && firstCh !== 45 && firstCh !== 58) {
        return false;
      }
      if (pos2 >= state.eMarks[nextLine]) {
        return false;
      }
      const secondCh = state.src.charCodeAt(pos2++);
      if (secondCh !== 124 && secondCh !== 45 && secondCh !== 58 && !isSpace(secondCh)) {
        return false;
      }
      if (firstCh === 45 && isSpace(secondCh)) {
        return false;
      }
      while (pos2 < state.eMarks[nextLine]) {
        const ch3 = state.src.charCodeAt(pos2);
        if (ch3 !== 124 && ch3 !== 45 && ch3 !== 58 && !isSpace(ch3)) {
          return false;
        }
        pos2++;
      }
      let lineText = getLine(state, startLine + 1);
      let columns = lineText.split("|");
      const aligns = [];
      for (let i2 = 0; i2 < columns.length; i2++) {
        const t2 = columns[i2].trim();
        if (!t2) {
          if (i2 === 0 || i2 === columns.length - 1) {
            continue;
          } else {
            return false;
          }
        }
        if (!/^:?-+:?$/.test(t2)) {
          return false;
        }
        if (t2.charCodeAt(t2.length - 1) === 58) {
          aligns.push(t2.charCodeAt(0) === 58 ? "center" : "right");
        } else if (t2.charCodeAt(0) === 58) {
          aligns.push("left");
        } else {
          aligns.push("");
        }
      }
      lineText = getLine(state, startLine).trim();
      if (lineText.indexOf("|") === -1) {
        return false;
      }
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      columns = escapedSplit(lineText);
      if (columns.length && columns[0] === "") columns.shift();
      if (columns.length && columns[columns.length - 1] === "") columns.pop();
      const columnCount = columns.length;
      if (columnCount === 0 || columnCount !== aligns.length) {
        return false;
      }
      if (silent) {
        return true;
      }
      const oldParentType = state.parentType;
      state.parentType = "table";
      const terminatorRules = state.md.block.ruler.getRules("blockquote");
      const token_to = state.push("table_open", "table", 1);
      const tableLines = [startLine, 0];
      token_to.map = tableLines;
      const token_tho = state.push("thead_open", "thead", 1);
      token_tho.map = [startLine, startLine + 1];
      const token_htro = state.push("tr_open", "tr", 1);
      token_htro.map = [startLine, startLine + 1];
      for (let i2 = 0; i2 < columns.length; i2++) {
        const token_ho = state.push("th_open", "th", 1);
        if (aligns[i2]) {
          token_ho.attrs = [["style", "text-align:" + aligns[i2]]];
        }
        const token_il = state.push("inline", "", 0);
        token_il.content = columns[i2].trim();
        token_il.children = [];
        state.push("th_close", "th", -1);
      }
      state.push("tr_close", "tr", -1);
      state.push("thead_close", "thead", -1);
      let tbodyLines;
      let autocompletedCells = 0;
      for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
        if (state.sCount[nextLine] < state.blkIndent) {
          break;
        }
        let terminate = false;
        for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
          if (terminatorRules[i2](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
        lineText = getLine(state, nextLine).trim();
        if (!lineText) {
          break;
        }
        if (state.sCount[nextLine] - state.blkIndent >= 4) {
          break;
        }
        columns = escapedSplit(lineText);
        if (columns.length && columns[0] === "") columns.shift();
        if (columns.length && columns[columns.length - 1] === "") columns.pop();
        autocompletedCells += columnCount - columns.length;
        if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) {
          break;
        }
        if (nextLine === startLine + 2) {
          const token_tbo = state.push("tbody_open", "tbody", 1);
          token_tbo.map = tbodyLines = [startLine + 2, 0];
        }
        const token_tro = state.push("tr_open", "tr", 1);
        token_tro.map = [nextLine, nextLine + 1];
        for (let i2 = 0; i2 < columnCount; i2++) {
          const token_tdo = state.push("td_open", "td", 1);
          if (aligns[i2]) {
            token_tdo.attrs = [["style", "text-align:" + aligns[i2]]];
          }
          const token_il = state.push("inline", "", 0);
          token_il.content = columns[i2] ? columns[i2].trim() : "";
          token_il.children = [];
          state.push("td_close", "td", -1);
        }
        state.push("tr_close", "tr", -1);
      }
      if (tbodyLines) {
        state.push("tbody_close", "tbody", -1);
        tbodyLines[1] = nextLine;
      }
      state.push("table_close", "table", -1);
      tableLines[1] = nextLine;
      state.parentType = oldParentType;
      state.line = nextLine;
      return true;
    }
    function code$3(state, startLine, endLine) {
      if (state.sCount[startLine] - state.blkIndent < 4) {
        return false;
      }
      let nextLine = startLine + 1;
      let last = nextLine;
      while (nextLine < endLine) {
        if (state.isEmpty(nextLine)) {
          nextLine++;
          continue;
        }
        if (state.sCount[nextLine] - state.blkIndent >= 4) {
          nextLine++;
          last = nextLine;
          continue;
        }
        break;
      }
      state.line = last;
      const token2 = state.push("code_block", "code", 0);
      token2.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + "\n";
      token2.map = [startLine, state.line];
      return true;
    }
    function fence(state, startLine, endLine, silent) {
      let pos2 = state.bMarks[startLine] + state.tShift[startLine];
      let max2 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (pos2 + 3 > max2) {
        return false;
      }
      const marker = state.src.charCodeAt(pos2);
      if (marker !== 126 && marker !== 96) {
        return false;
      }
      let mem = pos2;
      pos2 = state.skipChars(pos2, marker);
      let len = pos2 - mem;
      if (len < 3) {
        return false;
      }
      const markup = state.src.slice(mem, pos2);
      const params2 = state.src.slice(pos2, max2);
      if (marker === 96) {
        if (params2.indexOf(String.fromCharCode(marker)) >= 0) {
          return false;
        }
      }
      if (silent) {
        return true;
      }
      let nextLine = startLine;
      let haveEndMarker = false;
      for (; ; ) {
        nextLine++;
        if (nextLine >= endLine) {
          break;
        }
        pos2 = mem = state.bMarks[nextLine] + state.tShift[nextLine];
        max2 = state.eMarks[nextLine];
        if (pos2 < max2 && state.sCount[nextLine] < state.blkIndent) {
          break;
        }
        if (state.src.charCodeAt(pos2) !== marker) {
          continue;
        }
        if (state.sCount[nextLine] - state.blkIndent >= 4) {
          continue;
        }
        pos2 = state.skipChars(pos2, marker);
        if (pos2 - mem < len) {
          continue;
        }
        pos2 = state.skipSpaces(pos2);
        if (pos2 < max2) {
          continue;
        }
        haveEndMarker = true;
        break;
      }
      len = state.sCount[startLine];
      state.line = nextLine + (haveEndMarker ? 1 : 0);
      const token2 = state.push("fence", "code", 0);
      token2.info = params2;
      token2.content = state.getLines(startLine + 1, nextLine, len, true);
      token2.markup = markup;
      token2.map = [startLine, state.line];
      return true;
    }
    function blockquote(state, startLine, endLine, silent) {
      let pos2 = state.bMarks[startLine] + state.tShift[startLine];
      let max2 = state.eMarks[startLine];
      const oldLineMax = state.lineMax;
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (state.src.charCodeAt(pos2) !== 62) {
        return false;
      }
      if (silent) {
        return true;
      }
      const oldBMarks = [];
      const oldBSCount = [];
      const oldSCount = [];
      const oldTShift = [];
      const terminatorRules = state.md.block.ruler.getRules("blockquote");
      const oldParentType = state.parentType;
      state.parentType = "blockquote";
      let lastLineEmpty = false;
      let nextLine;
      for (nextLine = startLine; nextLine < endLine; nextLine++) {
        const isOutdented = state.sCount[nextLine] < state.blkIndent;
        pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
        max2 = state.eMarks[nextLine];
        if (pos2 >= max2) {
          break;
        }
        if (state.src.charCodeAt(pos2++) === 62 && !isOutdented) {
          let initial = state.sCount[nextLine] + 1;
          let spaceAfterMarker;
          let adjustTab;
          if (state.src.charCodeAt(pos2) === 32) {
            pos2++;
            initial++;
            adjustTab = false;
            spaceAfterMarker = true;
          } else if (state.src.charCodeAt(pos2) === 9) {
            spaceAfterMarker = true;
            if ((state.bsCount[nextLine] + initial) % 4 === 3) {
              pos2++;
              initial++;
              adjustTab = false;
            } else {
              adjustTab = true;
            }
          } else {
            spaceAfterMarker = false;
          }
          let offset = initial;
          oldBMarks.push(state.bMarks[nextLine]);
          state.bMarks[nextLine] = pos2;
          while (pos2 < max2) {
            const ch3 = state.src.charCodeAt(pos2);
            if (isSpace(ch3)) {
              if (ch3 === 9) {
                offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
              } else {
                offset++;
              }
            } else {
              break;
            }
            pos2++;
          }
          lastLineEmpty = pos2 >= max2;
          oldBSCount.push(state.bsCount[nextLine]);
          state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
          oldSCount.push(state.sCount[nextLine]);
          state.sCount[nextLine] = offset - initial;
          oldTShift.push(state.tShift[nextLine]);
          state.tShift[nextLine] = pos2 - state.bMarks[nextLine];
          continue;
        }
        if (lastLineEmpty) {
          break;
        }
        let terminate = false;
        for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
          if (terminatorRules[i2](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          state.lineMax = nextLine;
          if (state.blkIndent !== 0) {
            oldBMarks.push(state.bMarks[nextLine]);
            oldBSCount.push(state.bsCount[nextLine]);
            oldTShift.push(state.tShift[nextLine]);
            oldSCount.push(state.sCount[nextLine]);
            state.sCount[nextLine] -= state.blkIndent;
          }
          break;
        }
        oldBMarks.push(state.bMarks[nextLine]);
        oldBSCount.push(state.bsCount[nextLine]);
        oldTShift.push(state.tShift[nextLine]);
        oldSCount.push(state.sCount[nextLine]);
        state.sCount[nextLine] = -1;
      }
      const oldIndent = state.blkIndent;
      state.blkIndent = 0;
      const token_o = state.push("blockquote_open", "blockquote", 1);
      token_o.markup = ">";
      const lines = [startLine, 0];
      token_o.map = lines;
      state.md.block.tokenize(state, startLine, nextLine);
      const token_c = state.push("blockquote_close", "blockquote", -1);
      token_c.markup = ">";
      state.lineMax = oldLineMax;
      state.parentType = oldParentType;
      lines[1] = state.line;
      for (let i2 = 0; i2 < oldTShift.length; i2++) {
        state.bMarks[i2 + startLine] = oldBMarks[i2];
        state.tShift[i2 + startLine] = oldTShift[i2];
        state.sCount[i2 + startLine] = oldSCount[i2];
        state.bsCount[i2 + startLine] = oldBSCount[i2];
      }
      state.blkIndent = oldIndent;
      return true;
    }
    function hr(state, startLine, endLine, silent) {
      const max2 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      let pos2 = state.bMarks[startLine] + state.tShift[startLine];
      const marker = state.src.charCodeAt(pos2++);
      if (marker !== 42 && marker !== 45 && marker !== 95) {
        return false;
      }
      let cnt = 1;
      while (pos2 < max2) {
        const ch3 = state.src.charCodeAt(pos2++);
        if (ch3 !== marker && !isSpace(ch3)) {
          return false;
        }
        if (ch3 === marker) {
          cnt++;
        }
      }
      if (cnt < 3) {
        return false;
      }
      if (silent) {
        return true;
      }
      state.line = startLine + 1;
      const token2 = state.push("hr", "hr", 0);
      token2.map = [startLine, state.line];
      token2.markup = Array(cnt + 1).join(String.fromCharCode(marker));
      return true;
    }
    function skipBulletListMarker(state, startLine) {
      const max2 = state.eMarks[startLine];
      let pos2 = state.bMarks[startLine] + state.tShift[startLine];
      const marker = state.src.charCodeAt(pos2++);
      if (marker !== 42 && marker !== 45 && marker !== 43) {
        return -1;
      }
      if (pos2 < max2) {
        const ch3 = state.src.charCodeAt(pos2);
        if (!isSpace(ch3)) {
          return -1;
        }
      }
      return pos2;
    }
    function skipOrderedListMarker(state, startLine) {
      const start = state.bMarks[startLine] + state.tShift[startLine];
      const max2 = state.eMarks[startLine];
      let pos2 = start;
      if (pos2 + 1 >= max2) {
        return -1;
      }
      let ch3 = state.src.charCodeAt(pos2++);
      if (ch3 < 48 || ch3 > 57) {
        return -1;
      }
      for (; ; ) {
        if (pos2 >= max2) {
          return -1;
        }
        ch3 = state.src.charCodeAt(pos2++);
        if (ch3 >= 48 && ch3 <= 57) {
          if (pos2 - start >= 10) {
            return -1;
          }
          continue;
        }
        if (ch3 === 41 || ch3 === 46) {
          break;
        }
        return -1;
      }
      if (pos2 < max2) {
        ch3 = state.src.charCodeAt(pos2);
        if (!isSpace(ch3)) {
          return -1;
        }
      }
      return pos2;
    }
    function markTightParagraphs(state, idx) {
      const level = state.level + 2;
      for (let i2 = idx + 2, l = state.tokens.length - 2; i2 < l; i2++) {
        if (state.tokens[i2].level === level && state.tokens[i2].type === "paragraph_open") {
          state.tokens[i2 + 2].hidden = true;
          state.tokens[i2].hidden = true;
          i2 += 2;
        }
      }
    }
    function list$2(state, startLine, endLine, silent) {
      let max2, pos2, start, token2;
      let nextLine = startLine;
      let tight = true;
      if (state.sCount[nextLine] - state.blkIndent >= 4) {
        return false;
      }
      if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) {
        return false;
      }
      let isTerminatingParagraph = false;
      if (silent && state.parentType === "paragraph") {
        if (state.sCount[nextLine] >= state.blkIndent) {
          isTerminatingParagraph = true;
        }
      }
      let isOrdered;
      let markerValue;
      let posAfterMarker;
      if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) {
        isOrdered = true;
        start = state.bMarks[nextLine] + state.tShift[nextLine];
        markerValue = Number(state.src.slice(start, posAfterMarker - 1));
        if (isTerminatingParagraph && markerValue !== 1) return false;
      } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) {
        isOrdered = false;
      } else {
        return false;
      }
      if (isTerminatingParagraph) {
        if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false;
      }
      if (silent) {
        return true;
      }
      const markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
      const listTokIdx = state.tokens.length;
      if (isOrdered) {
        token2 = state.push("ordered_list_open", "ol", 1);
        if (markerValue !== 1) {
          token2.attrs = [["start", markerValue]];
        }
      } else {
        token2 = state.push("bullet_list_open", "ul", 1);
      }
      const listLines = [nextLine, 0];
      token2.map = listLines;
      token2.markup = String.fromCharCode(markerCharCode);
      let prevEmptyEnd = false;
      const terminatorRules = state.md.block.ruler.getRules("list");
      const oldParentType = state.parentType;
      state.parentType = "list";
      while (nextLine < endLine) {
        pos2 = posAfterMarker;
        max2 = state.eMarks[nextLine];
        const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]);
        let offset = initial;
        while (pos2 < max2) {
          const ch3 = state.src.charCodeAt(pos2);
          if (ch3 === 9) {
            offset += 4 - (offset + state.bsCount[nextLine]) % 4;
          } else if (ch3 === 32) {
            offset++;
          } else {
            break;
          }
          pos2++;
        }
        const contentStart = pos2;
        let indentAfterMarker;
        if (contentStart >= max2) {
          indentAfterMarker = 1;
        } else {
          indentAfterMarker = offset - initial;
        }
        if (indentAfterMarker > 4) {
          indentAfterMarker = 1;
        }
        const indent = initial + indentAfterMarker;
        token2 = state.push("list_item_open", "li", 1);
        token2.markup = String.fromCharCode(markerCharCode);
        const itemLines = [nextLine, 0];
        token2.map = itemLines;
        if (isOrdered) {
          token2.info = state.src.slice(start, posAfterMarker - 1);
        }
        const oldTight = state.tight;
        const oldTShift = state.tShift[nextLine];
        const oldSCount = state.sCount[nextLine];
        const oldListIndent = state.listIndent;
        state.listIndent = state.blkIndent;
        state.blkIndent = indent;
        state.tight = true;
        state.tShift[nextLine] = contentStart - state.bMarks[nextLine];
        state.sCount[nextLine] = offset;
        if (contentStart >= max2 && state.isEmpty(nextLine + 1)) {
          state.line = Math.min(state.line + 2, endLine);
        } else {
          state.md.block.tokenize(state, nextLine, endLine, true);
        }
        if (!state.tight || prevEmptyEnd) {
          tight = false;
        }
        prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1);
        state.blkIndent = state.listIndent;
        state.listIndent = oldListIndent;
        state.tShift[nextLine] = oldTShift;
        state.sCount[nextLine] = oldSCount;
        state.tight = oldTight;
        token2 = state.push("list_item_close", "li", -1);
        token2.markup = String.fromCharCode(markerCharCode);
        nextLine = state.line;
        itemLines[1] = nextLine;
        if (nextLine >= endLine) {
          break;
        }
        if (state.sCount[nextLine] < state.blkIndent) {
          break;
        }
        if (state.sCount[nextLine] - state.blkIndent >= 4) {
          break;
        }
        let terminate = false;
        for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
          if (terminatorRules[i2](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
        if (isOrdered) {
          posAfterMarker = skipOrderedListMarker(state, nextLine);
          if (posAfterMarker < 0) {
            break;
          }
          start = state.bMarks[nextLine] + state.tShift[nextLine];
        } else {
          posAfterMarker = skipBulletListMarker(state, nextLine);
          if (posAfterMarker < 0) {
            break;
          }
        }
        if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) {
          break;
        }
      }
      if (isOrdered) {
        token2 = state.push("ordered_list_close", "ol", -1);
      } else {
        token2 = state.push("bullet_list_close", "ul", -1);
      }
      token2.markup = String.fromCharCode(markerCharCode);
      listLines[1] = nextLine;
      state.line = nextLine;
      state.parentType = oldParentType;
      if (tight) {
        markTightParagraphs(state, listTokIdx);
      }
      return true;
    }
    function reference(state, startLine, _endLine, silent) {
      let pos2 = state.bMarks[startLine] + state.tShift[startLine];
      let max2 = state.eMarks[startLine];
      let nextLine = startLine + 1;
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (state.src.charCodeAt(pos2) !== 91) {
        return false;
      }
      function getNextLine(nextLine2) {
        const endLine = state.lineMax;
        if (nextLine2 >= endLine || state.isEmpty(nextLine2)) {
          return null;
        }
        let isContinuation = false;
        if (state.sCount[nextLine2] - state.blkIndent > 3) {
          isContinuation = true;
        }
        if (state.sCount[nextLine2] < 0) {
          isContinuation = true;
        }
        if (!isContinuation) {
          const terminatorRules = state.md.block.ruler.getRules("reference");
          const oldParentType = state.parentType;
          state.parentType = "reference";
          let terminate = false;
          for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
            if (terminatorRules[i2](state, nextLine2, endLine, true)) {
              terminate = true;
              break;
            }
          }
          state.parentType = oldParentType;
          if (terminate) {
            return null;
          }
        }
        const pos3 = state.bMarks[nextLine2] + state.tShift[nextLine2];
        const max3 = state.eMarks[nextLine2];
        return state.src.slice(pos3, max3 + 1);
      }
      let str2 = state.src.slice(pos2, max2 + 1);
      max2 = str2.length;
      let labelEnd = -1;
      for (pos2 = 1; pos2 < max2; pos2++) {
        const ch3 = str2.charCodeAt(pos2);
        if (ch3 === 91) {
          return false;
        } else if (ch3 === 93) {
          labelEnd = pos2;
          break;
        } else if (ch3 === 10) {
          const lineContent = getNextLine(nextLine);
          if (lineContent !== null) {
            str2 += lineContent;
            max2 = str2.length;
            nextLine++;
          }
        } else if (ch3 === 92) {
          pos2++;
          if (pos2 < max2 && str2.charCodeAt(pos2) === 10) {
            const lineContent = getNextLine(nextLine);
            if (lineContent !== null) {
              str2 += lineContent;
              max2 = str2.length;
              nextLine++;
            }
          }
        }
      }
      if (labelEnd < 0 || str2.charCodeAt(labelEnd + 1) !== 58) {
        return false;
      }
      for (pos2 = labelEnd + 2; pos2 < max2; pos2++) {
        const ch3 = str2.charCodeAt(pos2);
        if (ch3 === 10) {
          const lineContent = getNextLine(nextLine);
          if (lineContent !== null) {
            str2 += lineContent;
            max2 = str2.length;
            nextLine++;
          }
        } else if (isSpace(ch3)) ;
        else {
          break;
        }
      }
      const destRes = state.md.helpers.parseLinkDestination(str2, pos2, max2);
      if (!destRes.ok) {
        return false;
      }
      const href = state.md.normalizeLink(destRes.str);
      if (!state.md.validateLink(href)) {
        return false;
      }
      pos2 = destRes.pos;
      const destEndPos = pos2;
      const destEndLineNo = nextLine;
      const start = pos2;
      for (; pos2 < max2; pos2++) {
        const ch3 = str2.charCodeAt(pos2);
        if (ch3 === 10) {
          const lineContent = getNextLine(nextLine);
          if (lineContent !== null) {
            str2 += lineContent;
            max2 = str2.length;
            nextLine++;
          }
        } else if (isSpace(ch3)) ;
        else {
          break;
        }
      }
      let titleRes = state.md.helpers.parseLinkTitle(str2, pos2, max2);
      while (titleRes.can_continue) {
        const lineContent = getNextLine(nextLine);
        if (lineContent === null) break;
        str2 += lineContent;
        pos2 = max2;
        max2 = str2.length;
        nextLine++;
        titleRes = state.md.helpers.parseLinkTitle(str2, pos2, max2, titleRes);
      }
      let title2;
      if (pos2 < max2 && start !== pos2 && titleRes.ok) {
        title2 = titleRes.str;
        pos2 = titleRes.pos;
      } else {
        title2 = "";
        pos2 = destEndPos;
        nextLine = destEndLineNo;
      }
      while (pos2 < max2) {
        const ch3 = str2.charCodeAt(pos2);
        if (!isSpace(ch3)) {
          break;
        }
        pos2++;
      }
      if (pos2 < max2 && str2.charCodeAt(pos2) !== 10) {
        if (title2) {
          title2 = "";
          pos2 = destEndPos;
          nextLine = destEndLineNo;
          while (pos2 < max2) {
            const ch3 = str2.charCodeAt(pos2);
            if (!isSpace(ch3)) {
              break;
            }
            pos2++;
          }
        }
      }
      if (pos2 < max2 && str2.charCodeAt(pos2) !== 10) {
        return false;
      }
      const label2 = normalizeReference(str2.slice(1, labelEnd));
      if (!label2) {
        return false;
      }
      if (silent) {
        return true;
      }
      if (typeof state.env.references === "undefined") {
        state.env.references = {};
      }
      if (typeof state.env.references[label2] === "undefined") {
        state.env.references[label2] = { title: title2, href };
      }
      state.line = nextLine;
      return true;
    }
    const block_names = [
      "address",
      "article",
      "aside",
      "base",
      "basefont",
      "blockquote",
      "body",
      "caption",
      "center",
      "col",
      "colgroup",
      "dd",
      "details",
      "dialog",
      "dir",
      "div",
      "dl",
      "dt",
      "fieldset",
      "figcaption",
      "figure",
      "footer",
      "form",
      "frame",
      "frameset",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
      "head",
      "header",
      "hr",
      "html",
      "iframe",
      "legend",
      "li",
      "link",
      "main",
      "menu",
      "menuitem",
      "nav",
      "noframes",
      "ol",
      "optgroup",
      "option",
      "p",
      "param",
      "search",
      "section",
      "summary",
      "table",
      "tbody",
      "td",
      "tfoot",
      "th",
      "thead",
      "title",
      "tr",
      "track",
      "ul"
    ];
    const attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
    const unquoted = "[^\"'=<>`\\x00-\\x20]+";
    const single_quoted = "'[^']*'";
    const double_quoted = '"[^"]*"';
    const attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")";
    const attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)";
    const open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>";
    const close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";
    const comment$1 = "<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->";
    const processing = "<[?][\\s\\S]*?[?]>";
    const declaration = "<![A-Za-z][^>]*>";
    const cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>";
    const HTML_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + "|" + comment$1 + "|" + processing + "|" + declaration + "|" + cdata + ")");
    const HTML_OPEN_CLOSE_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + ")");
    const HTML_SEQUENCES = [
      [/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true],
      [/^<!--/, /-->/, true],
      [/^<\?/, /\?>/, true],
      [/^<![A-Z]/, />/, true],
      [/^<!\[CDATA\[/, /\]\]>/, true],
      [new RegExp("^</?(" + block_names.join("|") + ")(?=(\\s|/?>|$))", "i"), /^$/, true],
      [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false]
    ];
    function html_block(state, startLine, endLine, silent) {
      let pos2 = state.bMarks[startLine] + state.tShift[startLine];
      let max2 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (!state.md.options.html) {
        return false;
      }
      if (state.src.charCodeAt(pos2) !== 60) {
        return false;
      }
      let lineText = state.src.slice(pos2, max2);
      let i2 = 0;
      for (; i2 < HTML_SEQUENCES.length; i2++) {
        if (HTML_SEQUENCES[i2][0].test(lineText)) {
          break;
        }
      }
      if (i2 === HTML_SEQUENCES.length) {
        return false;
      }
      if (silent) {
        return HTML_SEQUENCES[i2][2];
      }
      let nextLine = startLine + 1;
      if (!HTML_SEQUENCES[i2][1].test(lineText)) {
        for (; nextLine < endLine; nextLine++) {
          if (state.sCount[nextLine] < state.blkIndent) {
            break;
          }
          pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
          max2 = state.eMarks[nextLine];
          lineText = state.src.slice(pos2, max2);
          if (HTML_SEQUENCES[i2][1].test(lineText)) {
            if (lineText.length !== 0) {
              nextLine++;
            }
            break;
          }
        }
      }
      state.line = nextLine;
      const token2 = state.push("html_block", "", 0);
      token2.map = [startLine, nextLine];
      token2.content = state.getLines(startLine, nextLine, state.blkIndent, true);
      return true;
    }
    function heading$1(state, startLine, endLine, silent) {
      let pos2 = state.bMarks[startLine] + state.tShift[startLine];
      let max2 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      let ch3 = state.src.charCodeAt(pos2);
      if (ch3 !== 35 || pos2 >= max2) {
        return false;
      }
      let level = 1;
      ch3 = state.src.charCodeAt(++pos2);
      while (ch3 === 35 && pos2 < max2 && level <= 6) {
        level++;
        ch3 = state.src.charCodeAt(++pos2);
      }
      if (level > 6 || pos2 < max2 && !isSpace(ch3)) {
        return false;
      }
      if (silent) {
        return true;
      }
      max2 = state.skipSpacesBack(max2, pos2);
      const tmp = state.skipCharsBack(max2, 35, pos2);
      if (tmp > pos2 && isSpace(state.src.charCodeAt(tmp - 1))) {
        max2 = tmp;
      }
      state.line = startLine + 1;
      const token_o = state.push("heading_open", "h" + String(level), 1);
      token_o.markup = "########".slice(0, level);
      token_o.map = [startLine, state.line];
      const token_i = state.push("inline", "", 0);
      token_i.content = state.src.slice(pos2, max2).trim();
      token_i.map = [startLine, state.line];
      token_i.children = [];
      const token_c = state.push("heading_close", "h" + String(level), -1);
      token_c.markup = "########".slice(0, level);
      return true;
    }
    function lheading(state, startLine, endLine) {
      const terminatorRules = state.md.block.ruler.getRules("paragraph");
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      const oldParentType = state.parentType;
      state.parentType = "paragraph";
      let level = 0;
      let marker;
      let nextLine = startLine + 1;
      for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
        if (state.sCount[nextLine] - state.blkIndent > 3) {
          continue;
        }
        if (state.sCount[nextLine] >= state.blkIndent) {
          let pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
          const max2 = state.eMarks[nextLine];
          if (pos2 < max2) {
            marker = state.src.charCodeAt(pos2);
            if (marker === 45 || marker === 61) {
              pos2 = state.skipChars(pos2, marker);
              pos2 = state.skipSpaces(pos2);
              if (pos2 >= max2) {
                level = marker === 61 ? 1 : 2;
                break;
              }
            }
          }
        }
        if (state.sCount[nextLine] < 0) {
          continue;
        }
        let terminate = false;
        for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
          if (terminatorRules[i2](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
      }
      if (!level) {
        return false;
      }
      const content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
      state.line = nextLine + 1;
      const token_o = state.push("heading_open", "h" + String(level), 1);
      token_o.markup = String.fromCharCode(marker);
      token_o.map = [startLine, state.line];
      const token_i = state.push("inline", "", 0);
      token_i.content = content2;
      token_i.map = [startLine, state.line - 1];
      token_i.children = [];
      const token_c = state.push("heading_close", "h" + String(level), -1);
      token_c.markup = String.fromCharCode(marker);
      state.parentType = oldParentType;
      return true;
    }
    function paragraph(state, startLine, endLine) {
      const terminatorRules = state.md.block.ruler.getRules("paragraph");
      const oldParentType = state.parentType;
      let nextLine = startLine + 1;
      state.parentType = "paragraph";
      for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
        if (state.sCount[nextLine] - state.blkIndent > 3) {
          continue;
        }
        if (state.sCount[nextLine] < 0) {
          continue;
        }
        let terminate = false;
        for (let i2 = 0, l = terminatorRules.length; i2 < l; i2++) {
          if (terminatorRules[i2](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
      }
      const content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
      state.line = nextLine;
      const token_o = state.push("paragraph_open", "p", 1);
      token_o.map = [startLine, state.line];
      const token_i = state.push("inline", "", 0);
      token_i.content = content2;
      token_i.map = [startLine, state.line];
      token_i.children = [];
      state.push("paragraph_close", "p", -1);
      state.parentType = oldParentType;
      return true;
    }
    const _rules$1 = [
      // First 2 params - rule name & source. Secondary array - list of rules,
      // which can be terminated by this one.
      ["table", table$2, ["paragraph", "reference"]],
      ["code", code$3],
      ["fence", fence, ["paragraph", "reference", "blockquote", "list"]],
      ["blockquote", blockquote, ["paragraph", "reference", "blockquote", "list"]],
      ["hr", hr, ["paragraph", "reference", "blockquote", "list"]],
      ["list", list$2, ["paragraph", "reference", "blockquote"]],
      ["reference", reference],
      ["html_block", html_block, ["paragraph", "reference", "blockquote"]],
      ["heading", heading$1, ["paragraph", "reference", "blockquote"]],
      ["lheading", lheading],
      ["paragraph", paragraph]
    ];
    function ParserBlock() {
      this.ruler = new Ruler();
      for (let i2 = 0; i2 < _rules$1.length; i2++) {
        this.ruler.push(_rules$1[i2][0], _rules$1[i2][1], { alt: (_rules$1[i2][2] || []).slice() });
      }
    }
    ParserBlock.prototype.tokenize = function(state, startLine, endLine) {
      const rules = this.ruler.getRules("");
      const len = rules.length;
      const maxNesting = state.md.options.maxNesting;
      let line2 = startLine;
      let hasEmptyLines = false;
      while (line2 < endLine) {
        state.line = line2 = state.skipEmptyLines(line2);
        if (line2 >= endLine) {
          break;
        }
        if (state.sCount[line2] < state.blkIndent) {
          break;
        }
        if (state.level >= maxNesting) {
          state.line = endLine;
          break;
        }
        const prevLine = state.line;
        let ok = false;
        for (let i2 = 0; i2 < len; i2++) {
          ok = rules[i2](state, line2, endLine, false);
          if (ok) {
            if (prevLine >= state.line) {
              throw new Error("block rule didn't increment state.line");
            }
            break;
          }
        }
        if (!ok) throw new Error("none of the block rules matched");
        state.tight = !hasEmptyLines;
        if (state.isEmpty(state.line - 1)) {
          hasEmptyLines = true;
        }
        line2 = state.line;
        if (line2 < endLine && state.isEmpty(line2)) {
          hasEmptyLines = true;
          line2++;
          state.line = line2;
        }
      }
    };
    ParserBlock.prototype.parse = function(src, md, env, outTokens) {
      if (!src) {
        return;
      }
      const state = new this.State(src, md, env, outTokens);
      this.tokenize(state, state.line, state.lineMax);
    };
    ParserBlock.prototype.State = StateBlock;
    function StateInline(src, md, env, outTokens) {
      this.src = src;
      this.env = env;
      this.md = md;
      this.tokens = outTokens;
      this.tokens_meta = Array(outTokens.length);
      this.pos = 0;
      this.posMax = this.src.length;
      this.level = 0;
      this.pending = "";
      this.pendingLevel = 0;
      this.cache = {};
      this.delimiters = [];
      this._prev_delimiters = [];
      this.backticks = {};
      this.backticksScanned = false;
      this.linkLevel = 0;
    }
    StateInline.prototype.pushPending = function() {
      const token2 = new Token("text", "", 0);
      token2.content = this.pending;
      token2.level = this.pendingLevel;
      this.tokens.push(token2);
      this.pending = "";
      return token2;
    };
    StateInline.prototype.push = function(type, tag, nesting) {
      if (this.pending) {
        this.pushPending();
      }
      const token2 = new Token(type, tag, nesting);
      let token_meta = null;
      if (nesting < 0) {
        this.level--;
        this.delimiters = this._prev_delimiters.pop();
      }
      token2.level = this.level;
      if (nesting > 0) {
        this.level++;
        this._prev_delimiters.push(this.delimiters);
        this.delimiters = [];
        token_meta = { delimiters: this.delimiters };
      }
      this.pendingLevel = this.level;
      this.tokens.push(token2);
      this.tokens_meta.push(token_meta);
      return token2;
    };
    StateInline.prototype.scanDelims = function(start, canSplitWord) {
      const max2 = this.posMax;
      const marker = this.src.charCodeAt(start);
      const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 32;
      let pos2 = start;
      while (pos2 < max2 && this.src.charCodeAt(pos2) === marker) {
        pos2++;
      }
      const count = pos2 - start;
      const nextChar = pos2 < max2 ? this.src.charCodeAt(pos2) : 32;
      const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
      const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
      const isLastWhiteSpace = isWhiteSpace(lastChar);
      const isNextWhiteSpace = isWhiteSpace(nextChar);
      const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar);
      const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar);
      const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar);
      const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar);
      return { can_open, can_close, length: count };
    };
    StateInline.prototype.Token = Token;
    function isTerminatorChar(ch3) {
      switch (ch3) {
        case 10:
        case 33:
        case 35:
        case 36:
        case 37:
        case 38:
        case 42:
        case 43:
        case 45:
        case 58:
        case 60:
        case 61:
        case 62:
        case 64:
        case 91:
        case 92:
        case 93:
        case 94:
        case 95:
        case 96:
        case 123:
        case 125:
        case 126:
          return true;
        default:
          return false;
      }
    }
    function text(state, silent) {
      let pos2 = state.pos;
      while (pos2 < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos2))) {
        pos2++;
      }
      if (pos2 === state.pos) {
        return false;
      }
      if (!silent) {
        state.pending += state.src.slice(state.pos, pos2);
      }
      state.pos = pos2;
      return true;
    }
    const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;
    function linkify(state, silent) {
      if (!state.md.options.linkify) return false;
      if (state.linkLevel > 0) return false;
      const pos2 = state.pos;
      const max2 = state.posMax;
      if (pos2 + 3 > max2) return false;
      if (state.src.charCodeAt(pos2) !== 58) return false;
      if (state.src.charCodeAt(pos2 + 1) !== 47) return false;
      if (state.src.charCodeAt(pos2 + 2) !== 47) return false;
      const match = state.pending.match(SCHEME_RE);
      if (!match) return false;
      const proto = match[1];
      const link2 = state.md.linkify.matchAtStart(state.src.slice(pos2 - proto.length));
      if (!link2) return false;
      let url = link2.url;
      if (url.length <= proto.length) return false;
      url = url.replace(/\*+$/, "");
      const fullUrl = state.md.normalizeLink(url);
      if (!state.md.validateLink(fullUrl)) return false;
      if (!silent) {
        state.pending = state.pending.slice(0, -proto.length);
        const token_o = state.push("link_open", "a", 1);
        token_o.attrs = [["href", fullUrl]];
        token_o.markup = "linkify";
        token_o.info = "auto";
        const token_t = state.push("text", "", 0);
        token_t.content = state.md.normalizeLinkText(url);
        const token_c = state.push("link_close", "a", -1);
        token_c.markup = "linkify";
        token_c.info = "auto";
      }
      state.pos += url.length - proto.length;
      return true;
    }
    function newline(state, silent) {
      let pos2 = state.pos;
      if (state.src.charCodeAt(pos2) !== 10) {
        return false;
      }
      const pmax = state.pending.length - 1;
      const max2 = state.posMax;
      if (!silent) {
        if (pmax >= 0 && state.pending.charCodeAt(pmax) === 32) {
          if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 32) {
            let ws = pmax - 1;
            while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 32) ws--;
            state.pending = state.pending.slice(0, ws);
            state.push("hardbreak", "br", 0);
          } else {
            state.pending = state.pending.slice(0, -1);
            state.push("softbreak", "br", 0);
          }
        } else {
          state.push("softbreak", "br", 0);
        }
      }
      pos2++;
      while (pos2 < max2 && isSpace(state.src.charCodeAt(pos2))) {
        pos2++;
      }
      state.pos = pos2;
      return true;
    }
    const ESCAPED = [];
    for (let i2 = 0; i2 < 256; i2++) {
      ESCAPED.push(0);
    }
    "\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(ch3) {
      ESCAPED[ch3.charCodeAt(0)] = 1;
    });
    function escape$2(state, silent) {
      let pos2 = state.pos;
      const max2 = state.posMax;
      if (state.src.charCodeAt(pos2) !== 92) return false;
      pos2++;
      if (pos2 >= max2) return false;
      let ch1 = state.src.charCodeAt(pos2);
      if (ch1 === 10) {
        if (!silent) {
          state.push("hardbreak", "br", 0);
        }
        pos2++;
        while (pos2 < max2) {
          ch1 = state.src.charCodeAt(pos2);
          if (!isSpace(ch1)) break;
          pos2++;
        }
        state.pos = pos2;
        return true;
      }
      let escapedStr = state.src[pos2];
      if (ch1 >= 55296 && ch1 <= 56319 && pos2 + 1 < max2) {
        const ch22 = state.src.charCodeAt(pos2 + 1);
        if (ch22 >= 56320 && ch22 <= 57343) {
          escapedStr += state.src[pos2 + 1];
          pos2++;
        }
      }
      const origStr = "\\" + escapedStr;
      if (!silent) {
        const token2 = state.push("text_special", "", 0);
        if (ch1 < 256 && ESCAPED[ch1] !== 0) {
          token2.content = escapedStr;
        } else {
          token2.content = origStr;
        }
        token2.markup = origStr;
        token2.info = "escape";
      }
      state.pos = pos2 + 1;
      return true;
    }
    function backtick(state, silent) {
      let pos2 = state.pos;
      const ch3 = state.src.charCodeAt(pos2);
      if (ch3 !== 96) {
        return false;
      }
      const start = pos2;
      pos2++;
      const max2 = state.posMax;
      while (pos2 < max2 && state.src.charCodeAt(pos2) === 96) {
        pos2++;
      }
      const marker = state.src.slice(start, pos2);
      const openerLength = marker.length;
      if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) {
        if (!silent) state.pending += marker;
        state.pos += openerLength;
        return true;
      }
      let matchEnd = pos2;
      let matchStart;
      while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) {
        matchEnd = matchStart + 1;
        while (matchEnd < max2 && state.src.charCodeAt(matchEnd) === 96) {
          matchEnd++;
        }
        const closerLength = matchEnd - matchStart;
        if (closerLength === openerLength) {
          if (!silent) {
            const token2 = state.push("code_inline", "code", 0);
            token2.markup = marker;
            token2.content = state.src.slice(pos2, matchStart).replace(/\n/g, " ").replace(/^ (.+) $/, "$1");
          }
          state.pos = matchEnd;
          return true;
        }
        state.backticks[closerLength] = matchStart;
      }
      state.backticksScanned = true;
      if (!silent) state.pending += marker;
      state.pos += openerLength;
      return true;
    }
    function strikethrough_tokenize(state, silent) {
      const start = state.pos;
      const marker = state.src.charCodeAt(start);
      if (silent) {
        return false;
      }
      if (marker !== 126) {
        return false;
      }
      const scanned = state.scanDelims(state.pos, true);
      let len = scanned.length;
      const ch3 = String.fromCharCode(marker);
      if (len < 2) {
        return false;
      }
      let token2;
      if (len % 2) {
        token2 = state.push("text", "", 0);
        token2.content = ch3;
        len--;
      }
      for (let i2 = 0; i2 < len; i2 += 2) {
        token2 = state.push("text", "", 0);
        token2.content = ch3 + ch3;
        state.delimiters.push({
          marker,
          length: 0,
          // disable "rule of 3" length checks meant for emphasis
          token: state.tokens.length - 1,
          end: -1,
          open: scanned.can_open,
          close: scanned.can_close
        });
      }
      state.pos += scanned.length;
      return true;
    }
    function postProcess$1(state, delimiters) {
      let token2;
      const loneMarkers = [];
      const max2 = delimiters.length;
      for (let i2 = 0; i2 < max2; i2++) {
        const startDelim = delimiters[i2];
        if (startDelim.marker !== 126) {
          continue;
        }
        if (startDelim.end === -1) {
          continue;
        }
        const endDelim = delimiters[startDelim.end];
        token2 = state.tokens[startDelim.token];
        token2.type = "s_open";
        token2.tag = "s";
        token2.nesting = 1;
        token2.markup = "~~";
        token2.content = "";
        token2 = state.tokens[endDelim.token];
        token2.type = "s_close";
        token2.tag = "s";
        token2.nesting = -1;
        token2.markup = "~~";
        token2.content = "";
        if (state.tokens[endDelim.token - 1].type === "text" && state.tokens[endDelim.token - 1].content === "~") {
          loneMarkers.push(endDelim.token - 1);
        }
      }
      while (loneMarkers.length) {
        const i2 = loneMarkers.pop();
        let j2 = i2 + 1;
        while (j2 < state.tokens.length && state.tokens[j2].type === "s_close") {
          j2++;
        }
        j2--;
        if (i2 !== j2) {
          token2 = state.tokens[j2];
          state.tokens[j2] = state.tokens[i2];
          state.tokens[i2] = token2;
        }
      }
    }
    function strikethrough_postProcess(state) {
      const tokens_meta = state.tokens_meta;
      const max2 = state.tokens_meta.length;
      postProcess$1(state, state.delimiters);
      for (let curr = 0; curr < max2; curr++) {
        if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
          postProcess$1(state, tokens_meta[curr].delimiters);
        }
      }
    }
    const r_strikethrough = {
      tokenize: strikethrough_tokenize,
      postProcess: strikethrough_postProcess
    };
    function emphasis_tokenize(state, silent) {
      const start = state.pos;
      const marker = state.src.charCodeAt(start);
      if (silent) {
        return false;
      }
      if (marker !== 95 && marker !== 42) {
        return false;
      }
      const scanned = state.scanDelims(state.pos, marker === 42);
      for (let i2 = 0; i2 < scanned.length; i2++) {
        const token2 = state.push("text", "", 0);
        token2.content = String.fromCharCode(marker);
        state.delimiters.push({
          // Char code of the starting marker (number).
          //
          marker,
          // Total length of these series of delimiters.
          //
          length: scanned.length,
          // A position of the token this delimiter corresponds to.
          //
          token: state.tokens.length - 1,
          // If this delimiter is matched as a valid opener, `end` will be
          // equal to its position, otherwise it's `-1`.
          //
          end: -1,
          // Boolean flags that determine if this delimiter could open or close
          // an emphasis.
          //
          open: scanned.can_open,
          close: scanned.can_close
        });
      }
      state.pos += scanned.length;
      return true;
    }
    function postProcess(state, delimiters) {
      const max2 = delimiters.length;
      for (let i2 = max2 - 1; i2 >= 0; i2--) {
        const startDelim = delimiters[i2];
        if (startDelim.marker !== 95 && startDelim.marker !== 42) {
          continue;
        }
        if (startDelim.end === -1) {
          continue;
        }
        const endDelim = delimiters[startDelim.end];
        const isStrong = i2 > 0 && delimiters[i2 - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent
        delimiters[i2 - 1].marker === startDelim.marker && delimiters[i2 - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match)
        delimiters[startDelim.end + 1].token === endDelim.token + 1;
        const ch3 = String.fromCharCode(startDelim.marker);
        const token_o = state.tokens[startDelim.token];
        token_o.type = isStrong ? "strong_open" : "em_open";
        token_o.tag = isStrong ? "strong" : "em";
        token_o.nesting = 1;
        token_o.markup = isStrong ? ch3 + ch3 : ch3;
        token_o.content = "";
        const token_c = state.tokens[endDelim.token];
        token_c.type = isStrong ? "strong_close" : "em_close";
        token_c.tag = isStrong ? "strong" : "em";
        token_c.nesting = -1;
        token_c.markup = isStrong ? ch3 + ch3 : ch3;
        token_c.content = "";
        if (isStrong) {
          state.tokens[delimiters[i2 - 1].token].content = "";
          state.tokens[delimiters[startDelim.end + 1].token].content = "";
          i2--;
        }
      }
    }
    function emphasis_post_process(state) {
      const tokens_meta = state.tokens_meta;
      const max2 = state.tokens_meta.length;
      postProcess(state, state.delimiters);
      for (let curr = 0; curr < max2; curr++) {
        if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
          postProcess(state, tokens_meta[curr].delimiters);
        }
      }
    }
    const r_emphasis = {
      tokenize: emphasis_tokenize,
      postProcess: emphasis_post_process
    };
    function link(state, silent) {
      let code2, label2, res, ref;
      let href = "";
      let title2 = "";
      let start = state.pos;
      let parseReference = true;
      if (state.src.charCodeAt(state.pos) !== 91) {
        return false;
      }
      const oldPos = state.pos;
      const max2 = state.posMax;
      const labelStart = state.pos + 1;
      const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
      if (labelEnd < 0) {
        return false;
      }
      let pos2 = labelEnd + 1;
      if (pos2 < max2 && state.src.charCodeAt(pos2) === 40) {
        parseReference = false;
        pos2++;
        for (; pos2 < max2; pos2++) {
          code2 = state.src.charCodeAt(pos2);
          if (!isSpace(code2) && code2 !== 10) {
            break;
          }
        }
        if (pos2 >= max2) {
          return false;
        }
        start = pos2;
        res = state.md.helpers.parseLinkDestination(state.src, pos2, state.posMax);
        if (res.ok) {
          href = state.md.normalizeLink(res.str);
          if (state.md.validateLink(href)) {
            pos2 = res.pos;
          } else {
            href = "";
          }
          start = pos2;
          for (; pos2 < max2; pos2++) {
            code2 = state.src.charCodeAt(pos2);
            if (!isSpace(code2) && code2 !== 10) {
              break;
            }
          }
          res = state.md.helpers.parseLinkTitle(state.src, pos2, state.posMax);
          if (pos2 < max2 && start !== pos2 && res.ok) {
            title2 = res.str;
            pos2 = res.pos;
            for (; pos2 < max2; pos2++) {
              code2 = state.src.charCodeAt(pos2);
              if (!isSpace(code2) && code2 !== 10) {
                break;
              }
            }
          }
        }
        if (pos2 >= max2 || state.src.charCodeAt(pos2) !== 41) {
          parseReference = true;
        }
        pos2++;
      }
      if (parseReference) {
        if (typeof state.env.references === "undefined") {
          return false;
        }
        if (pos2 < max2 && state.src.charCodeAt(pos2) === 91) {
          start = pos2 + 1;
          pos2 = state.md.helpers.parseLinkLabel(state, pos2);
          if (pos2 >= 0) {
            label2 = state.src.slice(start, pos2++);
          } else {
            pos2 = labelEnd + 1;
          }
        } else {
          pos2 = labelEnd + 1;
        }
        if (!label2) {
          label2 = state.src.slice(labelStart, labelEnd);
        }
        ref = state.env.references[normalizeReference(label2)];
        if (!ref) {
          state.pos = oldPos;
          return false;
        }
        href = ref.href;
        title2 = ref.title;
      }
      if (!silent) {
        state.pos = labelStart;
        state.posMax = labelEnd;
        const token_o = state.push("link_open", "a", 1);
        const attrs = [["href", href]];
        token_o.attrs = attrs;
        if (title2) {
          attrs.push(["title", title2]);
        }
        state.linkLevel++;
        state.md.inline.tokenize(state);
        state.linkLevel--;
        state.push("link_close", "a", -1);
      }
      state.pos = pos2;
      state.posMax = max2;
      return true;
    }
    function image(state, silent) {
      let code2, content2, label2, pos2, ref, res, title2, start;
      let href = "";
      const oldPos = state.pos;
      const max2 = state.posMax;
      if (state.src.charCodeAt(state.pos) !== 33) {
        return false;
      }
      if (state.src.charCodeAt(state.pos + 1) !== 91) {
        return false;
      }
      const labelStart = state.pos + 2;
      const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
      if (labelEnd < 0) {
        return false;
      }
      pos2 = labelEnd + 1;
      if (pos2 < max2 && state.src.charCodeAt(pos2) === 40) {
        pos2++;
        for (; pos2 < max2; pos2++) {
          code2 = state.src.charCodeAt(pos2);
          if (!isSpace(code2) && code2 !== 10) {
            break;
          }
        }
        if (pos2 >= max2) {
          return false;
        }
        start = pos2;
        res = state.md.helpers.parseLinkDestination(state.src, pos2, state.posMax);
        if (res.ok) {
          href = state.md.normalizeLink(res.str);
          if (state.md.validateLink(href)) {
            pos2 = res.pos;
          } else {
            href = "";
          }
        }
        start = pos2;
        for (; pos2 < max2; pos2++) {
          code2 = state.src.charCodeAt(pos2);
          if (!isSpace(code2) && code2 !== 10) {
            break;
          }
        }
        res = state.md.helpers.parseLinkTitle(state.src, pos2, state.posMax);
        if (pos2 < max2 && start !== pos2 && res.ok) {
          title2 = res.str;
          pos2 = res.pos;
          for (; pos2 < max2; pos2++) {
            code2 = state.src.charCodeAt(pos2);
            if (!isSpace(code2) && code2 !== 10) {
              break;
            }
          }
        } else {
          title2 = "";
        }
        if (pos2 >= max2 || state.src.charCodeAt(pos2) !== 41) {
          state.pos = oldPos;
          return false;
        }
        pos2++;
      } else {
        if (typeof state.env.references === "undefined") {
          return false;
        }
        if (pos2 < max2 && state.src.charCodeAt(pos2) === 91) {
          start = pos2 + 1;
          pos2 = state.md.helpers.parseLinkLabel(state, pos2);
          if (pos2 >= 0) {
            label2 = state.src.slice(start, pos2++);
          } else {
            pos2 = labelEnd + 1;
          }
        } else {
          pos2 = labelEnd + 1;
        }
        if (!label2) {
          label2 = state.src.slice(labelStart, labelEnd);
        }
        ref = state.env.references[normalizeReference(label2)];
        if (!ref) {
          state.pos = oldPos;
          return false;
        }
        href = ref.href;
        title2 = ref.title;
      }
      if (!silent) {
        content2 = state.src.slice(labelStart, labelEnd);
        const tokens = [];
        state.md.inline.parse(
          content2,
          state.md,
          state.env,
          tokens
        );
        const token2 = state.push("image", "img", 0);
        const attrs = [["src", href], ["alt", ""]];
        token2.attrs = attrs;
        token2.children = tokens;
        token2.content = content2;
        if (title2) {
          attrs.push(["title", title2]);
        }
      }
      state.pos = pos2;
      state.posMax = max2;
      return true;
    }
    const EMAIL_RE = /^([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])?)*)$/;
    const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;
    function autolink(state, silent) {
      let pos2 = state.pos;
      if (state.src.charCodeAt(pos2) !== 60) {
        return false;
      }
      const start = state.pos;
      const max2 = state.posMax;
      for (; ; ) {
        if (++pos2 >= max2) return false;
        const ch3 = state.src.charCodeAt(pos2);
        if (ch3 === 60) return false;
        if (ch3 === 62) break;
      }
      const url = state.src.slice(start + 1, pos2);
      if (AUTOLINK_RE.test(url)) {
        const fullUrl = state.md.normalizeLink(url);
        if (!state.md.validateLink(fullUrl)) {
          return false;
        }
        if (!silent) {
          const token_o = state.push("link_open", "a", 1);
          token_o.attrs = [["href", fullUrl]];
          token_o.markup = "autolink";
          token_o.info = "auto";
          const token_t = state.push("text", "", 0);
          token_t.content = state.md.normalizeLinkText(url);
          const token_c = state.push("link_close", "a", -1);
          token_c.markup = "autolink";
          token_c.info = "auto";
        }
        state.pos += url.length + 2;
        return true;
      }
      if (EMAIL_RE.test(url)) {
        const fullUrl = state.md.normalizeLink("mailto:" + url);
        if (!state.md.validateLink(fullUrl)) {
          return false;
        }
        if (!silent) {
          const token_o = state.push("link_open", "a", 1);
          token_o.attrs = [["href", fullUrl]];
          token_o.markup = "autolink";
          token_o.info = "auto";
          const token_t = state.push("text", "", 0);
          token_t.content = state.md.normalizeLinkText(url);
          const token_c = state.push("link_close", "a", -1);
          token_c.markup = "autolink";
          token_c.info = "auto";
        }
        state.pos += url.length + 2;
        return true;
      }
      return false;
    }
    function isLinkOpen(str2) {
      return /^<a[>\s]/i.test(str2);
    }
    function isLinkClose(str2) {
      return /^<\/a\s*>/i.test(str2);
    }
    function isLetter(ch3) {
      const lc = ch3 | 32;
      return lc >= 97 && lc <= 122;
    }
    function html_inline(state, silent) {
      if (!state.md.options.html) {
        return false;
      }
      const max2 = state.posMax;
      const pos2 = state.pos;
      if (state.src.charCodeAt(pos2) !== 60 || pos2 + 2 >= max2) {
        return false;
      }
      const ch3 = state.src.charCodeAt(pos2 + 1);
      if (ch3 !== 33 && ch3 !== 63 && ch3 !== 47 && !isLetter(ch3)) {
        return false;
      }
      const match = state.src.slice(pos2).match(HTML_TAG_RE);
      if (!match) {
        return false;
      }
      if (!silent) {
        const token2 = state.push("html_inline", "", 0);
        token2.content = match[0];
        if (isLinkOpen(token2.content)) state.linkLevel++;
        if (isLinkClose(token2.content)) state.linkLevel--;
      }
      state.pos += match[0].length;
      return true;
    }
    const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
    const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
    function entity(state, silent) {
      const pos2 = state.pos;
      const max2 = state.posMax;
      if (state.src.charCodeAt(pos2) !== 38) return false;
      if (pos2 + 1 >= max2) return false;
      const ch3 = state.src.charCodeAt(pos2 + 1);
      if (ch3 === 35) {
        const match = state.src.slice(pos2).match(DIGITAL_RE);
        if (match) {
          if (!silent) {
            const code2 = match[1][0].toLowerCase() === "x" ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10);
            const token2 = state.push("text_special", "", 0);
            token2.content = isValidEntityCode(code2) ? fromCodePoint$1(code2) : fromCodePoint$1(65533);
            token2.markup = match[0];
            token2.info = "entity";
          }
          state.pos += match[0].length;
          return true;
        }
      } else {
        const match = state.src.slice(pos2).match(NAMED_RE);
        if (match) {
          const decoded = decodeHTML(match[0]);
          if (decoded !== match[0]) {
            if (!silent) {
              const token2 = state.push("text_special", "", 0);
              token2.content = decoded;
              token2.markup = match[0];
              token2.info = "entity";
            }
            state.pos += match[0].length;
            return true;
          }
        }
      }
      return false;
    }
    function processDelimiters(delimiters) {
      const openersBottom = {};
      const max2 = delimiters.length;
      if (!max2) return;
      let headerIdx = 0;
      let lastTokenIdx = -2;
      const jumps = [];
      for (let closerIdx = 0; closerIdx < max2; closerIdx++) {
        const closer = delimiters[closerIdx];
        jumps.push(0);
        if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) {
          headerIdx = closerIdx;
        }
        lastTokenIdx = closer.token;
        closer.length = closer.length || 0;
        if (!closer.close) continue;
        if (!openersBottom.hasOwnProperty(closer.marker)) {
          openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1];
        }
        const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3];
        let openerIdx = headerIdx - jumps[headerIdx] - 1;
        let newMinOpenerIdx = openerIdx;
        for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) {
          const opener = delimiters[openerIdx];
          if (opener.marker !== closer.marker) continue;
          if (opener.open && opener.end < 0) {
            let isOddMatch = false;
            if (opener.close || closer.open) {
              if ((opener.length + closer.length) % 3 === 0) {
                if (opener.length % 3 !== 0 || closer.length % 3 !== 0) {
                  isOddMatch = true;
                }
              }
            }
            if (!isOddMatch) {
              const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0;
              jumps[closerIdx] = closerIdx - openerIdx + lastJump;
              jumps[openerIdx] = lastJump;
              closer.open = false;
              opener.end = closerIdx;
              opener.close = false;
              newMinOpenerIdx = -1;
              lastTokenIdx = -2;
              break;
            }
          }
        }
        if (newMinOpenerIdx !== -1) {
          openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx;
        }
      }
    }
    function link_pairs(state) {
      const tokens_meta = state.tokens_meta;
      const max2 = state.tokens_meta.length;
      processDelimiters(state.delimiters);
      for (let curr = 0; curr < max2; curr++) {
        if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
          processDelimiters(tokens_meta[curr].delimiters);
        }
      }
    }
    function fragments_join(state) {
      let curr, last;
      let level = 0;
      const tokens = state.tokens;
      const max2 = state.tokens.length;
      for (curr = last = 0; curr < max2; curr++) {
        if (tokens[curr].nesting < 0) level--;
        tokens[curr].level = level;
        if (tokens[curr].nesting > 0) level++;
        if (tokens[curr].type === "text" && curr + 1 < max2 && tokens[curr + 1].type === "text") {
          tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
        } else {
          if (curr !== last) {
            tokens[last] = tokens[curr];
          }
          last++;
        }
      }
      if (curr !== last) {
        tokens.length = last;
      }
    }
    const _rules = [
      ["text", text],
      ["linkify", linkify],
      ["newline", newline],
      ["escape", escape$2],
      ["backticks", backtick],
      ["strikethrough", r_strikethrough.tokenize],
      ["emphasis", r_emphasis.tokenize],
      ["link", link],
      ["image", image],
      ["autolink", autolink],
      ["html_inline", html_inline],
      ["entity", entity]
    ];
    const _rules2 = [
      ["balance_pairs", link_pairs],
      ["strikethrough", r_strikethrough.postProcess],
      ["emphasis", r_emphasis.postProcess],
      // rules for pairs separate '**' into its own text tokens, which may be left unused,
      // rule below merges unused segments back with the rest of the text
      ["fragments_join", fragments_join]
    ];
    function ParserInline() {
      this.ruler = new Ruler();
      for (let i2 = 0; i2 < _rules.length; i2++) {
        this.ruler.push(_rules[i2][0], _rules[i2][1]);
      }
      this.ruler2 = new Ruler();
      for (let i2 = 0; i2 < _rules2.length; i2++) {
        this.ruler2.push(_rules2[i2][0], _rules2[i2][1]);
      }
    }
    ParserInline.prototype.skipToken = function(state) {
      const pos2 = state.pos;
      const rules = this.ruler.getRules("");
      const len = rules.length;
      const maxNesting = state.md.options.maxNesting;
      const cache = state.cache;
      if (typeof cache[pos2] !== "undefined") {
        state.pos = cache[pos2];
        return;
      }
      let ok = false;
      if (state.level < maxNesting) {
        for (let i2 = 0; i2 < len; i2++) {
          state.level++;
          ok = rules[i2](state, true);
          state.level--;
          if (ok) {
            if (pos2 >= state.pos) {
              throw new Error("inline rule didn't increment state.pos");
            }
            break;
          }
        }
      } else {
        state.pos = state.posMax;
      }
      if (!ok) {
        state.pos++;
      }
      cache[pos2] = state.pos;
    };
    ParserInline.prototype.tokenize = function(state) {
      const rules = this.ruler.getRules("");
      const len = rules.length;
      const end = state.posMax;
      const maxNesting = state.md.options.maxNesting;
      while (state.pos < end) {
        const prevPos = state.pos;
        let ok = false;
        if (state.level < maxNesting) {
          for (let i2 = 0; i2 < len; i2++) {
            ok = rules[i2](state, false);
            if (ok) {
              if (prevPos >= state.pos) {
                throw new Error("inline rule didn't increment state.pos");
              }
              break;
            }
          }
        }
        if (ok) {
          if (state.pos >= end) {
            break;
          }
          continue;
        }
        state.pending += state.src[state.pos++];
      }
      if (state.pending) {
        state.pushPending();
      }
    };
    ParserInline.prototype.parse = function(str2, md, env, outTokens) {
      const state = new this.State(str2, md, env, outTokens);
      this.tokenize(state);
      const rules = this.ruler2.getRules("");
      const len = rules.length;
      for (let i2 = 0; i2 < len; i2++) {
        rules[i2](state);
      }
    };
    ParserInline.prototype.State = StateInline;
    function reFactory(opts) {
      const re2 = {};
      opts = opts || {};
      re2.src_Any = Any.source;
      re2.src_Cc = Cc.source;
      re2.src_Z = Z$1.source;
      re2.src_P = P.source;
      re2.src_ZPCc = [re2.src_Z, re2.src_P, re2.src_Cc].join("|");
      re2.src_ZCc = [re2.src_Z, re2.src_Cc].join("|");
      const text_separators = "[><｜]";
      re2.src_pseudo_letter = "(?:(?!" + text_separators + "|" + re2.src_ZPCc + ")" + re2.src_Any + ")";
      re2.src_ip4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
      re2.src_auth = "(?:(?:(?!" + re2.src_ZCc + "|[@/\\[\\]()]).)+@)?";
      re2.src_port = "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?";
      re2.src_host_terminator = "(?=$|" + text_separators + "|" + re2.src_ZPCc + ")(?!" + (opts["---"] ? "-(?!--)|" : "-|") + "_|:\\d|\\.-|\\.(?!$|" + re2.src_ZPCc + "))";
      re2.src_path = "(?:[/?#](?:(?!" + re2.src_ZCc + "|" + text_separators + `|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!` + re2.src_ZCc + "|\\]).)*\\]|\\((?:(?!" + re2.src_ZCc + "|[)]).)*\\)|\\{(?:(?!" + re2.src_ZCc + '|[}]).)*\\}|\\"(?:(?!' + re2.src_ZCc + `|["]).)+\\"|\\'(?:(?!` + re2.src_ZCc + "|[']).)+\\'|\\'(?=" + re2.src_pseudo_letter + "|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!" + re2.src_ZCc + "|[.]|$)|" + (opts["---"] ? "\\-(?!--(?:[^-]|$))(?:-*)|" : "\\-+|") + // allow `,,,` in paths
      ",(?!" + re2.src_ZCc + "|$)|;(?!" + re2.src_ZCc + "|$)|\\!+(?!" + re2.src_ZCc + "|[!]|$)|\\?(?!" + re2.src_ZCc + "|[?]|$))+|\\/)?";
      re2.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*';
      re2.src_xn = "xn--[a-z0-9\\-]{1,59}";
      re2.src_domain_root = // Allow letters & digits (http://test1)
      "(?:" + re2.src_xn + "|" + re2.src_pseudo_letter + "{1,63})";
      re2.src_domain = "(?:" + re2.src_xn + "|(?:" + re2.src_pseudo_letter + ")|(?:" + re2.src_pseudo_letter + "(?:-|" + re2.src_pseudo_letter + "){0,61}" + re2.src_pseudo_letter + "))";
      re2.src_host = "(?:(?:(?:(?:" + re2.src_domain + ")\\.)*" + re2.src_domain + "))";
      re2.tpl_host_fuzzy = "(?:" + re2.src_ip4 + "|(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%)))";
      re2.tpl_host_no_ip_fuzzy = "(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%))";
      re2.src_host_strict = re2.src_host + re2.src_host_terminator;
      re2.tpl_host_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_host_terminator;
      re2.src_host_port_strict = re2.src_host + re2.src_port + re2.src_host_terminator;
      re2.tpl_host_port_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_port + re2.src_host_terminator;
      re2.tpl_host_port_no_ip_fuzzy_strict = re2.tpl_host_no_ip_fuzzy + re2.src_port + re2.src_host_terminator;
      re2.tpl_host_fuzzy_test = "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + re2.src_ZPCc + "|>|$))";
      re2.tpl_email_fuzzy = "(^|" + text_separators + '|"|\\(|' + re2.src_ZCc + ")(" + re2.src_email_name + "@" + re2.tpl_host_fuzzy_strict + ")";
      re2.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
      // but can start with > (markdown blockquote)
      "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_fuzzy_strict + re2.src_path + ")";
      re2.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
      // but can start with > (markdown blockquote)
      "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_no_ip_fuzzy_strict + re2.src_path + ")";
      return re2;
    }
    function assign(obj) {
      const sources = Array.prototype.slice.call(arguments, 1);
      sources.forEach(function(source2) {
        if (!source2) {
          return;
        }
        Object.keys(source2).forEach(function(key2) {
          obj[key2] = source2[key2];
        });
      });
      return obj;
    }
    function _class(obj) {
      return Object.prototype.toString.call(obj);
    }
    function isString(obj) {
      return _class(obj) === "[object String]";
    }
    function isObject(obj) {
      return _class(obj) === "[object Object]";
    }
    function isRegExp(obj) {
      return _class(obj) === "[object RegExp]";
    }
    function isFunction(obj) {
      return _class(obj) === "[object Function]";
    }
    function escapeRE(str2) {
      return str2.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
    }
    const defaultOptions = {
      fuzzyLink: true,
      fuzzyEmail: true,
      fuzzyIP: false
    };
    function isOptionsObj(obj) {
      return Object.keys(obj || {}).reduce(function(acc, k) {
        return acc || defaultOptions.hasOwnProperty(k);
      }, false);
    }
    const defaultSchemas = {
      "http:": {
        validate: function(text2, pos2, self2) {
          const tail = text2.slice(pos2);
          if (!self2.re.http) {
            self2.re.http = new RegExp(
              "^\\/\\/" + self2.re.src_auth + self2.re.src_host_port_strict + self2.re.src_path,
              "i"
            );
          }
          if (self2.re.http.test(tail)) {
            return tail.match(self2.re.http)[0].length;
          }
          return 0;
        }
      },
      "https:": "http:",
      "ftp:": "http:",
      "//": {
        validate: function(text2, pos2, self2) {
          const tail = text2.slice(pos2);
          if (!self2.re.no_http) {
            self2.re.no_http = new RegExp(
              "^" + self2.re.src_auth + // Don't allow single-level domains, because of false positives like '//test'
              // with code comments
              "(?:localhost|(?:(?:" + self2.re.src_domain + ")\\.)+" + self2.re.src_domain_root + ")" + self2.re.src_port + self2.re.src_host_terminator + self2.re.src_path,
              "i"
            );
          }
          if (self2.re.no_http.test(tail)) {
            if (pos2 >= 3 && text2[pos2 - 3] === ":") {
              return 0;
            }
            if (pos2 >= 3 && text2[pos2 - 3] === "/") {
              return 0;
            }
            return tail.match(self2.re.no_http)[0].length;
          }
          return 0;
        }
      },
      "mailto:": {
        validate: function(text2, pos2, self2) {
          const tail = text2.slice(pos2);
          if (!self2.re.mailto) {
            self2.re.mailto = new RegExp(
              "^" + self2.re.src_email_name + "@" + self2.re.src_host_strict,
              "i"
            );
          }
          if (self2.re.mailto.test(tail)) {
            return tail.match(self2.re.mailto)[0].length;
          }
          return 0;
        }
      }
    };
    const tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]";
    const tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");
    function resetScanCache(self2) {
      self2.__index__ = -1;
      self2.__text_cache__ = "";
    }
    function createValidator(re2) {
      return function(text2, pos2) {
        const tail = text2.slice(pos2);
        if (re2.test(tail)) {
          return tail.match(re2)[0].length;
        }
        return 0;
      };
    }
    function createNormalizer() {
      return function(match, self2) {
        self2.normalize(match);
      };
    }
    function compile(self2) {
      const re2 = self2.re = reFactory(self2.__opts__);
      const tlds = self2.__tlds__.slice();
      self2.onCompile();
      if (!self2.__tlds_replaced__) {
        tlds.push(tlds_2ch_src_re);
      }
      tlds.push(re2.src_xn);
      re2.src_tlds = tlds.join("|");
      function untpl(tpl) {
        return tpl.replace("%TLDS%", re2.src_tlds);
      }
      re2.email_fuzzy = RegExp(untpl(re2.tpl_email_fuzzy), "i");
      re2.link_fuzzy = RegExp(untpl(re2.tpl_link_fuzzy), "i");
      re2.link_no_ip_fuzzy = RegExp(untpl(re2.tpl_link_no_ip_fuzzy), "i");
      re2.host_fuzzy_test = RegExp(untpl(re2.tpl_host_fuzzy_test), "i");
      const aliases2 = [];
      self2.__compiled__ = {};
      function schemaError(name2, val) {
        throw new Error('(LinkifyIt) Invalid schema "' + name2 + '": ' + val);
      }
      Object.keys(self2.__schemas__).forEach(function(name2) {
        const val = self2.__schemas__[name2];
        if (val === null) {
          return;
        }
        const compiled = { validate: null, link: null };
        self2.__compiled__[name2] = compiled;
        if (isObject(val)) {
          if (isRegExp(val.validate)) {
            compiled.validate = createValidator(val.validate);
          } else if (isFunction(val.validate)) {
            compiled.validate = val.validate;
          } else {
            schemaError(name2, val);
          }
          if (isFunction(val.normalize)) {
            compiled.normalize = val.normalize;
          } else if (!val.normalize) {
            compiled.normalize = createNormalizer();
          } else {
            schemaError(name2, val);
          }
          return;
        }
        if (isString(val)) {
          aliases2.push(name2);
          return;
        }
        schemaError(name2, val);
      });
      aliases2.forEach(function(alias) {
        if (!self2.__compiled__[self2.__schemas__[alias]]) {
          return;
        }
        self2.__compiled__[alias].validate = self2.__compiled__[self2.__schemas__[alias]].validate;
        self2.__compiled__[alias].normalize = self2.__compiled__[self2.__schemas__[alias]].normalize;
      });
      self2.__compiled__[""] = { validate: null, normalize: createNormalizer() };
      const slist = Object.keys(self2.__compiled__).filter(function(name2) {
        return name2.length > 0 && self2.__compiled__[name2];
      }).map(escapeRE).join("|");
      self2.re.schema_test = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "i");
      self2.re.schema_search = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "ig");
      self2.re.schema_at_start = RegExp("^" + self2.re.schema_search.source, "i");
      self2.re.pretest = RegExp(
        "(" + self2.re.schema_test.source + ")|(" + self2.re.host_fuzzy_test.source + ")|@",
        "i"
      );
      resetScanCache(self2);
    }
    function Match$1(self2, shift2) {
      const start = self2.__index__;
      const end = self2.__last_index__;
      const text2 = self2.__text_cache__.slice(start, end);
      this.schema = self2.__schema__.toLowerCase();
      this.index = start + shift2;
      this.lastIndex = end + shift2;
      this.raw = text2;
      this.text = text2;
      this.url = text2;
    }
    function createMatch(self2, shift2) {
      const match = new Match$1(self2, shift2);
      self2.__compiled__[match.schema].normalize(match, self2);
      return match;
    }
    function LinkifyIt(schemas, options2) {
      if (!(this instanceof LinkifyIt)) {
        return new LinkifyIt(schemas, options2);
      }
      if (!options2) {
        if (isOptionsObj(schemas)) {
          options2 = schemas;
          schemas = {};
        }
      }
      this.__opts__ = assign({}, defaultOptions, options2);
      this.__index__ = -1;
      this.__last_index__ = -1;
      this.__schema__ = "";
      this.__text_cache__ = "";
      this.__schemas__ = assign({}, defaultSchemas, schemas);
      this.__compiled__ = {};
      this.__tlds__ = tlds_default;
      this.__tlds_replaced__ = false;
      this.re = {};
      compile(this);
    }
    LinkifyIt.prototype.add = function add2(schema, definition) {
      this.__schemas__[schema] = definition;
      compile(this);
      return this;
    };
    LinkifyIt.prototype.set = function set(options2) {
      this.__opts__ = assign(this.__opts__, options2);
      return this;
    };
    LinkifyIt.prototype.test = function test(text2) {
      this.__text_cache__ = text2;
      this.__index__ = -1;
      if (!text2.length) {
        return false;
      }
      let m, ml, me, len, shift2, next, re2, tld_pos, at_pos;
      if (this.re.schema_test.test(text2)) {
        re2 = this.re.schema_search;
        re2.lastIndex = 0;
        while ((m = re2.exec(text2)) !== null) {
          len = this.testSchemaAt(text2, m[2], re2.lastIndex);
          if (len) {
            this.__schema__ = m[2];
            this.__index__ = m.index + m[1].length;
            this.__last_index__ = m.index + m[0].length + len;
            break;
          }
        }
      }
      if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
        tld_pos = text2.search(this.re.host_fuzzy_test);
        if (tld_pos >= 0) {
          if (this.__index__ < 0 || tld_pos < this.__index__) {
            if ((ml = text2.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) {
              shift2 = ml.index + ml[1].length;
              if (this.__index__ < 0 || shift2 < this.__index__) {
                this.__schema__ = "";
                this.__index__ = shift2;
                this.__last_index__ = ml.index + ml[0].length;
              }
            }
          }
        }
      }
      if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
        at_pos = text2.indexOf("@");
        if (at_pos >= 0) {
          if ((me = text2.match(this.re.email_fuzzy)) !== null) {
            shift2 = me.index + me[1].length;
            next = me.index + me[0].length;
            if (this.__index__ < 0 || shift2 < this.__index__ || shift2 === this.__index__ && next > this.__last_index__) {
              this.__schema__ = "mailto:";
              this.__index__ = shift2;
              this.__last_index__ = next;
            }
          }
        }
      }
      return this.__index__ >= 0;
    };
    LinkifyIt.prototype.pretest = function pretest(text2) {
      return this.re.pretest.test(text2);
    };
    LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text2, schema, pos2) {
      if (!this.__compiled__[schema.toLowerCase()]) {
        return 0;
      }
      return this.__compiled__[schema.toLowerCase()].validate(text2, pos2, this);
    };
    LinkifyIt.prototype.match = function match(text2) {
      const result2 = [];
      let shift2 = 0;
      if (this.__index__ >= 0 && this.__text_cache__ === text2) {
        result2.push(createMatch(this, shift2));
        shift2 = this.__last_index__;
      }
      let tail = shift2 ? text2.slice(shift2) : text2;
      while (this.test(tail)) {
        result2.push(createMatch(this, shift2));
        tail = tail.slice(this.__last_index__);
        shift2 += this.__last_index__;
      }
      if (result2.length) {
        return result2;
      }
      return null;
    };
    LinkifyIt.prototype.matchAtStart = function matchAtStart(text2) {
      this.__text_cache__ = text2;
      this.__index__ = -1;
      if (!text2.length) return null;
      const m = this.re.schema_at_start.exec(text2);
      if (!m) return null;
      const len = this.testSchemaAt(text2, m[2], m[0].length);
      if (!len) return null;
      this.__schema__ = m[2];
      this.__index__ = m.index + m[1].length;
      this.__last_index__ = m.index + m[0].length + len;
      return createMatch(this, 0);
    };
    LinkifyIt.prototype.tlds = function tlds(list2, keepOld) {
      list2 = Array.isArray(list2) ? list2 : [list2];
      if (!keepOld) {
        this.__tlds__ = list2.slice();
        this.__tlds_replaced__ = true;
        compile(this);
        return this;
      }
      this.__tlds__ = this.__tlds__.concat(list2).sort().filter(function(el, idx, arr2) {
        return el !== arr2[idx - 1];
      }).reverse();
      compile(this);
      return this;
    };
    LinkifyIt.prototype.normalize = function normalize2(match) {
      if (!match.schema) {
        match.url = "http://" + match.url;
      }
      if (match.schema === "mailto:" && !/^mailto:/i.test(match.url)) {
        match.url = "mailto:" + match.url;
      }
    };
    LinkifyIt.prototype.onCompile = function onCompile() {
    };
    const maxInt = 2147483647;
    const base$1 = 36;
    const tMin = 1;
    const tMax = 26;
    const skew = 38;
    const damp = 700;
    const initialBias = 72;
    const initialN = 128;
    const delimiter = "-";
    const regexPunycode = /^xn--/;
    const regexNonASCII = /[^\0-\x7F]/;
    const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
    const errors = {
      "overflow": "Overflow: input needs wider integers to process",
      "not-basic": "Illegal input >= 0x80 (not a basic code point)",
      "invalid-input": "Invalid input"
    };
    const baseMinusTMin = base$1 - tMin;
    const floor = Math.floor;
    const stringFromCharCode = String.fromCharCode;
    function error$1(type) {
      throw new RangeError(errors[type]);
    }
    function map(array, callback) {
      const result2 = [];
      let length = array.length;
      while (length--) {
        result2[length] = callback(array[length]);
      }
      return result2;
    }
    function mapDomain(domain, callback) {
      const parts = domain.split("@");
      let result2 = "";
      if (parts.length > 1) {
        result2 = parts[0] + "@";
        domain = parts[1];
      }
      domain = domain.replace(regexSeparators, ".");
      const labels = domain.split(".");
      const encoded = map(labels, callback).join(".");
      return result2 + encoded;
    }
    function ucs2decode(string2) {
      const output2 = [];
      let counter = 0;
      const length = string2.length;
      while (counter < length) {
        const value2 = string2.charCodeAt(counter++);
        if (value2 >= 55296 && value2 <= 56319 && counter < length) {
          const extra = string2.charCodeAt(counter++);
          if ((extra & 64512) == 56320) {
            output2.push(((value2 & 1023) << 10) + (extra & 1023) + 65536);
          } else {
            output2.push(value2);
            counter--;
          }
        } else {
          output2.push(value2);
        }
      }
      return output2;
    }
    const ucs2encode = (codePoints) => String.fromCodePoint(...codePoints);
    const basicToDigit = function(codePoint) {
      if (codePoint >= 48 && codePoint < 58) {
        return 26 + (codePoint - 48);
      }
      if (codePoint >= 65 && codePoint < 91) {
        return codePoint - 65;
      }
      if (codePoint >= 97 && codePoint < 123) {
        return codePoint - 97;
      }
      return base$1;
    };
    const digitToBasic = function(digit, flag) {
      return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
    };
    const adapt = function(delta, numPoints, firstTime) {
      let k = 0;
      delta = firstTime ? floor(delta / damp) : delta >> 1;
      delta += floor(delta / numPoints);
      for (; delta > baseMinusTMin * tMax >> 1; k += base$1) {
        delta = floor(delta / baseMinusTMin);
      }
      return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
    };
    const decode = function(input2) {
      const output2 = [];
      const inputLength = input2.length;
      let i2 = 0;
      let n = initialN;
      let bias = initialBias;
      let basic = input2.lastIndexOf(delimiter);
      if (basic < 0) {
        basic = 0;
      }
      for (let j2 = 0; j2 < basic; ++j2) {
        if (input2.charCodeAt(j2) >= 128) {
          error$1("not-basic");
        }
        output2.push(input2.charCodeAt(j2));
      }
      for (let index2 = basic > 0 ? basic + 1 : 0; index2 < inputLength; ) {
        const oldi = i2;
        for (let w2 = 1, k = base$1; ; k += base$1) {
          if (index2 >= inputLength) {
            error$1("invalid-input");
          }
          const digit = basicToDigit(input2.charCodeAt(index2++));
          if (digit >= base$1) {
            error$1("invalid-input");
          }
          if (digit > floor((maxInt - i2) / w2)) {
            error$1("overflow");
          }
          i2 += digit * w2;
          const t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
          if (digit < t2) {
            break;
          }
          const baseMinusT = base$1 - t2;
          if (w2 > floor(maxInt / baseMinusT)) {
            error$1("overflow");
          }
          w2 *= baseMinusT;
        }
        const out = output2.length + 1;
        bias = adapt(i2 - oldi, out, oldi == 0);
        if (floor(i2 / out) > maxInt - n) {
          error$1("overflow");
        }
        n += floor(i2 / out);
        i2 %= out;
        output2.splice(i2++, 0, n);
      }
      return String.fromCodePoint(...output2);
    };
    const encode = function(input2) {
      const output2 = [];
      input2 = ucs2decode(input2);
      const inputLength = input2.length;
      let n = initialN;
      let delta = 0;
      let bias = initialBias;
      for (const currentValue of input2) {
        if (currentValue < 128) {
          output2.push(stringFromCharCode(currentValue));
        }
      }
      const basicLength = output2.length;
      let handledCPCount = basicLength;
      if (basicLength) {
        output2.push(delimiter);
      }
      while (handledCPCount < inputLength) {
        let m = maxInt;
        for (const currentValue of input2) {
          if (currentValue >= n && currentValue < m) {
            m = currentValue;
          }
        }
        const handledCPCountPlusOne = handledCPCount + 1;
        if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
          error$1("overflow");
        }
        delta += (m - n) * handledCPCountPlusOne;
        n = m;
        for (const currentValue of input2) {
          if (currentValue < n && ++delta > maxInt) {
            error$1("overflow");
          }
          if (currentValue === n) {
            let q = delta;
            for (let k = base$1; ; k += base$1) {
              const t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
              if (q < t2) {
                break;
              }
              const qMinusT = q - t2;
              const baseMinusT = base$1 - t2;
              output2.push(
                stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0))
              );
              q = floor(qMinusT / baseMinusT);
            }
            output2.push(stringFromCharCode(digitToBasic(q, 0)));
            bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
            delta = 0;
            ++handledCPCount;
          }
        }
        ++delta;
        ++n;
      }
      return output2.join("");
    };
    const toUnicode = function(input2) {
      return mapDomain(input2, function(string2) {
        return regexPunycode.test(string2) ? decode(string2.slice(4).toLowerCase()) : string2;
      });
    };
    const toASCII = function(input2) {
      return mapDomain(input2, function(string2) {
        return regexNonASCII.test(string2) ? "xn--" + encode(string2) : string2;
      });
    };
    const punycode = {
      /**
       * A string representing the current Punycode.js version number.
       * @memberOf punycode
       * @type String
       */
      "version": "2.3.1",
      /**
       * An object of methods to convert from JavaScript's internal character
       * representation (UCS-2) to Unicode code points, and back.
       * @see <https://mathiasbynens.be/notes/javascript-encoding>
       * @memberOf punycode
       * @type Object
       */
      "ucs2": {
        "decode": ucs2decode,
        "encode": ucs2encode
      },
      "decode": decode,
      "encode": encode,
      "toASCII": toASCII,
      "toUnicode": toUnicode
    };
    const cfg_default = {
      options: {
        // Enable HTML tags in source
        html: false,
        // Use '/' to close single tags (<br />)
        xhtmlOut: false,
        // Convert '\n' in paragraphs into <br>
        breaks: false,
        // CSS language prefix for fenced blocks
        langPrefix: "language-",
        // autoconvert URL-like texts to links
        linkify: false,
        // Enable some language-neutral replacements + quotes beautification
        typographer: false,
        // Double + single quotes replacement pairs, when typographer enabled,
        // and smartquotes on. Could be either a String or an Array.
        //
        // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
        // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
        quotes: "“”‘’",
        /* “”‘’ */
        // Highlighter function. Should return escaped HTML,
        // or '' if the source string is not changed and should be escaped externaly.
        // If result starts with <pre... internal wrapper is skipped.
        //
        // function (/*str, lang*/) { return ''; }
        //
        highlight: null,
        // Internal protection, recursion limit
        maxNesting: 100
      },
      components: {
        core: {},
        block: {},
        inline: {}
      }
    };
    const cfg_zero = {
      options: {
        // Enable HTML tags in source
        html: false,
        // Use '/' to close single tags (<br />)
        xhtmlOut: false,
        // Convert '\n' in paragraphs into <br>
        breaks: false,
        // CSS language prefix for fenced blocks
        langPrefix: "language-",
        // autoconvert URL-like texts to links
        linkify: false,
        // Enable some language-neutral replacements + quotes beautification
        typographer: false,
        // Double + single quotes replacement pairs, when typographer enabled,
        // and smartquotes on. Could be either a String or an Array.
        //
        // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
        // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
        quotes: "“”‘’",
        /* “”‘’ */
        // Highlighter function. Should return escaped HTML,
        // or '' if the source string is not changed and should be escaped externaly.
        // If result starts with <pre... internal wrapper is skipped.
        //
        // function (/*str, lang*/) { return ''; }
        //
        highlight: null,
        // Internal protection, recursion limit
        maxNesting: 20
      },
      components: {
        core: {
          rules: [
            "normalize",
            "block",
            "inline",
            "text_join"
          ]
        },
        block: {
          rules: [
            "paragraph"
          ]
        },
        inline: {
          rules: [
            "text"
          ],
          rules2: [
            "balance_pairs",
            "fragments_join"
          ]
        }
      }
    };
    const cfg_commonmark = {
      options: {
        // Enable HTML tags in source
        html: true,
        // Use '/' to close single tags (<br />)
        xhtmlOut: true,
        // Convert '\n' in paragraphs into <br>
        breaks: false,
        // CSS language prefix for fenced blocks
        langPrefix: "language-",
        // autoconvert URL-like texts to links
        linkify: false,
        // Enable some language-neutral replacements + quotes beautification
        typographer: false,
        // Double + single quotes replacement pairs, when typographer enabled,
        // and smartquotes on. Could be either a String or an Array.
        //
        // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
        // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
        quotes: "“”‘’",
        /* “”‘’ */
        // Highlighter function. Should return escaped HTML,
        // or '' if the source string is not changed and should be escaped externaly.
        // If result starts with <pre... internal wrapper is skipped.
        //
        // function (/*str, lang*/) { return ''; }
        //
        highlight: null,
        // Internal protection, recursion limit
        maxNesting: 20
      },
      components: {
        core: {
          rules: [
            "normalize",
            "block",
            "inline",
            "text_join"
          ]
        },
        block: {
          rules: [
            "blockquote",
            "code",
            "fence",
            "heading",
            "hr",
            "html_block",
            "lheading",
            "list",
            "reference",
            "paragraph"
          ]
        },
        inline: {
          rules: [
            "autolink",
            "backticks",
            "emphasis",
            "entity",
            "escape",
            "html_inline",
            "image",
            "link",
            "newline",
            "text"
          ],
          rules2: [
            "balance_pairs",
            "emphasis",
            "fragments_join"
          ]
        }
      }
    };
    const config = {
      default: cfg_default,
      zero: cfg_zero,
      commonmark: cfg_commonmark
    };
    const BAD_PROTO_RE = /^(vbscript|javascript|file|data):/;
    const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/;
    function validateLink(url) {
      const str2 = url.trim().toLowerCase();
      return BAD_PROTO_RE.test(str2) ? GOOD_DATA_RE.test(str2) : true;
    }
    const RECODE_HOSTNAME_FOR = ["http:", "https:", "mailto:"];
    function normalizeLink(url) {
      const parsed = urlParse(url, true);
      if (parsed.hostname) {
        if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
          try {
            parsed.hostname = punycode.toASCII(parsed.hostname);
          } catch (er2) {
          }
        }
      }
      return encode$1(format$1(parsed));
    }
    function normalizeLinkText(url) {
      const parsed = urlParse(url, true);
      if (parsed.hostname) {
        if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
          try {
            parsed.hostname = punycode.toUnicode(parsed.hostname);
          } catch (er2) {
          }
        }
      }
      return decode$1(format$1(parsed), decode$1.defaultChars + "%");
    }
    function MarkdownIt(presetName, options2) {
      if (!(this instanceof MarkdownIt)) {
        return new MarkdownIt(presetName, options2);
      }
      if (!options2) {
        if (!isString$1(presetName)) {
          options2 = presetName || {};
          presetName = "default";
        }
      }
      this.inline = new ParserInline();
      this.block = new ParserBlock();
      this.core = new Core$1();
      this.renderer = new Renderer();
      this.linkify = new LinkifyIt();
      this.validateLink = validateLink;
      this.normalizeLink = normalizeLink;
      this.normalizeLinkText = normalizeLinkText;
      this.utils = utils;
      this.helpers = assign$1({}, helpers);
      this.options = {};
      this.configure(presetName);
      if (options2) {
        this.set(options2);
      }
    }
    MarkdownIt.prototype.set = function(options2) {
      assign$1(this.options, options2);
      return this;
    };
    MarkdownIt.prototype.configure = function(presets) {
      const self2 = this;
      if (isString$1(presets)) {
        const presetName = presets;
        presets = config[presetName];
        if (!presets) {
          throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
        }
      }
      if (!presets) {
        throw new Error("Wrong `markdown-it` preset, can't be empty");
      }
      if (presets.options) {
        self2.set(presets.options);
      }
      if (presets.components) {
        Object.keys(presets.components).forEach(function(name2) {
          if (presets.components[name2].rules) {
            self2[name2].ruler.enableOnly(presets.components[name2].rules);
          }
          if (presets.components[name2].rules2) {
            self2[name2].ruler2.enableOnly(presets.components[name2].rules2);
          }
        });
      }
      return this;
    };
    MarkdownIt.prototype.enable = function(list2, ignoreInvalid) {
      let result2 = [];
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      ["core", "block", "inline"].forEach(function(chain) {
        result2 = result2.concat(this[chain].ruler.enable(list2, true));
      }, this);
      result2 = result2.concat(this.inline.ruler2.enable(list2, true));
      const missed = list2.filter(function(name2) {
        return result2.indexOf(name2) < 0;
      });
      if (missed.length && !ignoreInvalid) {
        throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
      }
      return this;
    };
    MarkdownIt.prototype.disable = function(list2, ignoreInvalid) {
      let result2 = [];
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      ["core", "block", "inline"].forEach(function(chain) {
        result2 = result2.concat(this[chain].ruler.disable(list2, true));
      }, this);
      result2 = result2.concat(this.inline.ruler2.disable(list2, true));
      const missed = list2.filter(function(name2) {
        return result2.indexOf(name2) < 0;
      });
      if (missed.length && !ignoreInvalid) {
        throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
      }
      return this;
    };
    MarkdownIt.prototype.use = function(plugin) {
      const args = [this].concat(Array.prototype.slice.call(arguments, 1));
      plugin.apply(plugin, args);
      return this;
    };
    MarkdownIt.prototype.parse = function(src, env) {
      if (typeof src !== "string") {
        throw new Error("Input data should be a String");
      }
      const state = new this.core.State(src, this, env);
      this.core.process(state);
      return state.tokens;
    };
    MarkdownIt.prototype.render = function(src, env) {
      env = env || {};
      return this.renderer.render(this.parse(src, env), this.options, env);
    };
    MarkdownIt.prototype.parseInline = function(src, env) {
      const state = new this.core.State(src, this, env);
      state.inlineMode = true;
      this.core.process(state);
      return state.tokens;
    };
    MarkdownIt.prototype.renderInline = function(src, env) {
      env = env || {};
      return this.renderer.render(this.parseInline(src, env), this.options, env);
    };
    const MarkdownDiv = React$2.forwardRef(
      ({ markdown, style: style2, className: className2 }, ref) => {
        const escaped = markdown ? escape$1(markdown) : "";
        const preRendered = preRenderText(escaped);
        const protectedText = protectMarkdown(preRendered);
        let renderedHtml = protectedText;
        try {
          const md = MarkdownIt({
            breaks: true,
            html: true
          });
          renderedHtml = md.render(protectedText);
        } catch (ex) {
          console.log("Unable to markdown render content");
          console.error(ex);
        }
        const unescaped = unprotectMarkdown(renderedHtml);
        const withCode = unescapeCodeHtmlEntities(unescaped);
        const markup = { __html: withCode };
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            ref,
            dangerouslySetInnerHTML: markup,
            style: style2,
            className: clsx(className2, "markdown-content")
          }
        );
      }
    );
    const kLetterListPattern = /^([a-zA-Z][).]\s.*?)$/gm;
    const kCommonmarkReferenceLinkPattern = /\[([^\]]*)\]: (?!http)(.*)/g;
    const preRenderText = (txt) => {
      txt = txt.replace(/^[\u200B\u200C\u200D\u200E\u200F\uFEFF]/, "");
      return txt.replaceAll(
        kLetterListPattern,
        "<p class='markdown-ordered-list-item'>$1</p>"
      );
    };
    const protectMarkdown = (txt) => {
      return txt.replaceAll(
        kCommonmarkReferenceLinkPattern,
        "(open:767A125E)$1(close:767A125E) $2 "
      );
    };
    const unprotectMarkdown = (txt) => {
      txt = txt.replaceAll("(open:767A125E)", "[");
      txt = txt.replaceAll("(close:767A125E)", "]");
      return txt;
    };
    const escape$1 = (content2) => {
      return content2.replace(/[<>&'"]/g, (c2) => {
        switch (c2) {
          case "<":
            return "&lt;";
          case ">":
            return "&gt;";
          case "&":
            return "&amp;";
          case "'":
            return "&apos;";
          case '"':
            return "&quot;";
          default:
            throw new Error("Matched a value that isn't replaceable");
        }
      });
    };
    function unescapeCodeHtmlEntities(str2) {
      const htmlEntities = {
        "&lt;": "<",
        "&gt;": ">",
        "&amp;": "&",
        "&#x5C;": "\\",
        "&quot;": '"'
      };
      return str2.replace(
        /(<code[^>]*>)([\s\S]*?)(<\/code>)/gi,
        (_match, starttag, content2, endtag) => {
          return starttag + content2.replace(
            /&(?:amp|lt|gt|quot|#39|#x2F|#x5C|#96);/g,
            (entity2) => htmlEntities[entity2] || entity2
          ) + endtag;
        }
      );
    }
    const contentImage = "_contentImage_121dp_1";
    const styles$12 = {
      contentImage
    };
    const toolImage = "_toolImage_1j5uu_1";
    const output$1 = "_output_1j5uu_6";
    const textOutput = "_textOutput_1j5uu_10";
    const textCode = "_textCode_1j5uu_17";
    const styles$11 = {
      toolImage,
      output: output$1,
      textOutput,
      textCode
    };
    const ToolOutput = ({ output: output2 }) => {
      if (!output2) {
        return null;
      }
      const outputs = [];
      if (Array.isArray(output2)) {
        output2.forEach((out, idx) => {
          const key2 = `tool-output-${idx}`;
          if (out.type === "text") {
            outputs.push(/* @__PURE__ */ jsxRuntimeExports.jsx(ToolTextOutput, { text: out.text }, key2));
          } else {
            if (out.image.startsWith("data:")) {
              outputs.push(
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "img",
                  {
                    className: clsx(styles$11.toolImage),
                    src: out.image
                  },
                  key2
                )
              );
            } else {
              outputs.push(/* @__PURE__ */ jsxRuntimeExports.jsx(ToolTextOutput, { text: String(out.image) }, key2));
            }
          }
        });
      } else {
        outputs.push(
          /* @__PURE__ */ jsxRuntimeExports.jsx(ToolTextOutput, { text: String(output2) }, "tool-output-single")
        );
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$11.output), children: outputs });
    };
    const ToolTextOutput = ({ text: text2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: clsx(styles$11.textOutput, "tool-output"), children: /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: clsx("sourceCode", styles$11.textCode), children: text2.trim() }) });
    };
    const MessageContent = ({ contents: contents2 }) => {
      if (Array.isArray(contents2)) {
        return contents2.map((content2, index2) => {
          if (typeof content2 === "string") {
            return messageRenderers["text"].render(
              `text-content-${index2}`,
              {
                type: "text",
                text: content2
              },
              index2 === contents2.length - 1
            );
          } else {
            if (content2) {
              const renderer = messageRenderers[content2.type];
              if (renderer) {
                return renderer.render(
                  `text-${content2.type}-${index2}`,
                  content2,
                  index2 === contents2.length - 1
                );
              } else {
                console.error(`Unknown message content type '${content2.type}'`);
              }
            }
          }
        });
      } else {
        const contentText = {
          type: "text",
          text: contents2
        };
        return messageRenderers["text"].render(
          "text-message-content",
          contentText,
          true
        );
      }
    };
    const messageRenderers = {
      text: {
        render: (key2, content2, isLast) => {
          const c2 = content2;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            MarkdownDiv,
            {
              markdown: c2.text,
              className: isLast ? "no-last-para-padding" : ""
            },
            key2
          );
        }
      },
      reasoning: {
        render: (key2, content2, isLast) => {
          const r2 = content2;
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  "text-style-label",
                  "text-style-secondary",
                  isLast ? "no-last-para-padding" : ""
                ),
                children: "Reasoning"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ExpandablePanel, { collapse: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarkdownDiv,
              {
                markdown: r2.redacted ? "Reasoning encrypted by model provider." : r2.reasoning
              }
            ) })
          ] }, key2);
        }
      },
      image: {
        render: (key2, content2) => {
          const c2 = content2;
          if (c2.image.startsWith("data:")) {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("img", { src: c2.image, className: styles$12.contentImage }, key2);
          } else {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("code", { children: c2.image }, key2);
          }
        }
      },
      audio: {
        render: (key2, content2) => {
          const c2 = content2;
          return /* @__PURE__ */ jsxRuntimeExports.jsx("audio", { controls: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx("source", { src: c2.audio, type: mimeTypeForFormat(c2.format) }) }, key2);
        }
      },
      video: {
        render: (key2, content2) => {
          const c2 = content2;
          return /* @__PURE__ */ jsxRuntimeExports.jsx("video", { width: "500", height: "375", controls: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx("source", { src: c2.video, type: mimeTypeForFormat(c2.format) }) }, key2);
        }
      },
      tool: {
        render: (key2, content2) => {
          const c2 = content2;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ToolOutput, { output: c2.content }, key2);
        }
      }
    };
    const mimeTypeForFormat = (format2) => {
      switch (format2) {
        case "mov":
          return "video/quicktime";
        case "wav":
          return "audio/wav";
        case "mp3":
          return "audio/mpeg";
        case "mp4":
          return "video/mp4";
        case "mpeg":
          return "video/mpeg";
      }
    };
    const resolveToolInput = (fn2, toolArgs) => {
      const toolName = fn2;
      const [inputKey, highlightLanguage] = extractInputMetadata(toolName);
      const { input: input2, args } = extractInput(
        toolArgs,
        inputKey
      );
      const functionCall = args.length > 0 ? `${toolName}(${args.join(", ")})` : toolName;
      return {
        functionCall,
        input: input2,
        highlightLanguage
      };
    };
    const extractInputMetadata = (toolName) => {
      if (toolName === "bash") {
        return ["cmd", "bash"];
      } else if (toolName === "python") {
        return ["code", "python"];
      } else if (toolName === "web_search") {
        return ["query", "text"];
      } else {
        return [void 0, void 0];
      }
    };
    const extractInput = (args, inputKey) => {
      const formatArg = (key2, value2) => {
        const quotedValue = value2 === null ? "None" : typeof value2 === "string" ? `"${value2}"` : typeof value2 === "object" || Array.isArray(value2) ? JSON.stringify(value2, void 0, 2) : String(value2);
        return `${key2}: ${quotedValue}`;
      };
      if (args) {
        if (inputKey && args[inputKey]) {
          const input2 = args[inputKey];
          const filteredArgs = Object.keys(args).filter((key2) => {
            return key2 !== inputKey;
          }).map((key2) => {
            return formatArg(key2, args[key2]);
          });
          return {
            input: String(input2),
            args: filteredArgs
          };
        } else {
          const formattedArgs = Object.keys(args).map((key2) => {
            return formatArg(key2, args[key2]);
          });
          return {
            input: void 0,
            args: formattedArgs
          };
        }
      }
      return {
        input: void 0,
        args: []
      };
    };
    const outputPre = "_outputPre_1h1fn_1";
    const outputCode = "_outputCode_1h1fn_7";
    const styles$10 = {
      outputPre,
      outputCode
    };
    const useCodeHighlight = (language2) => {
      const codeRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        if (codeRef.current && language2) {
          prismExports.highlightElement(codeRef.current);
        }
      }, [language2]);
      return codeRef;
    };
    const ToolInput = reactExports.memo((props) => {
      const { highlightLanguage, contents: contents2, toolCallView } = props;
      const codeRef = useCodeHighlight(highlightLanguage);
      const toolViewRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        if ((toolCallView == null ? void 0 : toolCallView.content) && toolViewRef.current) {
          requestAnimationFrame(() => {
            const codeBlocks = toolViewRef.current.querySelectorAll("pre code");
            codeBlocks.forEach((block2) => {
              if (block2.className.includes("language-")) {
                block2.classList.add("sourceCode");
                prismExports.highlightElement(block2);
              }
            });
          });
        }
      }, [toolCallView == null ? void 0 : toolCallView.content]);
      if (!contents2 && !(toolCallView == null ? void 0 : toolCallView.content)) return null;
      if (toolCallView) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          MarkdownDiv,
          {
            markdown: toolCallView.content,
            ref: toolViewRef,
            className: clsx("text-size-small", "tool-output")
          }
        );
      }
      const formattedContent = typeof contents2 === "object" ? JSON.stringify(contents2) : contents2;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: clsx("tool-output", styles$10.outputPre, styles$10.bottomMargin), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "code",
        {
          ref: codeRef,
          className: clsx(
            "source-code",
            "sourceCode",
            `language-${highlightLanguage}`,
            styles$10.outputCode
          ),
          children: formattedContent
        }
      ) });
    });
    const styles$$ = {};
    const ToolTitle = ({ title: title2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: clsx("bi", "bi-tools", styles$$.styles) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-size-small", children: title2 })
      ] });
    };
    const ToolCallView = ({
      functionCall,
      input: input2,
      highlightLanguage,
      view,
      output: output2,
      mode
    }) => {
      function isContentImage(value2) {
        if (value2 && typeof value2 === "object") {
          if (value2.type === "image") {
            return true;
          } else if (value2.type === "tool") {
            if (Array.isArray(value2.content) && value2.content.some(isContentImage)) {
              return true;
            }
          }
        }
        return false;
      }
      const collapse = Array.isArray(output2) ? output2.every((item2) => !isContentImage(item2)) : !isContentImage(output2);
      const normalizedContent = reactExports.useMemo(() => normalizeContent$1(output2), [output2]);
      const contents2 = mode !== "compact" ? input2 : input2 || functionCall;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        mode !== "compact" && (!view || view.title) ? /* @__PURE__ */ jsxRuntimeExports.jsx(ToolTitle, { title: (view == null ? void 0 : view.title) || functionCall }) : "",
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ToolInput,
            {
              highlightLanguage,
              contents: contents2,
              toolCallView: view
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ExpandablePanel, { collapse, border: true, lines: 15, children: /* @__PURE__ */ jsxRuntimeExports.jsx(MessageContent, { contents: normalizedContent }) })
        ] }) })
      ] });
    };
    const normalizeContent$1 = (output2) => {
      if (Array.isArray(output2)) {
        return output2;
      } else {
        return [
          {
            type: "tool",
            content: [
              {
                type: "text",
                text: String(output2)
              }
            ]
          }
        ];
      }
    };
    const content$2 = "_content_p4lvn_1";
    const styles$_ = {
      content: content$2
    };
    const MessageContents = ({
      message: message2,
      toolMessages,
      toolCallStyle
    }) => {
      if (message2.role === "assistant" && message2.tool_calls && message2.tool_calls.length) {
        const toolCalls = message2.tool_calls.map((tool_call, idx) => {
          const { input: input2, functionCall, highlightLanguage } = resolveToolInput(
            tool_call.function,
            tool_call.arguments
          );
          let toolMessage;
          if (tool_call.id) {
            toolMessage = toolMessages.find((msg) => {
              return msg.tool_call_id === tool_call.id;
            });
          } else {
            toolMessage = toolMessages[idx];
          }
          const resolvedToolOutput = resolveToolMessage(toolMessage);
          if (toolCallStyle === "compact") {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("code", { children: [
              "tool: ",
              functionCall
            ] }) }, `tool-call-${idx}`);
          } else {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              ToolCallView,
              {
                functionCall,
                input: input2,
                highlightLanguage,
                output: resolvedToolOutput
              },
              `tool-call-${idx}`
            );
          }
        });
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$_.content, children: message2.content ? /* @__PURE__ */ jsxRuntimeExports.jsx(MessageContent, { contents: message2.content }) : void 0 }),
          toolCalls
        ] });
      } else {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(MessageContent, { contents: message2.content });
      }
    };
    const resolveToolMessage = (toolMessage) => {
      if (!toolMessage) {
        return [];
      }
      const content2 = toolMessage.error !== null && toolMessage.error ? toolMessage.error.message : toolMessage.content;
      if (typeof content2 === "string") {
        return [
          {
            type: "tool",
            content: [
              {
                type: "text",
                text: content2
              }
            ]
          }
        ];
      } else {
        const result2 = content2.map((con) => {
          if (typeof con === "string") {
            return {
              type: "tool",
              content: [
                {
                  type: "text",
                  text: con
                }
              ]
            };
          } else if (con.type === "text") {
            return {
              content: [con],
              type: "tool"
            };
          } else if (con.type === "image") {
            return {
              content: [con],
              type: "tool"
            };
          }
        }).filter((con) => con !== void 0);
        return result2;
      }
    };
    const resolveMessages = (messages) => {
      const resolvedMessages = [];
      for (const message2 of messages) {
        if (message2.role === "tool") {
          if (resolvedMessages.length > 0) {
            const msg = resolvedMessages[resolvedMessages.length - 1];
            msg.toolMessages = msg.toolMessages || [];
            msg.toolMessages.push(message2);
          }
        } else {
          resolvedMessages.push({ message: message2, toolMessages: [] });
        }
      }
      const systemMessages = [];
      const collapsedMessages = resolvedMessages.map((resolved) => {
        if (resolved.message.role === "system") {
          systemMessages.push(resolved.message);
        }
        return resolved;
      }).filter((resolved) => {
        return resolved.message.role !== "system";
      });
      const systemContent = [];
      for (const systemMessage2 of systemMessages) {
        const contents2 = Array.isArray(systemMessage2.content) ? systemMessage2.content : [systemMessage2.content];
        systemContent.push(...contents2.map(normalizeContent));
      }
      const systemMessage = {
        role: "system",
        content: systemContent,
        source: "input"
      };
      if (systemMessage && systemMessage.content.length > 0) {
        collapsedMessages.unshift({ message: systemMessage, toolMessages: [] });
      }
      return collapsedMessages;
    };
    const iconForMsg = (msg) => {
      if (msg.role === "user") {
        return ApplicationIcons.role.user;
      } else if (msg.role === "system") {
        return ApplicationIcons.role.system;
      } else if (msg.role === "tool") {
        return ApplicationIcons.role.tool;
      } else if (msg.role === "assistant") {
        return ApplicationIcons.role.assistant;
      } else {
        return ApplicationIcons.role.unknown;
      }
    };
    const normalizeContent = (content2) => {
      if (typeof content2 === "string") {
        return {
          type: "text",
          text: content2
        };
      } else {
        return content2;
      }
    };
    const ChatMessage = ({
      id,
      message: message2,
      toolMessages,
      indented: indented2,
      toolCallStyle
    }) => {
      const collapse = message2.role === "system";
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: clsx(
            message2.role,
            "text-size-base",
            styles$13.message,
            message2.role === "system" ? styles$13.systemRole : void 0
          ),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$13.messageGrid, "text-style-label"), children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: iconForMsg(message2) }),
              message2.role
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  styles$13.messageContents,
                  indented2 ? styles$13.indented : void 0
                ),
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExpandablePanel, { collapse, lines: 30, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  MessageContents,
                  {
                    message: message2,
                    toolMessages,
                    toolCallStyle
                  },
                  `${id}-contents`
                ) })
              }
            )
          ]
        }
      );
    };
    const grid$6 = "_grid_140x5_1";
    const number$1 = "_number_140x5_7";
    const styles$Z = {
      grid: grid$6,
      number: number$1
    };
    const ChatMessageRow = ({
      parentName,
      number: number2,
      resolvedMessage,
      toolCallStyle,
      indented: indented2
    }) => {
      if (number2) {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$Z.grid, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                "text-size-smaller",
                "text-style-secondary",
                styles$Z.number
              ),
              children: number2
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ChatMessage,
            {
              id: `${parentName}-chat-messages`,
              message: resolvedMessage.message,
              toolMessages: resolvedMessage.toolMessages,
              indented: indented2,
              toolCallStyle
            }
          )
        ] });
      } else {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          ChatMessage,
          {
            id: `${parentName}-chat-messages`,
            message: resolvedMessage.message,
            toolMessages: resolvedMessage.toolMessages,
            indented: indented2,
            toolCallStyle
          }
        );
      }
    };
    const ChatView = ({
      id,
      messages,
      toolCallStyle = "complete",
      indented: indented2,
      numbered = true,
      className: className2
    }) => {
      const collapsedMessages = resolveMessages(messages);
      const result2 = /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(className2), children: collapsedMessages.map((msg, index2) => {
        const number2 = collapsedMessages.length > 1 && numbered ? index2 + 1 : void 0;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          ChatMessageRow,
          {
            parentName: id || "chat-view",
            number: number2,
            resolvedMessage: msg,
            indented: indented2,
            toolCallStyle
          },
          `${id}-msg-${index2}`
        );
      }) });
      return result2;
    };
    const ChatMessageRenderer = {
      bucket: Buckets.first,
      canRender: (entry2) => {
        var _a2, _b2;
        const val = entry2.value;
        return Array.isArray(val) && val.length > 0 && ((_a2 = val[0]) == null ? void 0 : _a2.role) !== void 0 && ((_b2 = val[0]) == null ? void 0 : _b2.content) !== void 0;
      },
      render: (id, entry2) => {
        return {
          rendered: /* @__PURE__ */ jsxRuntimeExports.jsxs(NavPills, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(ChatSummary, { title: "Last Turn", id, messages: entry2.value }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ChatView, { title: "All", id, messages: entry2.value })
          ] })
        };
      }
    };
    const ChatSummary = ({ id, messages }) => {
      const summaryMessages = [];
      for (const message2 of messages.slice().reverse()) {
        summaryMessages.unshift(message2);
        if (message2.role === "user") {
          break;
        }
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ChatView, { id, messages: summaryMessages });
    };
    const table$1 = "_table_1memb_1";
    const cell$2 = "_cell_1memb_11";
    const compact = "_compact_1memb_15";
    const cellKey = "_cellKey_1memb_19";
    const cellValue = "_cellValue_1memb_31";
    const styles$Y = {
      table: table$1,
      cell: cell$2,
      compact,
      cellKey,
      cellValue
    };
    const MetaDataView = ({
      id,
      style: style2,
      entries,
      tableOptions,
      compact: compact2,
      className: className2
    }) => {
      const baseId = "metadataview";
      tableOptions = tableOptions || "sm";
      const tblClz = (tableOptions || "").split(",").map((option) => {
        return `table-${option}`;
      });
      const coercedEntries = toNameValues(entries);
      const entryEls = (coercedEntries || []).map((entry2, index2) => {
        const id2 = `${baseId}-value-${index2}`;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "td",
            {
              className: clsx(
                styles$Y.cell,
                styles$Y.cellKey,
                "text-size-small",
                "text-style-label"
              ),
              children: entry2.name
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: clsx(styles$Y.cell, styles$Y.cellValue, "text-size-small"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(RenderedContent, { id: id2, entry: entry2 }) })
        ] }, id2);
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "table",
        {
          id,
          className: clsx(
            "table",
            tblClz,
            styles$Y.table,
            compact2 ? styles$Y.compact : void 0,
            className2
          ),
          style: style2,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("th", { colSpan: 2, className: "th" }) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: entryEls })
          ]
        }
      );
    };
    const toNameValues = (entries) => {
      if (entries) {
        if (Array.isArray(entries)) {
          return entries;
        } else {
          return Object.entries(entries || {}).map(([key2, value2]) => {
            return { name: key2, value: value2 };
          });
        }
      } else {
        return entries;
      }
    };
    const kPrismRenderMaxSize = 25e4;
    const JSONPanel = ({
      id,
      json,
      data,
      simple = false,
      style: style2,
      className: className2
    }) => {
      const codeRef = reactExports.useRef(null);
      const sourceCode = reactExports.useMemo(() => {
        return json || JSON.stringify(resolveBase64(data), void 0, 2);
      }, [json, data]);
      reactExports.useEffect(() => {
        if (sourceCode.length < kPrismRenderMaxSize && codeRef.current) {
          prismExports.highlightElement(codeRef.current);
        }
      }, [sourceCode]);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "pre",
        {
          className: clsx("json-panel", simple ? "simple" : "", className2),
          style: style2,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "code",
            {
              id,
              ref: codeRef,
              className: clsx("source-code", "language-javascript"),
              children: sourceCode
            }
          )
        }
      );
    };
    const resolveBase64 = (value2) => {
      const prefix2 = "data:image";
      if (Array.isArray(value2)) {
        return value2.map((v) => resolveBase64(v));
      }
      if (value2 && typeof value2 === "object") {
        const resolvedObject = {};
        for (const key2 of Object.keys(value2)) {
          resolvedObject[key2] = resolveBase64(value2[key2]);
        }
        return resolvedObject;
      }
      if (typeof value2 === "string") {
        let resolvedValue = value2;
        if (resolvedValue.startsWith(prefix2)) {
          resolvedValue = "[base64 image]";
        }
        return resolvedValue;
      }
      return value2;
    };
    const isJson = (text2) => {
      text2 = text2.trim();
      if (text2.startsWith("{") && text2.endsWith("}")) {
        try {
          JSON.parse(text2);
          return true;
        } catch {
          return false;
        }
      }
      return false;
    };
    const parsedJson = (text2) => {
      text2 = text2.trim();
      if (text2.startsWith("{") && text2.endsWith("}")) {
        try {
          return JSON.parse(text2);
        } catch {
          return void 0;
        }
      }
      return void 0;
    };
    const query = "_query_9u9bt_1";
    const summary$3 = "_summary_9u9bt_6";
    const preWrap = "_preWrap_9u9bt_10";
    const styles$X = {
      query,
      summary: summary$3,
      preWrap
    };
    const RenderedContent = ({
      id,
      entry: entry2
    }) => {
      if (entry2.value === null) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "[null]" });
      }
      const renderer = Object.keys(contentRenderers).map((key2) => {
        return contentRenderers[key2];
      }).sort((a, b) => {
        return a.bucket - b.bucket;
      }).find((renderer2) => {
        return renderer2.canRender(entry2);
      });
      if (renderer) {
        const { rendered } = renderer.render(id, entry2);
        if (rendered !== void 0 && React$2.isValidElement(rendered)) {
          return rendered;
        }
      }
      const displayValue = (() => {
        try {
          if (typeof entry2.value === "object") {
            return JSON.stringify(entry2.value);
          }
          return String(entry2.value);
        } catch (e) {
          return "[Unable to display value]";
        }
      })();
      return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: displayValue });
    };
    const contentRenderers = {
      AnsiString: {
        bucket: Buckets.first,
        canRender: (entry2) => {
          return typeof entry2.value === "string" && entry2.value.indexOf("\x1B") > -1;
        },
        render: (_id, entry2) => {
          return {
            rendered: /* @__PURE__ */ jsxRuntimeExports.jsx(ANSIDisplay, { output: entry2.value })
          };
        }
      },
      JsonString: {
        bucket: Buckets.first,
        canRender: (entry2) => {
          if (typeof entry2.value === "string") {
            const trimmed = entry2.value.trim();
            return isJson(trimmed);
          }
          return false;
        },
        render: (_id, entry2) => {
          const obj = JSON.parse(entry2.value);
          return { rendered: /* @__PURE__ */ jsxRuntimeExports.jsx(JSONPanel, { data: obj }) };
        }
      },
      Model: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          return typeof entry2.value === "object" && entry2.value._model;
        },
        render: (_id, entry2) => {
          return {
            rendered: /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.model }),
              " ",
              entry2.value._model
            ] })
          };
        }
      },
      Boolean: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          return typeof entry2.value === "boolean";
        },
        render: (id, entry2) => {
          entry2.value = entry2.value.toString();
          return contentRenderers.String.render(id, entry2);
        }
      },
      Number: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          return typeof entry2.value === "number";
        },
        render: (id, entry2) => {
          entry2.value = formatNumber(entry2.value);
          return contentRenderers.String.render(id, entry2);
        }
      },
      String: {
        bucket: Buckets.final,
        canRender: (entry2) => {
          return typeof entry2.value === "string";
        },
        render: (_id, entry2) => {
          const rendered = entry2.value.trim();
          return {
            rendered
          };
        }
      },
      Array: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          const isArray = Array.isArray(entry2.value);
          if (isArray) {
            const types2 = new Set(
              entry2.value.filter((e) => e !== null).map((e) => {
                return typeof e;
              })
            );
            return types2.size === 1;
          } else {
            return false;
          }
        },
        render: (id, entry2) => {
          const arrayMap = {};
          entry2.value.forEach((e, index2) => {
            arrayMap[`[${index2}]`] = e;
          });
          const arrayRendered = /* @__PURE__ */ jsxRuntimeExports.jsx(
            MetaDataView,
            {
              id,
              className: "font-size-small",
              entries: arrayMap,
              tableOptions: "borderless,sm",
              compact: true
            }
          );
          return { rendered: arrayRendered };
        }
      },
      ChatMessage: ChatMessageRenderer,
      web_search: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          return typeof entry2.value === "object" && entry2.name === "web_search";
        },
        render: (_id, entry2) => {
          const results = [];
          results.push(
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$X.query, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.search }),
              " ",
              entry2.value.query
            ] })
          );
          entry2.value.results.forEach(
            (result2) => {
              results.push(
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: result2.url, children: result2.url }) })
              );
              results.push(
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-smaller", styles$X.summary), children: result2.summary })
              );
            }
          );
          return {
            rendered: results
          };
        }
      },
      web_browser: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          var _a2;
          return typeof entry2.value === "string" && ((_a2 = entry2.name) == null ? void 0 : _a2.startsWith("web_browser"));
        },
        render: (_id, entry2) => {
          return {
            rendered: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: styles$X.preWrap, children: entry2.value })
          };
        }
      },
      Html: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          return typeof entry2.value === "object" && entry2.value._html;
        },
        render: (_id, entry2) => {
          return {
            rendered: entry2.value._html
          };
        }
      },
      Image: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          return typeof entry2.value === "string" && entry2.value.startsWith("data:image/");
        },
        render: (_id, entry2) => {
          return {
            rendered: /* @__PURE__ */ jsxRuntimeExports.jsx("img", { src: entry2.value })
          };
        }
      },
      Object: {
        bucket: Buckets.intermediate,
        canRender: (entry2) => {
          return typeof entry2.value === "object";
        },
        render: (id, entry2) => {
          return {
            rendered: /* @__PURE__ */ jsxRuntimeExports.jsx(
              MetaDataView,
              {
                id,
                className: "text-size-smaller",
                entries: entry2.value,
                tableOptions: "borderless,sm",
                compact: true
              }
            )
          };
        }
      }
    };
    const otherScoreDescriptor = () => {
      return {
        scoreType: kScoreTypeOther,
        compare: () => {
          return 0;
        },
        render: (score2) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            RenderedContent,
            {
              id: "other-score-value",
              entry: { name: "other-score-value", value: score2 }
            }
          );
        }
      };
    };
    const circle = "_circle_1iagp_1";
    const green = "_green_1iagp_12";
    const red = "_red_1iagp_18";
    const orange = "_orange_1iagp_24";
    const styles$W = {
      circle,
      green,
      red,
      orange
    };
    const passFailScoreDescriptor = (values) => {
      const categories = [];
      if (values.includes("C")) {
        categories.push({
          val: "C",
          text: "Correct"
        });
      }
      if (values.includes("P")) {
        categories.push({
          val: "P",
          text: "Partial"
        });
      }
      if (values.includes("I")) {
        categories.push({
          val: "I",
          text: "Incorrect"
        });
      }
      if (values.includes("N")) {
        categories.push({
          val: "N",
          text: "Refusal"
        });
      }
      const order = ["C", "P", "I", "N"];
      return {
        scoreType: kScoreTypePassFail,
        categories,
        render: (score2) => {
          if (score2 === "C") {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                className: clsx("text-size-small", styles$W.circle, styles$W.green),
                children: "C"
              }
            );
          } else if (score2 === "I") {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: clsx("text-size-small", styles$W.circle, styles$W.red), children: "I" });
          } else if (score2 === "P") {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                className: clsx("text-size-small", styles$W.circle, styles$W.orange),
                children: "P"
              }
            );
          } else if (score2 === "N") {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: clsx("text-size-small", styles$W.circle, styles$W.red), children: "N" });
          } else {
            return String(score2);
          }
        },
        compare: (a, b) => {
          if (typeof a.value !== "string" || typeof b.value !== "string") {
            throw new Error(
              "Unexpectedly using the pass fail scorer on non-string values"
            );
          }
          const sort = order.indexOf(a.value || "") - order.indexOf(b.value || "");
          return sort;
        }
      };
    };
    const getScoreDescriptorForValues = (uniqScoreValues, uniqScoreTypes) => {
      for (const categorizer of scoreCategorizers) {
        const scoreDescriptor = categorizer.describe(
          uniqScoreValues,
          uniqScoreTypes
        );
        if (scoreDescriptor) {
          return scoreDescriptor;
        }
      }
    };
    const scoreCategorizers = [
      {
        describe: (_values, types2) => {
          if (types2 && types2.length === 1 && types2[0] === "boolean") {
            return booleanScoreDescriptor();
          }
        }
      },
      {
        describe: (values, _types) => {
          if (values.length === 2 && values.every((val) => {
            return val === 1 || val === 0;
          })) {
            return booleanScoreDescriptor();
          }
        }
      },
      {
        describe: (values, types2) => {
          if (types2 && types2[0] === "string" && types2.length === 1 && values.length < 5 && !values.find((val) => {
            return val !== "I" && val !== "C" && val !== "P" && val !== "N";
          })) {
            return passFailScoreDescriptor(values);
          }
        }
      },
      {
        describe: (values, types2) => {
          if (values.length < 10 && types2 && types2.length === 1 && types2[0] === "string") {
            return categoricalScoreDescriptor(values);
          }
        }
      },
      {
        describe: (values, types2) => {
          if (types2 && types2.length !== 0 && types2[0] === "number") {
            return numericScoreDescriptor(values);
          }
        }
      },
      {
        describe: (values, types2) => {
          if (types2 && types2.length !== 0 && types2[0] === "object") {
            return objectScoreDescriptor(values);
          }
        }
      },
      {
        describe: (_values, _types) => {
          return otherScoreDescriptor();
        }
      }
    ];
    const createEvalDescriptor = (scores2, epochs, samples) => {
      if (!samples) {
        return void 0;
      }
      const scoreValue2 = (sample2, scoreLabel) => {
        if (sample2.scores === null || Object.keys(sample2.scores).length === 0 || !scoreLabel) {
          return void 0;
        }
        if (scoreLabel.scorer !== scoreLabel.name && sample2.scores[scoreLabel.scorer] && sample2.scores[scoreLabel.scorer].value) {
          return sample2.scores[scoreLabel.scorer].value;
        } else if (sample2.scores[scoreLabel.name]) {
          return sample2.scores[scoreLabel.name].value;
        } else {
          return void 0;
        }
      };
      const scoreAnswer = (sample2, scorer) => {
        if (sample2 && sample2.scores) {
          const sampleScore = sample2.scores[scorer];
          if (sampleScore && sampleScore.answer) {
            return sampleScore.answer;
          }
        } else {
          return void 0;
        }
      };
      const scoreExplanation = (sample2, scorer) => {
        if (sample2 && sample2.scores) {
          const sampleScore = sample2.scores[scorer];
          if (sampleScore && sampleScore.explanation) {
            return sampleScore.explanation;
          }
        }
        return void 0;
      };
      const scoreMetadata = (sample2, scorer) => {
        if (sample2 && sample2.scores) {
          const sampleScore = sample2.scores[scorer];
          if (sampleScore && sampleScore.metadata) {
            return sampleScore.metadata;
          }
        }
        return void 0;
      };
      const scoreDescriptorMap = {};
      for (const scoreLabel of scores2) {
        const uniqScoreValues = [
          ...new Set(
            samples.filter((sample2) => !!sample2.scores).filter((sample2) => {
              if (!scoreLabel) {
                return true;
              }
              if (!sample2.scores) {
                return false;
              }
              if (scoreLabel.scorer !== scoreLabel.name) {
                return Object.keys(sample2.scores).includes(scoreLabel.scorer) && Object.keys(sample2.scores[scoreLabel.scorer].value).includes(
                  scoreLabel.name
                );
              } else {
                return Object.keys(sample2.scores).includes(scoreLabel.name);
              }
            }).map((sample2) => {
              return scoreValue2(sample2, scoreLabel);
            }).filter((value2) => {
              return value2 !== null;
            }).filter((value2) => {
              return value2 !== void 0;
            })
          )
        ];
        const uniqScoreTypes = [
          ...new Set(uniqScoreValues.map((scoreValue22) => typeof scoreValue22))
        ];
        const scoreDescriptor2 = getScoreDescriptorForValues(
          uniqScoreValues,
          uniqScoreTypes
        );
        if (scoreDescriptor2) {
          scoreDescriptorMap[scoreLabelKey(scoreLabel)] = scoreDescriptor2;
        }
      }
      const scoreDescriptor = (scoreLabel) => {
        return scoreDescriptorMap[scoreLabelKey(scoreLabel)];
      };
      const scoreRendered = (sample2, scoreLabel) => {
        const descriptor = scoreDescriptor(scoreLabel);
        const score22 = scoreValue2(sample2, scoreLabel);
        if (score22 === null) {
          return "null";
        } else if (score22 === void 0) {
          return "";
        } else if (score22 && descriptor && descriptor.render) {
          return descriptor.render(score22);
        } else {
          return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: String(score22) });
        }
      };
      const scorerDescriptor = (sample2, scoreLabel) => {
        return {
          metadata: () => {
            return scoreMetadata(sample2, scoreLabel.scorer) || {};
          },
          explanation: () => {
            return scoreExplanation(sample2, scoreLabel.scorer) || "";
          },
          answer: () => {
            return scoreAnswer(sample2, scoreLabel.scorer) || "";
          },
          scores: () => {
            if (!sample2 || !sample2.scores) {
              return [];
            }
            const myScoreDescriptor = scoreDescriptor(scoreLabel);
            if (!myScoreDescriptor) {
              return [];
            }
            const scoreNames = scores2.map((score22) => {
              return score22.name;
            });
            const sampleScorer = sample2.scores[scoreLabel.scorer];
            const scoreVal = sampleScorer.value;
            if (typeof scoreVal === "object") {
              const names = Object.keys(scoreVal);
              if (names.find((name2) => {
                return scoreNames.includes(name2);
              })) {
                const scores22 = names.map((name2) => {
                  return {
                    name: name2,
                    rendered: () => {
                      return myScoreDescriptor.render(scoreVal);
                    }
                  };
                });
                return scores22;
              } else {
                return [
                  {
                    name: scoreLabel.scorer,
                    rendered: () => {
                      return myScoreDescriptor.render(scoreVal);
                    }
                  }
                ];
              }
            } else {
              return [
                {
                  name: scoreLabel.scorer,
                  rendered: () => {
                    return myScoreDescriptor.render(scoreVal);
                  }
                }
              ];
            }
          }
        };
      };
      const score2 = (sample2, scoreLabel) => {
        return {
          value: scoreValue2(sample2, scoreLabel),
          render: () => {
            return scoreRendered(sample2, scoreLabel);
          }
        };
      };
      return {
        epochs,
        samples,
        scores: scores2,
        scorerDescriptor,
        scoreDescriptor,
        score: score2,
        scoreAnswer
      };
    };
    const createSamplesDescriptor = (evalDescriptor, selectedScore) => {
      const sizes = evalDescriptor.samples.reduce(
        (previous, current) => {
          var _a2;
          const text2 = inputString(current.input).join(" ");
          const score2 = evalDescriptor.score(current, selectedScore);
          const scoreValue2 = score2 == null ? void 0 : score2.value;
          const scoreText = scoreValue2 ? String(scoreValue2) : current.error ? String(current.error) : "";
          previous[0] = Math.min(Math.max(previous[0], text2.length), 300);
          previous[1] = Math.min(
            Math.max(previous[1], arrayToString(current.target).length),
            300
          );
          previous[2] = Math.min(
            Math.max(
              previous[2],
              ((_a2 = evalDescriptor.scoreAnswer(current, selectedScore == null ? void 0 : selectedScore.name)) == null ? void 0 : _a2.length) || 0
            ),
            300
          );
          previous[3] = Math.min(
            Math.max(previous[3], current.limit ? current.limit.length : 0),
            50
          );
          previous[4] = Math.min(
            Math.max(previous[4], String(current.id).length),
            10
          );
          previous[5] = Math.min(Math.max(previous[5], scoreText.length), 30);
          return previous;
        },
        [0, 0, 0, 0, 0, 0]
      );
      const maxSizes = {
        input: Math.min(sizes[0], 300),
        target: Math.min(sizes[1], 300),
        answer: Math.min(sizes[2], 300),
        limit: Math.min(sizes[3], 50),
        id: Math.min(sizes[4], 10),
        score: Math.min(sizes[4], 30)
      };
      const base2 = maxSizes.input + maxSizes.target + maxSizes.answer + maxSizes.limit + maxSizes.id + maxSizes.score || 1;
      const messageShape = {
        raw: {
          input: sizes[0],
          target: sizes[1],
          answer: sizes[2],
          limit: sizes[3],
          id: sizes[4],
          score: sizes[5]
        },
        normalized: {
          input: maxSizes.input / base2,
          target: maxSizes.target / base2,
          answer: maxSizes.answer / base2,
          limit: maxSizes.limit / base2,
          id: maxSizes.id / base2,
          score: maxSizes.score / base2
        }
      };
      return {
        evalDescriptor,
        messageShape,
        selectedScoreDescriptor: evalDescriptor.scoreDescriptor(selectedScore),
        selectedScore: (sample2) => evalDescriptor.score(sample2, selectedScore),
        selectedScorerDescriptor: (sample2) => evalDescriptor.scorerDescriptor(sample2, selectedScore)
      };
    };
    const scoreLabelKey = (scoreLabel) => {
      return `${scoreLabel == null ? void 0 : scoreLabel.scorer}.${scoreLabel.name}`;
    };
    var _parser = function() {
      var parser2 = {
        trace: function trace() {
        },
        yy: {},
        symbols_: {
          error: 2,
          expressions: 3,
          e: 4,
          EndOfExpression: 5,
          "-": 6,
          "+": 7,
          "*": 8,
          "/": 9,
          "^": 10,
          mod: 11,
          and: 12,
          or: 13,
          not: 14,
          if: 15,
          then: 16,
          else: 17,
          in: 18,
          notIn: 19,
          "(": 20,
          ")": 21,
          Arguments: 22,
          ",": 23,
          Number: 24,
          Symbol: 25,
          String: 26,
          of: 27,
          Relation: 28,
          "%": 29,
          "?": 30,
          ":": 31,
          RelationalOperator: 32,
          "==": 33,
          "!=": 34,
          "~=": 35,
          "<": 36,
          "<=": 37,
          ">=": 38,
          ">": 39,
          $accept: 0,
          $end: 1
        },
        terminals_: {
          2: "error",
          5: "EndOfExpression",
          6: "-",
          7: "+",
          8: "*",
          9: "/",
          10: "^",
          11: "mod",
          12: "and",
          13: "or",
          14: "not",
          15: "if",
          16: "then",
          17: "else",
          18: "in",
          19: "notIn",
          20: "(",
          21: ")",
          23: ",",
          24: "Number",
          25: "Symbol",
          26: "String",
          27: "of",
          29: "%",
          30: "?",
          31: ":",
          33: "==",
          34: "!=",
          35: "~=",
          36: "<",
          37: "<=",
          38: ">=",
          39: ">"
        },
        productions_: [
          0,
          [3, 2],
          [4, 2],
          [4, 3],
          [4, 3],
          [4, 3],
          [4, 3],
          [4, 3],
          [4, 3],
          [4, 3],
          [4, 3],
          [4, 2],
          [4, 6],
          [4, 3],
          [4, 3],
          [4, 3],
          [4, 5],
          [4, 1],
          [4, 1],
          [4, 1],
          [4, 3],
          [4, 3],
          [4, 4],
          [4, 1],
          [4, 3],
          [4, 5],
          [32, 1],
          [32, 1],
          [32, 1],
          [32, 1],
          [32, 1],
          [32, 1],
          [32, 1],
          [28, 3],
          [28, 3],
          [22, 1],
          [22, 3]
        ],
        performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
          var $0 = $$.length - 1;
          switch (yystate) {
            case 1:
              return $$[$0 - 1];
            case 2:
              this.$ = ["(", "ops['-'](", $$[$0], ")", ")"];
              break;
            case 3:
              this.$ = [
                "(",
                "ops['",
                $$[$0 - 1],
                "'](",
                $$[$0 - 2],
                ", ",
                $$[$0],
                ")",
                ")"
              ];
              break;
            case 4:
              this.$ = [
                "(",
                "ops['",
                $$[$0 - 1],
                "'](",
                $$[$0 - 2],
                ", ",
                $$[$0],
                ")",
                ")"
              ];
              break;
            case 5:
              this.$ = [
                "(",
                "ops['",
                $$[$0 - 1],
                "'](",
                $$[$0 - 2],
                ", ",
                $$[$0],
                ")",
                ")"
              ];
              break;
            case 6:
              this.$ = [
                "(",
                "ops['",
                $$[$0 - 1],
                "'](",
                $$[$0 - 2],
                ", ",
                $$[$0],
                ")",
                ")"
              ];
              break;
            case 7:
              this.$ = [
                "(",
                "ops['",
                $$[$0 - 1],
                "'](",
                $$[$0 - 2],
                ", ",
                $$[$0],
                ")",
                ")"
              ];
              break;
            case 8:
              this.$ = ["(", "ops.mod(", $$[$0 - 2], ", ", $$[$0], ")", ")"];
              break;
            case 9:
              this.$ = [
                "(",
                "",
                "std.coerceBoolean",
                "(",
                $$[$0 - 2],
                ") && ",
                "std.coerceBoolean",
                "(",
                $$[$0],
                ")",
                ")"
              ];
              break;
            case 10:
              this.$ = [
                "(",
                "",
                "std.coerceBoolean",
                "(",
                $$[$0 - 2],
                ") || ",
                "std.coerceBoolean",
                "(",
                $$[$0],
                ")",
                ")"
              ];
              break;
            case 11:
              this.$ = ["(", "! ", "std.coerceBoolean", "(", $$[$0], ")", ")"];
              break;
            case 12:
              this.$ = [
                "(",
                "",
                "std.coerceBoolean",
                "(",
                $$[$0 - 4],
                ") ? ",
                $$[$0 - 2],
                " : ",
                $$[$0],
                "",
                ")"
              ];
              break;
            case 13:
              this.$ = ["(", "std.isSubset(", $$[$0 - 2], ", ", $$[$0], ")", ")"];
              break;
            case 14:
              this.$ = ["(", "!std.isSubset(", $$[$0 - 2], ", ", $$[$0], ")", ")"];
              break;
            case 15:
              this.$ = ["(", "", $$[$0 - 1], "", ")"];
              break;
            case 16:
              this.$ = ["(", "[ ", $$[$0 - 3], ", ", $$[$0 - 1], " ]", ")"];
              break;
            case 17:
              this.$ = ["", $$[$0], ""];
              break;
            case 18:
              this.$ = ["prop(", $$[$0], ", data)"];
              break;
            case 19:
              this.$ = ["", $$[$0], ""];
              break;
            case 20:
              this.$ = ["prop(", $$[$0 - 2], ", ", $$[$0], ")"];
              break;
            case 21:
              this.$ = ["call(", $$[$0 - 2], ")"];
              break;
            case 22:
              this.$ = ["call(", $$[$0 - 3], ", ", $$[$0 - 1], ")"];
              break;
            case 23:
              this.$ = yy.reduceRelation($$[$0]);
              break;
            case 24:
              this.$ = [
                "std.warnDeprecated('modulo', ops['mod'](",
                $$[$0 - 2],
                ", ",
                $$[$0],
                "))"
              ];
              break;
            case 25:
              this.$ = [
                "std.warnDeprecated('ternary', ",
                "std.coerceBoolean",
                "(",
                $$[$0 - 4],
                ") ? ",
                $$[$0 - 2],
                " : ",
                $$[$0],
                ")"
              ];
              break;
            case 26:
              this.$ = ["=="];
              break;
            case 27:
              this.$ = ["!="];
              break;
            case 28:
              this.$ = ["~="];
              break;
            case 29:
              this.$ = ["<"];
              break;
            case 30:
              this.$ = ["<="];
              break;
            case 31:
              this.$ = [">="];
              break;
            case 32:
              this.$ = [">"];
              break;
            case 33:
              this.$ = [$$[$0 - 2], $$[$0 - 1], ...$$[$0]];
              break;
            case 34:
              this.$ = [$$[$0 - 2], $$[$0 - 1], $$[$0]];
              break;
            case 35:
              this.$ = ["", $$[$0], ""];
              break;
            case 36:
              this.$ = ["", $$[$0 - 2], ", ", $$[$0], ""];
              break;
          }
        },
        table: [
          {
            3: 1,
            4: 2,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            1: [3]
          },
          {
            5: [1, 11],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            18: [1, 20],
            19: [1, 21],
            29: [1, 22],
            30: [1, 23],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            4: 32,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 33,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 34,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 35,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            22: 36,
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            5: [2, 17],
            6: [2, 17],
            7: [2, 17],
            8: [2, 17],
            9: [2, 17],
            10: [2, 17],
            11: [2, 17],
            12: [2, 17],
            13: [2, 17],
            16: [2, 17],
            17: [2, 17],
            18: [2, 17],
            19: [2, 17],
            21: [2, 17],
            23: [2, 17],
            29: [2, 17],
            30: [2, 17],
            31: [2, 17],
            33: [2, 17],
            34: [2, 17],
            35: [2, 17],
            36: [2, 17],
            37: [2, 17],
            38: [2, 17],
            39: [2, 17]
          },
          {
            5: [2, 18],
            6: [2, 18],
            7: [2, 18],
            8: [2, 18],
            9: [2, 18],
            10: [2, 18],
            11: [2, 18],
            12: [2, 18],
            13: [2, 18],
            16: [2, 18],
            17: [2, 18],
            18: [2, 18],
            19: [2, 18],
            20: [1, 38],
            21: [2, 18],
            23: [2, 18],
            27: [1, 37],
            29: [2, 18],
            30: [2, 18],
            31: [2, 18],
            33: [2, 18],
            34: [2, 18],
            35: [2, 18],
            36: [2, 18],
            37: [2, 18],
            38: [2, 18],
            39: [2, 18]
          },
          {
            5: [2, 19],
            6: [2, 19],
            7: [2, 19],
            8: [2, 19],
            9: [2, 19],
            10: [2, 19],
            11: [2, 19],
            12: [2, 19],
            13: [2, 19],
            16: [2, 19],
            17: [2, 19],
            18: [2, 19],
            19: [2, 19],
            21: [2, 19],
            23: [2, 19],
            29: [2, 19],
            30: [2, 19],
            31: [2, 19],
            33: [2, 19],
            34: [2, 19],
            35: [2, 19],
            36: [2, 19],
            37: [2, 19],
            38: [2, 19],
            39: [2, 19]
          },
          {
            5: [2, 23],
            6: [2, 23],
            7: [2, 23],
            8: [2, 23],
            9: [2, 23],
            10: [2, 23],
            11: [2, 23],
            12: [2, 23],
            13: [2, 23],
            16: [2, 23],
            17: [2, 23],
            18: [2, 23],
            19: [2, 23],
            21: [2, 23],
            23: [2, 23],
            29: [2, 23],
            30: [2, 23],
            31: [2, 23],
            33: [2, 23],
            34: [2, 23],
            35: [2, 23],
            36: [2, 23],
            37: [2, 23],
            38: [2, 23],
            39: [2, 23]
          },
          {
            1: [2, 1]
          },
          {
            4: 39,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 40,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 41,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 42,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 43,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 44,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 45,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 46,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 47,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 48,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 49,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 50,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 52,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 51
          },
          {
            6: [2, 26],
            14: [2, 26],
            15: [2, 26],
            20: [2, 26],
            24: [2, 26],
            25: [2, 26],
            26: [2, 26]
          },
          {
            6: [2, 27],
            14: [2, 27],
            15: [2, 27],
            20: [2, 27],
            24: [2, 27],
            25: [2, 27],
            26: [2, 27]
          },
          {
            6: [2, 28],
            14: [2, 28],
            15: [2, 28],
            20: [2, 28],
            24: [2, 28],
            25: [2, 28],
            26: [2, 28]
          },
          {
            6: [2, 29],
            14: [2, 29],
            15: [2, 29],
            20: [2, 29],
            24: [2, 29],
            25: [2, 29],
            26: [2, 29]
          },
          {
            6: [2, 30],
            14: [2, 30],
            15: [2, 30],
            20: [2, 30],
            24: [2, 30],
            25: [2, 30],
            26: [2, 30]
          },
          {
            6: [2, 31],
            14: [2, 31],
            15: [2, 31],
            20: [2, 31],
            24: [2, 31],
            25: [2, 31],
            26: [2, 31]
          },
          {
            6: [2, 32],
            14: [2, 32],
            15: [2, 32],
            20: [2, 32],
            24: [2, 32],
            25: [2, 32],
            26: [2, 32]
          },
          {
            5: [2, 2],
            6: [2, 2],
            7: [2, 2],
            8: [2, 2],
            9: [2, 2],
            10: [1, 16],
            11: [2, 2],
            12: [2, 2],
            13: [2, 2],
            16: [2, 2],
            17: [2, 2],
            18: [2, 2],
            19: [2, 2],
            21: [2, 2],
            23: [2, 2],
            29: [2, 2],
            30: [2, 2],
            31: [2, 2],
            32: 24,
            33: [2, 2],
            34: [2, 2],
            35: [2, 2],
            36: [2, 2],
            37: [2, 2],
            38: [2, 2],
            39: [2, 2]
          },
          {
            5: [2, 11],
            6: [2, 11],
            7: [2, 11],
            8: [2, 11],
            9: [2, 11],
            10: [1, 16],
            11: [2, 11],
            12: [2, 11],
            13: [2, 11],
            16: [2, 11],
            17: [2, 11],
            18: [2, 11],
            19: [2, 11],
            21: [2, 11],
            23: [2, 11],
            29: [2, 11],
            30: [2, 11],
            31: [2, 11],
            32: 24,
            33: [2, 11],
            34: [2, 11],
            35: [2, 11],
            36: [2, 11],
            37: [2, 11],
            38: [2, 11],
            39: [2, 11]
          },
          {
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            16: [1, 53],
            18: [1, 20],
            19: [1, 21],
            29: [1, 22],
            30: [1, 23],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            18: [1, 20],
            19: [1, 21],
            21: [1, 54],
            23: [2, 35],
            29: [1, 22],
            30: [1, 23],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            23: [1, 55]
          },
          {
            4: 56,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            4: 59,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            21: [1, 57],
            22: 58,
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            5: [2, 3],
            6: [2, 3],
            7: [2, 3],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [2, 3],
            13: [2, 3],
            16: [2, 3],
            17: [2, 3],
            18: [2, 3],
            19: [2, 3],
            21: [2, 3],
            23: [2, 3],
            29: [1, 22],
            30: [2, 3],
            31: [2, 3],
            32: 24,
            33: [2, 3],
            34: [2, 3],
            35: [2, 3],
            36: [2, 3],
            37: [2, 3],
            38: [2, 3],
            39: [2, 3]
          },
          {
            5: [2, 4],
            6: [2, 4],
            7: [2, 4],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [2, 4],
            13: [2, 4],
            16: [2, 4],
            17: [2, 4],
            18: [2, 4],
            19: [2, 4],
            21: [2, 4],
            23: [2, 4],
            29: [1, 22],
            30: [2, 4],
            31: [2, 4],
            32: 24,
            33: [2, 4],
            34: [2, 4],
            35: [2, 4],
            36: [2, 4],
            37: [2, 4],
            38: [2, 4],
            39: [2, 4]
          },
          {
            5: [2, 5],
            6: [2, 5],
            7: [2, 5],
            8: [2, 5],
            9: [2, 5],
            10: [1, 16],
            11: [2, 5],
            12: [2, 5],
            13: [2, 5],
            16: [2, 5],
            17: [2, 5],
            18: [2, 5],
            19: [2, 5],
            21: [2, 5],
            23: [2, 5],
            29: [2, 5],
            30: [2, 5],
            31: [2, 5],
            32: 24,
            33: [2, 5],
            34: [2, 5],
            35: [2, 5],
            36: [2, 5],
            37: [2, 5],
            38: [2, 5],
            39: [2, 5]
          },
          {
            5: [2, 6],
            6: [2, 6],
            7: [2, 6],
            8: [2, 6],
            9: [2, 6],
            10: [1, 16],
            11: [2, 6],
            12: [2, 6],
            13: [2, 6],
            16: [2, 6],
            17: [2, 6],
            18: [2, 6],
            19: [2, 6],
            21: [2, 6],
            23: [2, 6],
            29: [2, 6],
            30: [2, 6],
            31: [2, 6],
            32: 24,
            33: [2, 6],
            34: [2, 6],
            35: [2, 6],
            36: [2, 6],
            37: [2, 6],
            38: [2, 6],
            39: [2, 6]
          },
          {
            5: [2, 7],
            6: [2, 7],
            7: [2, 7],
            8: [2, 7],
            9: [2, 7],
            10: [1, 16],
            11: [2, 7],
            12: [2, 7],
            13: [2, 7],
            16: [2, 7],
            17: [2, 7],
            18: [2, 7],
            19: [2, 7],
            21: [2, 7],
            23: [2, 7],
            29: [2, 7],
            30: [2, 7],
            31: [2, 7],
            32: 24,
            33: [2, 7],
            34: [2, 7],
            35: [2, 7],
            36: [2, 7],
            37: [2, 7],
            38: [2, 7],
            39: [2, 7]
          },
          {
            5: [2, 8],
            6: [2, 8],
            7: [2, 8],
            8: [2, 8],
            9: [2, 8],
            10: [1, 16],
            11: [2, 8],
            12: [2, 8],
            13: [2, 8],
            16: [2, 8],
            17: [2, 8],
            18: [2, 8],
            19: [2, 8],
            21: [2, 8],
            23: [2, 8],
            29: [2, 8],
            30: [2, 8],
            31: [2, 8],
            32: 24,
            33: [2, 8],
            34: [2, 8],
            35: [2, 8],
            36: [2, 8],
            37: [2, 8],
            38: [2, 8],
            39: [2, 8]
          },
          {
            5: [2, 9],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [2, 9],
            13: [2, 9],
            16: [2, 9],
            17: [2, 9],
            18: [1, 20],
            19: [1, 21],
            21: [2, 9],
            23: [2, 9],
            29: [1, 22],
            30: [2, 9],
            31: [2, 9],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            5: [2, 10],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [2, 10],
            16: [2, 10],
            17: [2, 10],
            18: [1, 20],
            19: [1, 21],
            21: [2, 10],
            23: [2, 10],
            29: [1, 22],
            30: [2, 10],
            31: [2, 10],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            5: [2, 13],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [2, 13],
            13: [2, 13],
            16: [2, 13],
            17: [2, 13],
            18: [2, 13],
            19: [2, 13],
            21: [2, 13],
            23: [2, 13],
            29: [1, 22],
            30: [2, 13],
            31: [2, 13],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            5: [2, 14],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [2, 14],
            13: [2, 14],
            16: [2, 14],
            17: [2, 14],
            18: [2, 14],
            19: [2, 14],
            21: [2, 14],
            23: [2, 14],
            29: [1, 22],
            30: [2, 14],
            31: [2, 14],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            5: [2, 24],
            6: [2, 24],
            7: [2, 24],
            8: [2, 24],
            9: [2, 24],
            10: [1, 16],
            11: [2, 24],
            12: [2, 24],
            13: [2, 24],
            16: [2, 24],
            17: [2, 24],
            18: [2, 24],
            19: [2, 24],
            21: [2, 24],
            23: [2, 24],
            29: [2, 24],
            30: [2, 24],
            31: [2, 24],
            32: 24,
            33: [2, 24],
            34: [2, 24],
            35: [2, 24],
            36: [2, 24],
            37: [2, 24],
            38: [2, 24],
            39: [2, 24]
          },
          {
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            18: [1, 20],
            19: [1, 21],
            29: [1, 22],
            30: [1, 23],
            31: [1, 60],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            5: [2, 33],
            6: [2, 33],
            7: [2, 33],
            8: [2, 33],
            9: [2, 33],
            10: [2, 33],
            11: [2, 33],
            12: [2, 33],
            13: [2, 33],
            16: [2, 33],
            17: [2, 33],
            18: [2, 33],
            19: [2, 33],
            21: [2, 33],
            23: [2, 33],
            29: [2, 33],
            30: [2, 33],
            31: [2, 33],
            33: [2, 33],
            34: [2, 33],
            35: [2, 33],
            36: [2, 33],
            37: [2, 33],
            38: [2, 33],
            39: [2, 33]
          },
          {
            5: [2, 34],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [2, 34],
            13: [2, 34],
            16: [2, 34],
            17: [2, 34],
            18: [2, 34],
            19: [2, 34],
            21: [2, 34],
            23: [2, 34],
            29: [1, 22],
            30: [2, 34],
            31: [2, 34],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            4: 61,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            5: [2, 15],
            6: [2, 15],
            7: [2, 15],
            8: [2, 15],
            9: [2, 15],
            10: [2, 15],
            11: [2, 15],
            12: [2, 15],
            13: [2, 15],
            16: [2, 15],
            17: [2, 15],
            18: [2, 15],
            19: [2, 15],
            21: [2, 15],
            23: [2, 15],
            29: [2, 15],
            30: [2, 15],
            31: [2, 15],
            33: [2, 15],
            34: [2, 15],
            35: [2, 15],
            36: [2, 15],
            37: [2, 15],
            38: [2, 15],
            39: [2, 15]
          },
          {
            4: 62,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            5: [2, 20],
            6: [2, 20],
            7: [2, 20],
            8: [2, 20],
            9: [2, 20],
            10: [2, 20],
            11: [2, 20],
            12: [2, 20],
            13: [2, 20],
            16: [2, 20],
            17: [2, 20],
            18: [2, 20],
            19: [2, 20],
            21: [2, 20],
            23: [2, 20],
            29: [2, 20],
            30: [2, 20],
            31: [2, 20],
            32: 24,
            33: [2, 20],
            34: [2, 20],
            35: [2, 20],
            36: [2, 20],
            37: [2, 20],
            38: [2, 20],
            39: [2, 20]
          },
          {
            5: [2, 21],
            6: [2, 21],
            7: [2, 21],
            8: [2, 21],
            9: [2, 21],
            10: [2, 21],
            11: [2, 21],
            12: [2, 21],
            13: [2, 21],
            16: [2, 21],
            17: [2, 21],
            18: [2, 21],
            19: [2, 21],
            21: [2, 21],
            23: [2, 21],
            29: [2, 21],
            30: [2, 21],
            31: [2, 21],
            33: [2, 21],
            34: [2, 21],
            35: [2, 21],
            36: [2, 21],
            37: [2, 21],
            38: [2, 21],
            39: [2, 21]
          },
          {
            21: [1, 63],
            23: [1, 64]
          },
          {
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            18: [1, 20],
            19: [1, 21],
            21: [2, 35],
            23: [2, 35],
            29: [1, 22],
            30: [1, 23],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            4: 65,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            17: [1, 66],
            18: [1, 20],
            19: [1, 21],
            29: [1, 22],
            30: [1, 23],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            18: [1, 20],
            19: [1, 21],
            21: [1, 67],
            23: [2, 36],
            29: [1, 22],
            30: [1, 23],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            5: [2, 22],
            6: [2, 22],
            7: [2, 22],
            8: [2, 22],
            9: [2, 22],
            10: [2, 22],
            11: [2, 22],
            12: [2, 22],
            13: [2, 22],
            16: [2, 22],
            17: [2, 22],
            18: [2, 22],
            19: [2, 22],
            21: [2, 22],
            23: [2, 22],
            29: [2, 22],
            30: [2, 22],
            31: [2, 22],
            33: [2, 22],
            34: [2, 22],
            35: [2, 22],
            36: [2, 22],
            37: [2, 22],
            38: [2, 22],
            39: [2, 22]
          },
          {
            4: 68,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            5: [2, 25],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            16: [2, 25],
            17: [2, 25],
            18: [1, 20],
            19: [1, 21],
            21: [2, 25],
            23: [2, 25],
            29: [1, 22],
            30: [1, 23],
            31: [2, 25],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            4: 69,
            6: [1, 3],
            14: [1, 4],
            15: [1, 5],
            20: [1, 6],
            24: [1, 7],
            25: [1, 8],
            26: [1, 9],
            28: 10
          },
          {
            5: [2, 16],
            6: [2, 16],
            7: [2, 16],
            8: [2, 16],
            9: [2, 16],
            10: [2, 16],
            11: [2, 16],
            12: [2, 16],
            13: [2, 16],
            16: [2, 16],
            17: [2, 16],
            18: [2, 16],
            19: [2, 16],
            21: [2, 16],
            23: [2, 16],
            29: [2, 16],
            30: [2, 16],
            31: [2, 16],
            33: [2, 16],
            34: [2, 16],
            35: [2, 16],
            36: [2, 16],
            37: [2, 16],
            38: [2, 16],
            39: [2, 16]
          },
          {
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            18: [1, 20],
            19: [1, 21],
            21: [2, 36],
            23: [2, 36],
            29: [1, 22],
            30: [1, 23],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          },
          {
            5: [2, 12],
            6: [1, 13],
            7: [1, 12],
            8: [1, 14],
            9: [1, 15],
            10: [1, 16],
            11: [1, 17],
            12: [1, 18],
            13: [1, 19],
            16: [2, 12],
            17: [2, 12],
            18: [1, 20],
            19: [1, 21],
            21: [2, 12],
            23: [2, 12],
            29: [1, 22],
            30: [1, 23],
            31: [2, 12],
            32: 24,
            33: [1, 25],
            34: [1, 26],
            35: [1, 27],
            36: [1, 28],
            37: [1, 29],
            38: [1, 30],
            39: [1, 31]
          }
        ],
        defaultActions: {
          11: [2, 1]
        },
        parseError: function parseError(str2, hash) {
          throw new Error(str2);
        },
        parse: function parse2(input2) {
          var self2 = this, stack2 = [0], vstack = [null], lstack = [], table2 = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
          this.lexer.setInput(input2);
          this.lexer.yy = this.yy;
          this.yy.lexer = this.lexer;
          this.yy.parser = this;
          if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
          var yyloc = this.lexer.yylloc;
          lstack.push(yyloc);
          var ranges = this.lexer.options && this.lexer.options.ranges;
          if (typeof this.yy.parseError === "function")
            this.parseError = this.yy.parseError;
          function popStack(n) {
            stack2.length = stack2.length - 2 * n;
            vstack.length = vstack.length - n;
            lstack.length = lstack.length - n;
          }
          function lex2() {
            var token2;
            token2 = self2.lexer.lex() || 1;
            if (typeof token2 !== "number") {
              token2 = self2.symbols_[token2] || token2;
            }
            return token2;
          }
          var symbol, preErrorSymbol, state, action, r2, yyval = {}, p, len, newState, expected;
          while (true) {
            state = stack2[stack2.length - 1];
            if (this.defaultActions[state]) {
              action = this.defaultActions[state];
            } else {
              if (symbol === null || typeof symbol == "undefined") {
                symbol = lex2();
              }
              action = table2[state] && table2[state][symbol];
            }
            if (typeof action === "undefined" || !action.length || !action[0]) {
              var errStr = "";
              if (!recovering) {
                expected = [];
                for (p in table2[state])
                  if (this.terminals_[p] && p > 2) {
                    expected.push("'" + this.terminals_[p] + "'");
                  }
                if (this.lexer.showPosition) {
                  errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
                } else {
                  errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
                }
                this.parseError(errStr, {
                  text: this.lexer.match,
                  token: this.terminals_[symbol] || symbol,
                  line: this.lexer.yylineno,
                  loc: yyloc,
                  expected
                });
              }
              if (recovering == 3) {
                if (symbol == EOF) {
                  throw new Error(errStr || "Parsing halted.");
                }
                yyleng = this.lexer.yyleng;
                yytext = this.lexer.yytext;
                yylineno = this.lexer.yylineno;
                yyloc = this.lexer.yylloc;
                symbol = lex2();
              }
              while (1) {
                if (TERROR.toString() in table2[state]) {
                  break;
                }
                if (state === 0) {
                  throw new Error(errStr || "Parsing halted.");
                }
                popStack(1);
                state = stack2[stack2.length - 1];
              }
              preErrorSymbol = symbol == 2 ? null : symbol;
              symbol = TERROR;
              state = stack2[stack2.length - 1];
              action = table2[state] && table2[state][TERROR];
              recovering = 3;
            }
            if (action[0] instanceof Array && action.length > 1) {
              throw new Error(
                "Parse Error: multiple actions possible at state: " + state + ", token: " + symbol
              );
            }
            switch (action[0]) {
              case 1:
                stack2.push(symbol);
                vstack.push(this.lexer.yytext);
                lstack.push(this.lexer.yylloc);
                stack2.push(action[1]);
                symbol = null;
                if (!preErrorSymbol) {
                  yyleng = this.lexer.yyleng;
                  yytext = this.lexer.yytext;
                  yylineno = this.lexer.yylineno;
                  yyloc = this.lexer.yylloc;
                  if (recovering > 0) recovering--;
                } else {
                  symbol = preErrorSymbol;
                  preErrorSymbol = null;
                }
                break;
              case 2:
                len = this.productions_[action[1]][1];
                yyval.$ = vstack[vstack.length - len];
                yyval._$ = {
                  first_line: lstack[lstack.length - (len || 1)].first_line,
                  last_line: lstack[lstack.length - 1].last_line,
                  first_column: lstack[lstack.length - (len || 1)].first_column,
                  last_column: lstack[lstack.length - 1].last_column
                };
                if (ranges) {
                  yyval._$.range = [
                    lstack[lstack.length - (len || 1)].range[0],
                    lstack[lstack.length - 1].range[1]
                  ];
                }
                r2 = this.performAction.call(
                  yyval,
                  yytext,
                  yyleng,
                  yylineno,
                  this.yy,
                  action[1],
                  vstack,
                  lstack
                );
                if (typeof r2 !== "undefined") {
                  return r2;
                }
                if (len) {
                  stack2 = stack2.slice(0, -1 * len * 2);
                  vstack = vstack.slice(0, -1 * len);
                  lstack = lstack.slice(0, -1 * len);
                }
                stack2.push(this.productions_[action[1]][0]);
                vstack.push(yyval.$);
                lstack.push(yyval._$);
                newState = table2[stack2[stack2.length - 2]][stack2[stack2.length - 1]];
                stack2.push(newState);
                break;
              case 3:
                return true;
            }
          }
          return true;
        }
      };
      var lexer = function() {
        var lexer2 = {
          EOF: 1,
          parseError: function parseError(str2, hash) {
            if (this.yy.parser) {
              this.yy.parser.parseError(str2, hash);
            } else {
              throw new Error(str2);
            }
          },
          setInput: function(input2) {
            this._input = input2;
            this._more = this._less = this.done = false;
            this.yylineno = this.yyleng = 0;
            this.yytext = this.matched = this.match = "";
            this.conditionStack = ["INITIAL"];
            this.yylloc = {
              first_line: 1,
              first_column: 0,
              last_line: 1,
              last_column: 0
            };
            if (this.options.ranges) this.yylloc.range = [0, 0];
            this.offset = 0;
            return this;
          },
          input: function() {
            var ch3 = this._input[0];
            this.yytext += ch3;
            this.yyleng++;
            this.offset++;
            this.match += ch3;
            this.matched += ch3;
            var lines = ch3.match(/(?:\r\n?|\n).*/g);
            if (lines) {
              this.yylineno++;
              this.yylloc.last_line++;
            } else {
              this.yylloc.last_column++;
            }
            if (this.options.ranges) this.yylloc.range[1]++;
            this._input = this._input.slice(1);
            return ch3;
          },
          unput: function(ch3) {
            var len = ch3.length;
            var lines = ch3.split(/(?:\r\n?|\n)/g);
            this._input = ch3 + this._input;
            this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
            this.offset -= len;
            var oldLines = this.match.split(/(?:\r\n?|\n)/g);
            this.match = this.match.substr(0, this.match.length - 1);
            this.matched = this.matched.substr(0, this.matched.length - 1);
            if (lines.length - 1) this.yylineno -= lines.length - 1;
            var r2 = this.yylloc.range;
            this.yylloc = {
              first_line: this.yylloc.first_line,
              last_line: this.yylineno + 1,
              first_column: this.yylloc.first_column,
              last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
            };
            if (this.options.ranges) {
              this.yylloc.range = [r2[0], r2[0] + this.yyleng - len];
            }
            return this;
          },
          more: function() {
            this._more = true;
            return this;
          },
          less: function(n) {
            this.unput(this.match.slice(n));
          },
          pastInput: function() {
            var past = this.matched.substr(
              0,
              this.matched.length - this.match.length
            );
            return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, "");
          },
          upcomingInput: function() {
            var next = this.match;
            if (next.length < 20) {
              next += this._input.substr(0, 20 - next.length);
            }
            return (next.substr(0, 20) + (next.length > 20 ? "..." : "")).replace(
              /\n/g,
              ""
            );
          },
          showPosition: function() {
            var pre = this.pastInput();
            var c2 = new Array(pre.length + 1).join("-");
            return pre + this.upcomingInput() + "\n" + c2 + "^";
          },
          next: function() {
            if (this.done) {
              return this.EOF;
            }
            if (!this._input) this.done = true;
            var token2, match, tempMatch, index2, lines;
            if (!this._more) {
              this.yytext = "";
              this.match = "";
            }
            var rules = this._currentRules();
            for (var i2 = 0; i2 < rules.length; i2++) {
              tempMatch = this._input.match(this.rules[rules[i2]]);
              if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
                match = tempMatch;
                index2 = i2;
                if (!this.options.flex) break;
              }
            }
            if (match) {
              lines = match[0].match(/(?:\r\n?|\n).*/g);
              if (lines) this.yylineno += lines.length;
              this.yylloc = {
                first_line: this.yylloc.last_line,
                last_line: this.yylineno + 1,
                first_column: this.yylloc.last_column,
                last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length
              };
              this.yytext += match[0];
              this.match += match[0];
              this.matches = match;
              this.yyleng = this.yytext.length;
              if (this.options.ranges) {
                this.yylloc.range = [this.offset, this.offset += this.yyleng];
              }
              this._more = false;
              this._input = this._input.slice(match[0].length);
              this.matched += match[0];
              token2 = this.performAction.call(
                this,
                this.yy,
                this,
                rules[index2],
                this.conditionStack[this.conditionStack.length - 1]
              );
              if (this.done && this._input) this.done = false;
              if (token2) return token2;
              else return;
            }
            if (this._input === "") {
              return this.EOF;
            } else {
              return this.parseError(
                "Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition(),
                {
                  text: "",
                  token: null,
                  line: this.yylineno
                }
              );
            }
          },
          lex: function lex2() {
            var r2 = this.next();
            if (typeof r2 !== "undefined") {
              return r2;
            } else {
              return this.lex();
            }
          },
          begin: function begin(condition) {
            this.conditionStack.push(condition);
          },
          popState: function popState() {
            return this.conditionStack.pop();
          },
          _currentRules: function _currentRules() {
            return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
          },
          topState: function() {
            return this.conditionStack[this.conditionStack.length - 2];
          },
          pushState: function begin(condition) {
            this.begin(condition);
          }
        };
        lexer2.options = {};
        lexer2.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {
          switch ($avoiding_name_collisions) {
            case 0:
              return "*";
            case 1:
              return "/";
            case 2:
              return "-";
            case 3:
              return "+";
            case 4:
              return "^";
            case 5:
              return "(";
            case 6:
              return ")";
            case 7:
              return ",";
            case 8:
              return "==";
            case 9:
              return "!=";
            case 10:
              return "~=";
            case 11:
              return ">=";
            case 12:
              return "<=";
            case 13:
              return "<";
            case 14:
              return ">";
            case 15:
              return "notIn";
            case 16:
              return "and";
            case 17:
              return "or";
            case 18:
              return "not";
            case 19:
              return "in";
            case 20:
              return "of";
            case 21:
              return "if";
            case 22:
              return "then";
            case 23:
              return "else";
            case 24:
              return "mod";
            case 25:
              break;
            case 26:
              return "Number";
            case 27:
              yy_.yytext = JSON.stringify({
                name: yy_.yytext,
                type: "unescaped"
              });
              return "Symbol";
            case 28:
              yy_.yytext = JSON.stringify({
                name: yy.buildString("'", yy_.yytext),
                type: "single-quoted"
              });
              return "Symbol";
            case 29:
              yy_.yytext = JSON.stringify(yy.buildString('"', yy_.yytext));
              return "String";
            case 30:
              return "%";
            case 31:
              return "?";
            case 32:
              return ":";
            case 33:
              return "EndOfExpression";
          }
        };
        lexer2.rules = [
          /^(?:\*)/,
          /^(?:\/)/,
          /^(?:-)/,
          /^(?:\+)/,
          /^(?:\^)/,
          /^(?:\()/,
          /^(?:\))/,
          /^(?:\,)/,
          /^(?:==)/,
          /^(?:\!=)/,
          /^(?:\~=)/,
          /^(?:>=)/,
          /^(?:<=)/,
          /^(?:<)/,
          /^(?:>)/,
          /^(?:not\s+in[^\w])/,
          /^(?:and[^\w])/,
          /^(?:or[^\w])/,
          /^(?:not[^\w])/,
          /^(?:in[^\w])/,
          /^(?:of[^\w])/,
          /^(?:if[^\w])/,
          /^(?:then[^\w])/,
          /^(?:else[^\w])/,
          /^(?:mod[^\w])/,
          /^(?:\s+)/,
          /^(?:[0-9]+(?:\.[0-9]+)?(?![0-9\.]))/,
          /^(?:[a-zA-Z$_][\.a-zA-Z0-9$_]*)/,
          /^(?:'(?:\\'|\\\\|[^'\\])*')/,
          /^(?:"(?:\\"|\\\\|[^"\\])*")/,
          /^(?:\%)/,
          /^(?:\?)/,
          /^(?::)/,
          /^(?:$)/
        ];
        lexer2.conditions = {
          INITIAL: {
            rules: [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15,
              16,
              17,
              18,
              19,
              20,
              21,
              22,
              23,
              24,
              25,
              26,
              27,
              28,
              29,
              30,
              31,
              32,
              33
            ],
            inclusive: true
          }
        };
        return lexer2;
      }();
      parser2.lexer = lexer;
      function Parser2() {
        this.yy = {};
      }
      Parser2.prototype = parser2;
      parser2.Parser = Parser2;
      return new Parser2();
    }();
    const parser = _parser;
    _parser.Parser;
    class UnknownFunctionError extends ReferenceError {
      constructor(funcName) {
        super(`Unknown function: ${funcName}()`);
        __publicField(this, "I18N_STRING", "UNKNOWN_FUNCTION");
        this.functionName = funcName;
      }
    }
    class UnknownPropertyError extends ReferenceError {
      constructor(propName) {
        super(`Property “${propName}” does not exist.`);
        __publicField(this, "I18N_STRING", "UNKNOWN_PROPERTY");
        this.propertyName = propName;
      }
    }
    class UnknownOptionError extends TypeError {
      constructor(key2) {
        super(`Unknown option: ${key2}`);
        __publicField(this, "I18N_STRING", "UNKNOWN_OPTION");
        this.keyName = key2;
      }
    }
    class UnexpectedTypeError extends TypeError {
      constructor(expected, got) {
        super(`Expected a ${expected}, but got a ${got} instead.`);
        __publicField(this, "I18N_STRING", "UNEXPECTED_TYPE");
        this.expectedType = expected;
        this.recievedType = got;
      }
    }
    class InternalError extends Error {
      constructor(message2) {
        super(message2);
        __publicField(this, "I18N_STRING", "INTERNAL");
      }
    }
    function hasOwnProperty(obj, prop) {
      if (typeof obj === "object" || typeof obj === "function") {
        return Object.prototype.hasOwnProperty.call(obj, prop);
      }
      return false;
    }
    function mod(a, b) {
      return (a % b + b) % b;
    }
    function unbox(value2) {
      if (typeof value2 !== "object") return value2;
      if (value2 instanceof Number || value2 instanceof String || value2 instanceof Boolean)
        return value2.valueOf();
    }
    function unwrap$1(value2) {
      if (Array.isArray(value2) && value2.length === 1) value2 = value2[0];
      return unbox(value2);
    }
    function prettyType(value2) {
      value2 = unwrap$1(value2);
      if (value2 === void 0) return "undefined";
      if (value2 === null) return "null";
      if (value2 === true) return "true";
      if (value2 === false) return "false";
      if (typeof value2 === "number") return "number";
      if (typeof value2 === "string") return "text";
      if (typeof value2 !== "object" && typeof value2 !== "function")
        return "unknown type";
      if (Array.isArray(value2)) return "list";
      return "object";
    }
    function num(value2) {
      value2 = unwrap$1(value2);
      if (typeof value2 === "number") return value2;
      throw new UnexpectedTypeError("number", prettyType(value2));
    }
    function str(value2) {
      value2 = unwrap$1(value2);
      if (typeof value2 === "string") return value2;
      throw new UnexpectedTypeError("text", prettyType(value2));
    }
    function numstr(value2) {
      value2 = unwrap$1(value2);
      if (typeof value2 === "string" || typeof value2 === "number") return value2;
      throw new UnexpectedTypeError("text or number", prettyType(value2));
    }
    function bool(value2) {
      value2 = unwrap$1(value2);
      if (typeof value2 === "boolean") return value2;
      throw new UnexpectedTypeError(
        "logical value (“true” or “false”)",
        prettyType(value2)
      );
    }
    function arr(value2) {
      if (value2 === void 0 || value2 === null) {
        throw new UnexpectedTypeError("list", prettyType(value2));
      }
      if (Array.isArray(value2)) {
        return value2;
      } else {
        return [value2];
      }
    }
    function flatten$1(input2) {
      const stack2 = [...input2];
      const res = [];
      while (stack2.length) {
        const next = stack2.pop();
        if (Array.isArray(next)) {
          stack2.push(...next);
        } else {
          res.push(next);
        }
      }
      return res.reverse();
    }
    const std = {
      isfn(fns, funcName) {
        return hasOwnProperty(fns, funcName) && typeof fns[funcName] === "function";
      },
      unknown(funcName) {
        throw new UnknownFunctionError(funcName);
      },
      coerceArray: arr,
      coerceNumber: num,
      coerceNumberOrString: numstr,
      coerceBoolean: bool,
      isSubset(a, b) {
        const A2 = arr(a);
        const B = arr(b);
        return A2.every((val) => B.includes(val));
      },
      warnDeprecated: /* @__PURE__ */ function() {
        const warnMax = 3;
        let warnedTimes = {
          ternary: 0,
          modulo: 0
        };
        return (cause, value2) => {
          switch (cause) {
            case "ternary":
              if (warnedTimes.ternary++ >= warnMax) break;
              console.warn(
                "The use of ? and : as conditional operators has been deprecated in Filtrex v3 in favor of the if..then..else ternary operator. See issue #34 for more information."
              );
              break;
            case "modulo":
              if (warnedTimes.modulo++ >= warnMax) break;
              console.warn(
                "The use of '%' as a modulo operator has been deprecated in Filtrex v3 in favor of the 'mod' operator. You can use it like this: '3 mod 2 == 1'. See issue #48 for more information."
              );
              break;
          }
          return value2;
        };
      }(),
      buildString(quote, literal2) {
        quote = String(quote)[0];
        literal2 = String(literal2);
        let built = "";
        if (literal2[0] !== quote || literal2[literal2.length - 1] !== quote)
          throw new InternalError(
            `Unexpected internal error: String literal doesn't begin/end with the right quotation mark.`
          );
        for (let i2 = 1; i2 < literal2.length - 1; i2++) {
          if (literal2[i2] === "\\") {
            i2++;
            if (i2 >= literal2.length - 1)
              throw new InternalError(
                `Unexpected internal error: Unescaped backslash at the end of string literal.`
              );
            if (literal2[i2] === "\\") built += "\\";
            else if (literal2[i2] === quote) built += quote;
            else
              throw new InternalError(
                `Unexpected internal error: Invalid escaped character in string literal: ${literal2[i2]}`
              );
          } else if (literal2[i2] === quote) {
            throw new InternalError(
              `Unexpected internal error: String literal contains unescaped quotation mark.`
            );
          } else {
            built += literal2[i2];
          }
        }
        return built;
      },
      reduceRelation(arr2) {
        const declarations = [];
        const comparisons = [];
        let previousExpression = flatten$1([arr2[0]]).join("");
        let j2 = 0;
        for (let i2 = 1; i2 < arr2.length - 1; i2 += 2) {
          const expr = flatten$1([arr2[i2 + 1]]).join("");
          const tempVar = `tmp${j2++}`;
          comparisons.push(
            `ops["${arr2[i2]}"](${previousExpression}, ${tempVar} = ${expr})`
          );
          previousExpression = tempVar;
          declarations.push(tempVar);
        }
        return `(function(){ var ${declarations.join(", ")}; return ${comparisons.join(" && ")};})()`;
      }
    };
    parser.yy = Object.create(std);
    function compileExpression(expression, options2) {
      if (arguments.length > 2) throw new TypeError("Too many arguments.");
      options2 = typeof options2 === "object" ? options2 : {};
      const knownOptions = [
        "extraFunctions",
        "constants",
        "customProp",
        "operators"
      ];
      let { extraFunctions, constants, customProp, operators } = options2;
      for (const key2 of Object.keys(options2))
        if (!knownOptions.includes(key2)) throw new UnknownOptionError(key2);
      let functions = {
        abs: Math.abs,
        ceil: Math.ceil,
        floor: Math.floor,
        log: Math.log,
        log2: Math.log2,
        log10: Math.log10,
        max: Math.max,
        min: Math.min,
        round: Math.round,
        sqrt: Math.sqrt,
        exists: (v) => v !== void 0 && v !== null,
        empty: (v) => v === void 0 || v === null || v === "" || Array.isArray(v) && v.length === 0
      };
      if (extraFunctions) {
        for (const name2 of Object.keys(extraFunctions)) {
          functions[name2] = extraFunctions[name2];
        }
      }
      let defaultOperators = {
        "+": (a, b) => numstr(a) + numstr(b),
        "-": (a, b) => b === void 0 ? -num(a) : num(a) - num(b),
        "*": (a, b) => num(a) * num(b),
        "/": (a, b) => num(a) / num(b),
        "^": (a, b) => Math.pow(num(a), num(b)),
        mod: (a, b) => mod(num(a), num(b)),
        "==": (a, b) => a === b,
        "!=": (a, b) => a !== b,
        "<": (a, b) => num(a) < num(b),
        "<=": (a, b) => num(a) <= num(b),
        ">=": (a, b) => num(a) >= num(b),
        ">": (a, b) => num(a) > num(b),
        "~=": (a, b) => RegExp(str(b)).test(str(a))
      };
      if (operators) {
        for (const name2 of Object.keys(operators)) {
          defaultOperators[name2] = operators[name2];
        }
      }
      operators = defaultOperators;
      constants = constants ?? {};
      let js = flatten$1(parser.parse(expression));
      js.unshift("return ");
      js.push(";");
      function nakedProp(name2, obj, type) {
        if (hasOwnProperty(obj ?? {}, name2)) return obj[name2];
        throw new UnknownPropertyError(name2);
      }
      function safeGetter(obj) {
        return function get2(name2) {
          if (hasOwnProperty(obj ?? {}, name2)) return obj[name2];
          throw new UnknownPropertyError(name2);
        };
      }
      if (typeof customProp === "function") {
        nakedProp = (name2, obj, type) => customProp(name2, safeGetter(obj), obj, type);
      }
      function createCall(fns) {
        return function call(_ref) {
          let { name: name2 } = _ref;
          for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
          }
          if (hasOwnProperty(fns, name2) && typeof fns[name2] === "function")
            return fns[name2](...args);
          throw new UnknownFunctionError(name2);
        };
      }
      function prop(_ref2, obj) {
        let { name: name2, type } = _ref2;
        if (type === "unescaped" && hasOwnProperty(constants, name2))
          return constants[name2];
        return nakedProp(name2, obj, type);
      }
      let func = new Function("call", "ops", "std", "prop", "data", js.join(""));
      return function(data) {
        try {
          return func(createCall(functions), operators, std, prop, data);
        } catch (e) {
          return e;
        }
      };
    }
    const coerceValue = (value2, descriptor) => {
      if (descriptor && descriptor.scoreType === kScoreTypeBoolean) {
        return Boolean(value2);
      } else {
        return value2;
      }
    };
    const isFilteringSupportedForValue = (value2) => ["string", "number", "boolean"].includes(typeof value2) || value2 === null;
    const bannedShortScoreNames = (scores2) => {
      const used = /* @__PURE__ */ new Set();
      const banned = /* @__PURE__ */ new Set();
      for (const { scorer, name: name2 } of scores2) {
        banned.add(scorer);
        if (used.has(name2)) {
          banned.add(name2);
        } else {
          used.add(name2);
        }
      }
      return banned;
    };
    const filterExpressionConstants = {
      True: true,
      False: false,
      None: null
    };
    const scoreVariables = (evalDescriptor, sampleScores) => {
      const bannedShortNames = bannedShortScoreNames(evalDescriptor.scores);
      const variables = {};
      const addScore = (variableName, scoreLabel, value2) => {
        const coercedValue = coerceValue(
          value2,
          evalDescriptor.scoreDescriptor(scoreLabel)
        );
        if (isFilteringSupportedForValue(coercedValue)) {
          variables[variableName] = coercedValue;
        }
      };
      for (const [scorer, score2] of Object.entries(sampleScores || {})) {
        addScore(scorer, { scorer, name: scorer }, score2.value);
        if (typeof score2.value === "object") {
          for (const [name2, value2] of Object.entries(score2.value)) {
            addScore(`${scorer}.${name2}`, { scorer, name: name2 }, value2);
            if (!bannedShortNames.has(name2)) {
              addScore(name2, { scorer, name: name2 }, value2);
            }
          }
        }
      }
      return variables;
    };
    const sampleVariables = (sample2) => {
      return {
        has_error: !!sample2.error
      };
    };
    const scoreFilterItems = (evalDescriptor) => {
      const items = [];
      const bannedShortNames = bannedShortScoreNames(evalDescriptor.scores);
      const valueToString = (value2) => typeof value2 === "string" ? `"${value2}"` : String(value2);
      const addScore = (scoreLabel, shortName, qualifiedName) => {
        const canonicalName = shortName || qualifiedName;
        if (!canonicalName) {
          throw new Error("Unable to create a canonical name for a score");
        }
        const descriptor = evalDescriptor.scoreDescriptor(scoreLabel);
        const scoreType = descriptor == null ? void 0 : descriptor.scoreType;
        if (!descriptor) {
          items.push({
            shortName,
            qualifiedName,
            canonicalName,
            tooltip: void 0,
            categories: [],
            scoreType
          });
          return;
        }
        var tooltip = `${canonicalName}: ${descriptor.scoreType}`;
        var categories = [];
        if (descriptor.min !== void 0 || descriptor.max !== void 0) {
          const rounded = (num2) => {
            return parseFloat(num2.toPrecision(3)).toString();
          };
          tooltip += `
range: ${rounded(descriptor.min || 0)} to ${rounded(descriptor.max || 0)}`;
        }
        if (descriptor.categories) {
          categories = descriptor.categories.map((cat) => {
            const val = cat.val;
            return valueToString(val);
          });
          tooltip += `
categories: ${categories.join(" ")}`;
        }
        items.push({
          shortName,
          qualifiedName,
          canonicalName,
          tooltip,
          categories,
          scoreType
        });
      };
      for (const { name: name2, scorer } of evalDescriptor.scores) {
        const hasShortName = name2 === scorer || !bannedShortNames.has(name2);
        const hasQualifiedName = name2 !== scorer;
        const shortName = hasShortName ? name2 : void 0;
        const qualifiedName = hasQualifiedName ? `${scorer}.${name2}` : void 0;
        addScore({ name: name2, scorer }, shortName, qualifiedName);
      }
      return items;
    };
    const filterExpression = (evalDescriptor, sample2, filterValue) => {
      var _a2, _b2;
      try {
        const inputContains = (regex2) => {
          return inputString(sample2.input).some(
            (msg) => msg.match(new RegExp(regex2, "i"))
          );
        };
        const targetContains = (regex2) => {
          let targets = Array.isArray(sample2.target) ? sample2.target : [sample2.target];
          return targets.some((target2) => target2.match(new RegExp(regex2, "i")));
        };
        const errorContains = (regex2) => {
          var _a3;
          return !!((_a3 = sample2.error) == null ? void 0 : _a3.match(new RegExp(regex2, "i")));
        };
        const extraFunctions = {
          input_contains: inputContains,
          target_contains: targetContains,
          error_contains: errorContains
        };
        const mySampleVariables = sampleVariables(sample2);
        const vars = {
          ...mySampleVariables,
          ...scoreVariables(evalDescriptor, sample2.scores)
        };
        const resolveVariable = (name2, get2) => {
          if (name2 in mySampleVariables) {
            return get2(name2);
          }
          return sample2.error ? void 0 : get2(name2);
        };
        const expression = compileExpression(filterValue, {
          extraFunctions,
          constants: filterExpressionConstants,
          customProp: resolveVariable
        });
        const result2 = expression(vars);
        if (typeof result2 === "boolean") {
          return { matches: result2, error: void 0 };
        } else if (result2 instanceof Error) {
          throw result2;
        } else {
          throw new TypeError(
            `Filter expression returned a non-boolean value: ${result2}`
          );
        }
      } catch (error2) {
        if (error2 instanceof ReferenceError) {
          const errorObj = error2;
          const propertyName2 = errorObj["propertyName"] || "";
          if (propertyName2) {
            const regex2 = new RegExp(`\\b${propertyName2}\\b`);
            const match = regex2.exec(filterValue);
            if (match) {
              return {
                matches: false,
                error: {
                  from: match.index,
                  to: match.index + propertyName2.length,
                  message: error2.message,
                  severity: "warning"
                }
              };
            }
          }
        }
        const message2 = error2 instanceof Error ? error2.message : "";
        if (message2.startsWith("Parse error") || message2.startsWith("Lexical error")) {
          const from = (_b2 = (_a2 = message2.match(/^(-*)\^$/m)) == null ? void 0 : _a2[1]) == null ? void 0 : _b2.length;
          return {
            matches: false,
            error: {
              from,
              message: "Syntax error",
              severity: "error"
            }
          };
        }
        return {
          matches: false,
          error: {
            message: message2,
            severity: "error"
          }
        };
      }
    };
    const filterSamples = (evalDescriptor, samples, filterValue) => {
      var error2 = void 0;
      const result2 = samples.filter((sample2) => {
        if (filterValue) {
          const { matches, error: sampleError } = filterExpression(
            evalDescriptor,
            sample2,
            filterValue
          );
          error2 || (error2 = sampleError);
          return matches;
        } else {
          return true;
        }
      });
      return { result: result2, error: error2 };
    };
    const flex$1 = "_flex_1kye9_1";
    const label$5 = "_label_1kye9_5";
    const styles$V = {
      flex: flex$1,
      label: label$5
    };
    const SortFilter = ({ sort, setSort, epochs }) => {
      const options2 = [
        { label: "sample asc", val: kSampleAscVal },
        { label: "sample desc", val: kSampleDescVal }
      ];
      if (epochs > 1) {
        options2.push({
          label: "epoch asc",
          val: kEpochAscVal
        });
        options2.push({
          label: "epoch desc",
          val: kEpochDescVal
        });
      }
      options2.push({
        label: "score asc",
        val: kScoreAscVal
      });
      options2.push({
        label: "score desc",
        val: kScoreDescVal
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$V.flex, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: clsx(
              "sort-filter-label",
              "text-size-smaller",
              "text-style-label",
              "text-style-secondary",
              styles$V.label
            ),
            children: "Sort:"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "select",
          {
            className: clsx("form-select", "form-select-sm", "text-size-smaller"),
            "aria-label": ".sort-filter-label",
            value: sort,
            onChange: (e) => {
              const sel = e.target;
              setSort(sel.value);
            },
            children: options2.map((option) => {
              return /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: option.val, children: option.label }, option.val);
            })
          }
        )
      ] });
    };
    const byEpoch = (sort) => {
      return sort === kEpochAscVal || sort === kEpochDescVal;
    };
    const bySample = (sort) => {
      return sort === kSampleAscVal || sort === kSampleDescVal;
    };
    const sortId = (a, b) => {
      if (isNumeric(a.id) && isNumeric(b.id)) {
        return Number(a.id) - Number(b.id);
      } else {
        return String(a.id).localeCompare(String(b.id));
      }
    };
    const sortSamples = (sort, samples, samplesDescriptor) => {
      const sortedSamples = samples.sort((a, b) => {
        switch (sort) {
          case kSampleAscVal: {
            const result2 = sortId(a, b);
            if (result2 !== 0) {
              return result2;
            } else {
              return a.epoch - b.epoch;
            }
          }
          case kSampleDescVal: {
            const result2 = sortId(b, a);
            if (result2 !== 0) {
              return result2;
            } else {
              return a.epoch - b.epoch;
            }
          }
          case kEpochAscVal: {
            const result2 = a.epoch - b.epoch;
            if (result2 !== 0) {
              return result2;
            } else {
              return sortId(a, b);
            }
          }
          case kEpochDescVal: {
            const result2 = b.epoch - a.epoch;
            if (result2 !== 0) {
              return result2;
            } else {
              return sortId(a, b);
            }
          }
          case kScoreAscVal: {
            const aScore = samplesDescriptor.selectedScore(a);
            const bScore = samplesDescriptor.selectedScore(b);
            if (aScore === void 0 || bScore === void 0 || samplesDescriptor.selectedScoreDescriptor == void 0) {
              return 0;
            }
            return samplesDescriptor.selectedScoreDescriptor.compare(
              aScore,
              bScore
            );
          }
          case kScoreDescVal: {
            const aScore = samplesDescriptor.selectedScore(a);
            const bScore = samplesDescriptor.selectedScore(b);
            if (aScore === void 0 || bScore === void 0 || samplesDescriptor.selectedScoreDescriptor == void 0) {
              return 0;
            }
            return samplesDescriptor.selectedScoreDescriptor.compare(
              bScore,
              aScore
            );
          }
          default:
            return 0;
        }
      });
      return {
        sorted: sortedSamples,
        order: sort === kSampleAscVal || sort === kEpochAscVal || sort === kScoreAscVal ? "asc" : "desc"
      };
    };
    const resolveAttachments = (value2, attachments) => {
      const kContentProtocol = "tc://";
      const kAttachmentProtocol = "attachment://";
      if (Array.isArray(value2)) {
        return value2.map((v) => resolveAttachments(v, attachments));
      }
      if (value2 && typeof value2 === "object") {
        const resolvedObject = {};
        for (const key2 of Object.keys(value2)) {
          resolvedObject[key2] = resolveAttachments(value2[key2], attachments);
        }
        return resolvedObject;
      }
      if (typeof value2 === "string") {
        let resolvedValue = value2;
        if (resolvedValue.startsWith(kContentProtocol)) {
          resolvedValue = resolvedValue.replace(
            kContentProtocol,
            kAttachmentProtocol
          );
        }
        if (resolvedValue.startsWith(kAttachmentProtocol)) {
          return attachments[resolvedValue.replace(kAttachmentProtocol, "")];
        }
        return resolvedValue;
      }
      return value2;
    };
    let vscodeApi;
    const getVscodeApi = () => {
      if (window.acquireVsCodeApi) {
        if (vscodeApi === void 0) {
          vscodeApi = window.acquireVsCodeApi();
        }
        return vscodeApi;
      } else {
        return void 0;
      }
    };
    const isVscode = () => {
      const bodyEl = document.querySelector("body");
      return bodyEl !== null && !!bodyEl.getAttributeNames().find((attr) => {
        return attr.includes("data-vscode-");
      });
    };
    const dirname$1 = "_dirname_16ra5_1";
    const styles$U = {
      dirname: dirname$1
    };
    const LogDirectoryTitleView = ({
      log_dir,
      offcanvas
    }) => {
      if (log_dir) {
        const displayDir = prettyDir(log_dir);
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { display: "flex", flexDirection: "column" }, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: clsx(
                "text-style-secondary",
                "text-style-label",
                "text-size-small"
              ),
              children: "Log Directory"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              title: displayDir,
              className: clsx("text-size-base", styles$U.dirname),
              children: offcanvas ? displayDir : ""
            }
          )
        ] });
      } else {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: clsx("text-size-title"), children: offcanvas ? "Log History" : "" });
      }
    };
    const prettyDir = (path) => {
      try {
        let url = new URL(path);
        if (url.protocol === "file:") {
          return url.pathname;
        } else {
          return path;
        }
      } catch {
        return path;
      }
    };
    const sidebar = "_sidebar_1u82r_1";
    const sidebarClosed = "_sidebarClosed_1u82r_15";
    const sidebarOpen = "_sidebarOpen_1u82r_19";
    const header$2 = "_header_1u82r_23";
    const toggle$1 = "_toggle_1u82r_39";
    const progress = "_progress_1u82r_46";
    const list$1 = "_list_1u82r_50";
    const backdrop = "_backdrop_1u82r_55";
    const active = "_active_1u82r_62";
    const item$1 = "_item_1u82r_66";
    const styles$T = {
      sidebar,
      sidebarClosed,
      sidebarOpen,
      header: header$2,
      toggle: toggle$1,
      progress,
      list: list$1,
      backdrop,
      active,
      item: item$1
    };
    const error = "_error_srruf_1";
    const running = "_running_srruf_6";
    const cancelled = "_cancelled_srruf_13";
    const styles$S = {
      error,
      running,
      cancelled
    };
    const metricDisplayName = (metric2) => {
      let modifier = void 0;
      for (const metricModifier of metricModifiers) {
        modifier = metricModifier(metric2);
        if (modifier) {
          break;
        }
      }
      const metricName2 = !modifier ? metric2.name : `${metric2.name}[${modifier}]`;
      return metricName2;
    };
    const clusterMetricModifier = (metric2) => {
      if (metric2.name !== "stderr") {
        return void 0;
      }
      const clusterValue = (metric2.params || {})["cluster"];
      if (clusterValue === void 0 || typeof clusterValue !== "string") {
        return void 0;
      }
      return clusterValue;
    };
    const metricModifiers = [clusterMetricModifier];
    const container$b = "_container_1frsg_1";
    const metric = "_metric_1frsg_8";
    const metricName$1 = "_metricName_1frsg_17";
    const metricReducer$1 = "_metricReducer_1frsg_21";
    const styles$R = {
      container: container$b,
      metric,
      metricName: metricName$1,
      metricReducer: metricReducer$1
    };
    const SidebarScoreView = ({ scorer }) => {
      const showReducer = !!scorer.reducer;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$R.container, children: Object.keys(scorer.metrics).map((metric2) => {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$R.metric, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                "text-style-secondary",
                "text-style-label",
                "text-size-small",
                styles$R.metricName
              ),
              children: metricDisplayName(scorer.metrics[metric2])
            }
          ),
          showReducer ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-small", styles$R.metricReducer), children: scorer.reducer || "default" }) : "",
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-size-title-secondary", children: formatPrettyDecimal(scorer.metrics[metric2].value) })
        ] }, metric2);
      }) });
    };
    const container$a = "_container_5kpg1_1";
    const scoreWrapper = "_scoreWrapper_5kpg1_9";
    const metricName = "_metricName_5kpg1_16";
    const metricReducer = "_metricReducer_5kpg1_22";
    const metricValues = "_metricValues_5kpg1_27";
    const metricValue = "_metricValue_5kpg1_27";
    const styles$Q = {
      container: container$a,
      scoreWrapper,
      metricName,
      metricReducer,
      metricValues,
      metricValue
    };
    const SidebarScoresView = ({ scores: scores2 }) => {
      const showReducer = scores2.findIndex((score2) => !!score2.reducer) !== -1;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$Q.container, children: scores2.map((score2, idx) => {
        const name2 = score2.name;
        const reducer = score2.reducer;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$Q.scoreWrapper, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                "text-style-secondary",
                "text-style-label",
                "text-size-small",
                styles$Q.metricName
              ),
              children: name2
            }
          ),
          showReducer ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                "text-size-small",
                "text-style-label",
                "text-style-secondary",
                styles$Q.metricReducer
              ),
              children: reducer || "default"
            }
          ) : "",
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-small", styles$Q.metricValues), children: Object.keys(score2.metrics).map((key2) => {
            const metric2 = score2.metrics[key2];
            return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(), children: metricDisplayName(metric2) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$Q.metricValue, children: formatPrettyDecimal(metric2.value) })
            ] }, key2);
          }) })
        ] }, `scorer-${name2}-${idx}`);
      }) });
    };
    const EvalStatus = ({ logHeader }) => {
      var _a2, _b2;
      switch (logHeader == null ? void 0 : logHeader.status) {
        case "error":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(StatusError, { message: "Error" });
        case "cancelled":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(StatusCancelled, { message: "Cancelled" });
        case "started":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(StatusRunning, { message: "Running" });
        default:
          if (((_a2 = logHeader == null ? void 0 : logHeader.results) == null ? void 0 : _a2.scores) && ((_b2 = logHeader.results) == null ? void 0 : _b2.scores.length) > 0) {
            if (logHeader.results.scores.length === 1) {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(SidebarScoreView, { scorer: logHeader.results.scores[0] });
            } else {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(SidebarScoresView, { scores: logHeader.results.scores });
            }
          } else {
            return null;
          }
      }
    };
    const StatusCancelled = ({ message: message2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: clsx(
            "text-style-secondary",
            "text-style-label",
            "text-size-small",
            styles$S.cancelled
          ),
          children: message2
        }
      );
    };
    const StatusRunning = ({ message: message2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: clsx(
            "text-style-secondary",
            "text-style-label",
            "text-size-small",
            styles$S.running
          ),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: message2 })
        }
      );
    };
    const StatusError = ({ message: message2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$S.error, "text-size-small"), children: message2 });
    };
    const entry = "_entry_12m5n_1";
    const title$3 = "_title_12m5n_7";
    const task = "_task_12m5n_12";
    const params = "_params_12m5n_18";
    const scores = "_scores_12m5n_22";
    const styles$P = {
      entry,
      title: title$3,
      task,
      params,
      scores
    };
    const SidebarLogEntry = ({
      logHeader,
      task: task2
    }) => {
      var _a2, _b2, _c, _d, _e2, _f, _g, _h, _i, _j, _k;
      const hyperparameters = {
        ...((_a2 = logHeader == null ? void 0 : logHeader.plan) == null ? void 0 : _a2.config) || {},
        ...((_b2 = logHeader == null ? void 0 : logHeader.eval) == null ? void 0 : _b2.task_args) || {}
      };
      const model2 = (_c = logHeader == null ? void 0 : logHeader.eval) == null ? void 0 : _c.model;
      const datasetName = (_d = logHeader == null ? void 0 : logHeader.eval) == null ? void 0 : _d.dataset.name;
      const uniqScorers = /* @__PURE__ */ new Set();
      (_f = (_e2 = logHeader == null ? void 0 : logHeader.results) == null ? void 0 : _e2.scores) == null ? void 0 : _f.forEach((scorer) => {
        uniqScorers.add(scorer.name);
      });
      const scorerNames = Array.from(uniqScorers).join(",");
      const scorerLabel = Object.keys(((_g = logHeader == null ? void 0 : logHeader.results) == null ? void 0 : _g.scores) || {}).length === 1 ? "scorer" : "scorers";
      const completed = (_h = logHeader == null ? void 0 : logHeader.stats) == null ? void 0 : _h.completed_at;
      const time = completed ? new Date(completed) : void 0;
      const timeStr = time ? `${time.toDateString()}
    ${time.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit"
      })}` : "";
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$P.entry, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$P.title, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$P.task, "text-size-title-secondary"), children: ((_i = logHeader == null ? void 0 : logHeader.eval) == null ? void 0 : _i.task) || task2 }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("small", { className: clsx("mb-1", "text-size-small"), children: timeStr }),
            model2 && model2 !== kModelNone ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("small", { className: clsx("mb-1", "text-size-small"), children: model2 }) }) : ""
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(EvalStatus, { logHeader })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$P.params, "three-line-clamp"), children: /* @__PURE__ */ jsxRuntimeExports.jsx("small", { className: "mb-1", children: hyperparameters ? Object.keys(hyperparameters).map((key2) => {
          const val = hyperparameters[key2];
          if (Array.isArray(val) || typeof val === "object") {
            return `${key2}: ${JSON.stringify(val)}`;
          } else {
            return `${key2}: ${val}`;
          }
        }).join(", ") : "" }) }),
        (((_j = logHeader == null ? void 0 : logHeader.eval) == null ? void 0 : _j.dataset) || ((_k = logHeader == null ? void 0 : logHeader.results) == null ? void 0 : _k.scores)) && (logHeader == null ? void 0 : logHeader.status) === "success" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: clsx("text-truncate", "text-size-small", styles$P.scores),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                "dataset: ",
                datasetName || "(samples)"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("text-truncate", styles$P.scoreInfo), children: [
                scorerLabel,
                ": ",
                scorerNames || "(none)"
              ] })
            ]
          }
        ) : ""
      ] });
    };
    const Sidebar = ({
      logs,
      logHeaders,
      offcanvas,
      setOffcanvas,
      loading,
      selectedIndex,
      onSelectedIndexChanged
    }) => {
      const handleToggle = () => {
        setOffcanvas(!offcanvas);
      };
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        offcanvas && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$T.backdrop, onClick: handleToggle }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: clsx(
              styles$T.sidebar,
              offcanvas ? styles$T.sidebarOpen : styles$T.sidebarClosed
            ),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$T.header, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(LogDirectoryTitleView, { log_dir: logs.log_dir, offcanvas }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    onClick: handleToggle,
                    className: clsx("btn", styles$T.toggle),
                    type: "button",
                    "aria-label": "Close sidebar",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.close })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$T.progress, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ProgressBar, { animating: loading }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: clsx("list-group", styles$T.list), children: logs.files.map((file, index2) => {
                const logHeader = logHeaders[file.name];
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "li",
                  {
                    className: clsx(
                      "list-group-item",
                      "list-group-item-action",
                      styles$T.item,
                      selectedIndex === index2 ? styles$T.active : void 0
                    ),
                    onClick: () => onSelectedIndexChanged(index2),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      SidebarLogEntry,
                      {
                        logHeader,
                        task: file.task || "unknown task"
                      }
                    )
                  },
                  file.name
                );
              }) })
            ]
          }
        )
      ] });
    };
    const ToolButton = React$2.forwardRef(
      ({ label: label2, classes = "", icon, className: className2, ...rest }, ref) => {
        const combinedClasses = `btn btn-tools tool-button ${classes} ${className2 || ""}`.trim();
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("button", { ref, type: "button", className: combinedClasses, ...rest, children: [
          icon && /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: `${icon}` }),
          label2
        ] });
      }
    );
    ToolButton.displayName = "ToolButton";
    const container$9 = "_container_15b4r_1";
    const label$4 = "_label_15b4r_5";
    const styles$O = {
      container: container$9,
      label: label$4
    };
    const EpochFilter = ({
      epochs,
      epoch,
      setEpoch
    }) => {
      const options2 = ["all"];
      for (let i2 = 1; i2 <= epochs; i2++) {
        options2.push(i2 + "");
      }
      const handleEpochChange = (e) => {
        const sel = e.target;
        setEpoch(sel.value);
      };
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$O.container, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: clsx(
              "epoch-filter-label",
              "text-size-smaller",
              "text-style-label",
              "text-style-secondary",
              styles$O.label
            ),
            children: "Epochs:"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "select",
          {
            className: clsx("form-select", "form-select-sm", "text-size-smaller"),
            "aria-label": ".epoch-filter-label",
            value: epoch,
            onChange: handleEpochChange,
            children: options2.map((option) => {
              return /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: option, children: option });
            })
          }
        )
      ] });
    };
    let rangeFrom = [], rangeTo = [];
    (() => {
      let numbers = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((s) => s ? parseInt(s, 36) : 1);
      for (let i2 = 0, n = 0; i2 < numbers.length; i2++)
        (i2 % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i2]);
    })();
    function isExtendingChar(code2) {
      if (code2 < 768) return false;
      for (let from = 0, to2 = rangeFrom.length; ; ) {
        let mid = from + to2 >> 1;
        if (code2 < rangeFrom[mid]) to2 = mid;
        else if (code2 >= rangeTo[mid]) from = mid + 1;
        else return true;
        if (from == to2) return false;
      }
    }
    function isRegionalIndicator(code2) {
      return code2 >= 127462 && code2 <= 127487;
    }
    const ZWJ = 8205;
    function findClusterBreak$1(str2, pos2, forward = true, includeExtending = true) {
      return (forward ? nextClusterBreak : prevClusterBreak)(str2, pos2, includeExtending);
    }
    function nextClusterBreak(str2, pos2, includeExtending) {
      if (pos2 == str2.length) return pos2;
      if (pos2 && surrogateLow$1(str2.charCodeAt(pos2)) && surrogateHigh$1(str2.charCodeAt(pos2 - 1))) pos2--;
      let prev = codePointAt$1(str2, pos2);
      pos2 += codePointSize$1(prev);
      while (pos2 < str2.length) {
        let next = codePointAt$1(str2, pos2);
        if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
          pos2 += codePointSize$1(next);
          prev = next;
        } else if (isRegionalIndicator(next)) {
          let countBefore = 0, i2 = pos2 - 2;
          while (i2 >= 0 && isRegionalIndicator(codePointAt$1(str2, i2))) {
            countBefore++;
            i2 -= 2;
          }
          if (countBefore % 2 == 0) break;
          else pos2 += 2;
        } else {
          break;
        }
      }
      return pos2;
    }
    function prevClusterBreak(str2, pos2, includeExtending) {
      while (pos2 > 0) {
        let found = nextClusterBreak(str2, pos2 - 2, includeExtending);
        if (found < pos2) return found;
        pos2--;
      }
      return 0;
    }
    function codePointAt$1(str2, pos2) {
      let code0 = str2.charCodeAt(pos2);
      if (!surrogateHigh$1(code0) || pos2 + 1 == str2.length) return code0;
      let code1 = str2.charCodeAt(pos2 + 1);
      if (!surrogateLow$1(code1)) return code0;
      return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
    }
    function surrogateLow$1(ch3) {
      return ch3 >= 56320 && ch3 < 57344;
    }
    function surrogateHigh$1(ch3) {
      return ch3 >= 55296 && ch3 < 56320;
    }
    function codePointSize$1(code2) {
      return code2 < 65536 ? 1 : 2;
    }
    class Text {
      /**
      Get the line description around the given position.
      */
      lineAt(pos2) {
        if (pos2 < 0 || pos2 > this.length)
          throw new RangeError(`Invalid position ${pos2} in document of length ${this.length}`);
        return this.lineInner(pos2, false, 1, 0);
      }
      /**
      Get the description for the given (1-based) line number.
      */
      line(n) {
        if (n < 1 || n > this.lines)
          throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
        return this.lineInner(n, true, 1, 0);
      }
      /**
      Replace a range of the text with the given content.
      */
      replace(from, to2, text2) {
        [from, to2] = clip(this, from, to2);
        let parts = [];
        this.decompose(
          0,
          from,
          parts,
          2
          /* Open.To */
        );
        if (text2.length)
          text2.decompose(
            0,
            text2.length,
            parts,
            1 | 2
            /* Open.To */
          );
        this.decompose(
          to2,
          this.length,
          parts,
          1
          /* Open.From */
        );
        return TextNode.from(parts, this.length - (to2 - from) + text2.length);
      }
      /**
      Append another document to this one.
      */
      append(other) {
        return this.replace(this.length, this.length, other);
      }
      /**
      Retrieve the text between the given points.
      */
      slice(from, to2 = this.length) {
        [from, to2] = clip(this, from, to2);
        let parts = [];
        this.decompose(from, to2, parts, 0);
        return TextNode.from(parts, to2 - from);
      }
      /**
      Test whether this text is equal to another instance.
      */
      eq(other) {
        if (other == this)
          return true;
        if (other.length != this.length || other.lines != this.lines)
          return false;
        let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
        let a = new RawTextCursor(this), b = new RawTextCursor(other);
        for (let skip = start, pos2 = start; ; ) {
          a.next(skip);
          b.next(skip);
          skip = 0;
          if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
            return false;
          pos2 += a.value.length;
          if (a.done || pos2 >= end)
            return true;
        }
      }
      /**
      Iterate over the text. When `dir` is `-1`, iteration happens
      from end to start. This will return lines and the breaks between
      them as separate strings.
      */
      iter(dir = 1) {
        return new RawTextCursor(this, dir);
      }
      /**
      Iterate over a range of the text. When `from` > `to`, the
      iterator will run in reverse.
      */
      iterRange(from, to2 = this.length) {
        return new PartialTextCursor(this, from, to2);
      }
      /**
      Return a cursor that iterates over the given range of lines,
      _without_ returning the line breaks between, and yielding empty
      strings for empty lines.
      
      When `from` and `to` are given, they should be 1-based line numbers.
      */
      iterLines(from, to2) {
        let inner;
        if (from == null) {
          inner = this.iter();
        } else {
          if (to2 == null)
            to2 = this.lines + 1;
          let start = this.line(from).from;
          inner = this.iterRange(start, Math.max(start, to2 == this.lines + 1 ? this.length : to2 <= 1 ? 0 : this.line(to2 - 1).to));
        }
        return new LineCursor(inner);
      }
      /**
      Return the document as a string, using newline characters to
      separate lines.
      */
      toString() {
        return this.sliceString(0);
      }
      /**
      Convert the document to an array of lines (which can be
      deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
      */
      toJSON() {
        let lines = [];
        this.flatten(lines);
        return lines;
      }
      /**
      @internal
      */
      constructor() {
      }
      /**
      Create a `Text` instance for the given array of lines.
      */
      static of(text2) {
        if (text2.length == 0)
          throw new RangeError("A document must have at least one line");
        if (text2.length == 1 && !text2[0])
          return Text.empty;
        return text2.length <= 32 ? new TextLeaf(text2) : TextNode.from(TextLeaf.split(text2, []));
      }
    }
    class TextLeaf extends Text {
      constructor(text2, length = textLength(text2)) {
        super();
        this.text = text2;
        this.length = length;
      }
      get lines() {
        return this.text.length;
      }
      get children() {
        return null;
      }
      lineInner(target2, isLine, line2, offset) {
        for (let i2 = 0; ; i2++) {
          let string2 = this.text[i2], end = offset + string2.length;
          if ((isLine ? line2 : end) >= target2)
            return new Line$1(offset, end, line2, string2);
          offset = end + 1;
          line2++;
        }
      }
      decompose(from, to2, target2, open) {
        let text2 = from <= 0 && to2 >= this.length ? this : new TextLeaf(sliceText(this.text, from, to2), Math.min(to2, this.length) - Math.max(0, from));
        if (open & 1) {
          let prev = target2.pop();
          let joined = appendText(text2.text, prev.text.slice(), 0, text2.length);
          if (joined.length <= 32) {
            target2.push(new TextLeaf(joined, prev.length + text2.length));
          } else {
            let mid = joined.length >> 1;
            target2.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
          }
        } else {
          target2.push(text2);
        }
      }
      replace(from, to2, text2) {
        if (!(text2 instanceof TextLeaf))
          return super.replace(from, to2, text2);
        [from, to2] = clip(this, from, to2);
        let lines = appendText(this.text, appendText(text2.text, sliceText(this.text, 0, from)), to2);
        let newLen = this.length + text2.length - (to2 - from);
        if (lines.length <= 32)
          return new TextLeaf(lines, newLen);
        return TextNode.from(TextLeaf.split(lines, []), newLen);
      }
      sliceString(from, to2 = this.length, lineSep = "\n") {
        [from, to2] = clip(this, from, to2);
        let result2 = "";
        for (let pos2 = 0, i2 = 0; pos2 <= to2 && i2 < this.text.length; i2++) {
          let line2 = this.text[i2], end = pos2 + line2.length;
          if (pos2 > from && i2)
            result2 += lineSep;
          if (from < end && to2 > pos2)
            result2 += line2.slice(Math.max(0, from - pos2), to2 - pos2);
          pos2 = end + 1;
        }
        return result2;
      }
      flatten(target2) {
        for (let line2 of this.text)
          target2.push(line2);
      }
      scanIdentical() {
        return 0;
      }
      static split(text2, target2) {
        let part = [], len = -1;
        for (let line2 of text2) {
          part.push(line2);
          len += line2.length + 1;
          if (part.length == 32) {
            target2.push(new TextLeaf(part, len));
            part = [];
            len = -1;
          }
        }
        if (len > -1)
          target2.push(new TextLeaf(part, len));
        return target2;
      }
    }
    class TextNode extends Text {
      constructor(children2, length) {
        super();
        this.children = children2;
        this.length = length;
        this.lines = 0;
        for (let child of children2)
          this.lines += child.lines;
      }
      lineInner(target2, isLine, line2, offset) {
        for (let i2 = 0; ; i2++) {
          let child = this.children[i2], end = offset + child.length, endLine = line2 + child.lines - 1;
          if ((isLine ? endLine : end) >= target2)
            return child.lineInner(target2, isLine, line2, offset);
          offset = end + 1;
          line2 = endLine + 1;
        }
      }
      decompose(from, to2, target2, open) {
        for (let i2 = 0, pos2 = 0; pos2 <= to2 && i2 < this.children.length; i2++) {
          let child = this.children[i2], end = pos2 + child.length;
          if (from <= end && to2 >= pos2) {
            let childOpen = open & ((pos2 <= from ? 1 : 0) | (end >= to2 ? 2 : 0));
            if (pos2 >= from && end <= to2 && !childOpen)
              target2.push(child);
            else
              child.decompose(from - pos2, to2 - pos2, target2, childOpen);
          }
          pos2 = end + 1;
        }
      }
      replace(from, to2, text2) {
        [from, to2] = clip(this, from, to2);
        if (text2.lines < this.lines)
          for (let i2 = 0, pos2 = 0; i2 < this.children.length; i2++) {
            let child = this.children[i2], end = pos2 + child.length;
            if (from >= pos2 && to2 <= end) {
              let updated = child.replace(from - pos2, to2 - pos2, text2);
              let totalLines = this.lines - child.lines + updated.lines;
              if (updated.lines < totalLines >> 5 - 1 && updated.lines > totalLines >> 5 + 1) {
                let copy = this.children.slice();
                copy[i2] = updated;
                return new TextNode(copy, this.length - (to2 - from) + text2.length);
              }
              return super.replace(pos2, end, updated);
            }
            pos2 = end + 1;
          }
        return super.replace(from, to2, text2);
      }
      sliceString(from, to2 = this.length, lineSep = "\n") {
        [from, to2] = clip(this, from, to2);
        let result2 = "";
        for (let i2 = 0, pos2 = 0; i2 < this.children.length && pos2 <= to2; i2++) {
          let child = this.children[i2], end = pos2 + child.length;
          if (pos2 > from && i2)
            result2 += lineSep;
          if (from < end && to2 > pos2)
            result2 += child.sliceString(from - pos2, to2 - pos2, lineSep);
          pos2 = end + 1;
        }
        return result2;
      }
      flatten(target2) {
        for (let child of this.children)
          child.flatten(target2);
      }
      scanIdentical(other, dir) {
        if (!(other instanceof TextNode))
          return 0;
        let length = 0;
        let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1];
        for (; ; iA += dir, iB += dir) {
          if (iA == eA || iB == eB)
            return length;
          let chA = this.children[iA], chB = other.children[iB];
          if (chA != chB)
            return length + chA.scanIdentical(chB, dir);
          length += chA.length + 1;
        }
      }
      static from(children2, length = children2.reduce((l, ch3) => l + ch3.length + 1, -1)) {
        let lines = 0;
        for (let ch3 of children2)
          lines += ch3.lines;
        if (lines < 32) {
          let flat = [];
          for (let ch3 of children2)
            ch3.flatten(flat);
          return new TextLeaf(flat, length);
        }
        let chunk = Math.max(
          32,
          lines >> 5
          /* Tree.BranchShift */
        ), maxChunk = chunk << 1, minChunk = chunk >> 1;
        let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
        function add2(child) {
          let last;
          if (child.lines > maxChunk && child instanceof TextNode) {
            for (let node2 of child.children)
              add2(node2);
          } else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
            flush();
            chunked.push(child);
          } else if (child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= 32) {
            currentLines += child.lines;
            currentLen += child.length + 1;
            currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
          } else {
            if (currentLines + child.lines > chunk)
              flush();
            currentLines += child.lines;
            currentLen += child.length + 1;
            currentChunk.push(child);
          }
        }
        function flush() {
          if (currentLines == 0)
            return;
          chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
          currentLen = -1;
          currentLines = currentChunk.length = 0;
        }
        for (let child of children2)
          add2(child);
        flush();
        return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
      }
    }
    Text.empty = /* @__PURE__ */ new TextLeaf([""], 0);
    function textLength(text2) {
      let length = -1;
      for (let line2 of text2)
        length += line2.length + 1;
      return length;
    }
    function appendText(text2, target2, from = 0, to2 = 1e9) {
      for (let pos2 = 0, i2 = 0, first2 = true; i2 < text2.length && pos2 <= to2; i2++) {
        let line2 = text2[i2], end = pos2 + line2.length;
        if (end >= from) {
          if (end > to2)
            line2 = line2.slice(0, to2 - pos2);
          if (pos2 < from)
            line2 = line2.slice(from - pos2);
          if (first2) {
            target2[target2.length - 1] += line2;
            first2 = false;
          } else
            target2.push(line2);
        }
        pos2 = end + 1;
      }
      return target2;
    }
    function sliceText(text2, from, to2) {
      return appendText(text2, [""], from, to2);
    }
    class RawTextCursor {
      constructor(text2, dir = 1) {
        this.dir = dir;
        this.done = false;
        this.lineBreak = false;
        this.value = "";
        this.nodes = [text2];
        this.offsets = [dir > 0 ? 1 : (text2 instanceof TextLeaf ? text2.text.length : text2.children.length) << 1];
      }
      nextInner(skip, dir) {
        this.done = this.lineBreak = false;
        for (; ; ) {
          let last = this.nodes.length - 1;
          let top2 = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
          let size = top2 instanceof TextLeaf ? top2.text.length : top2.children.length;
          if (offset == (dir > 0 ? size : 0)) {
            if (last == 0) {
              this.done = true;
              this.value = "";
              return this;
            }
            if (dir > 0)
              this.offsets[last - 1]++;
            this.nodes.pop();
            this.offsets.pop();
          } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
            this.offsets[last] += dir;
            if (skip == 0) {
              this.lineBreak = true;
              this.value = "\n";
              return this;
            }
            skip--;
          } else if (top2 instanceof TextLeaf) {
            let next = top2.text[offset + (dir < 0 ? -1 : 0)];
            this.offsets[last] += dir;
            if (next.length > Math.max(0, skip)) {
              this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
              return this;
            }
            skip -= next.length;
          } else {
            let next = top2.children[offset + (dir < 0 ? -1 : 0)];
            if (skip > next.length) {
              skip -= next.length;
              this.offsets[last] += dir;
            } else {
              if (dir < 0)
                this.offsets[last]--;
              this.nodes.push(next);
              this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
            }
          }
        }
      }
      next(skip = 0) {
        if (skip < 0) {
          this.nextInner(-skip, -this.dir);
          skip = this.value.length;
        }
        return this.nextInner(skip, this.dir);
      }
    }
    class PartialTextCursor {
      constructor(text2, start, end) {
        this.value = "";
        this.done = false;
        this.cursor = new RawTextCursor(text2, start > end ? -1 : 1);
        this.pos = start > end ? text2.length : 0;
        this.from = Math.min(start, end);
        this.to = Math.max(start, end);
      }
      nextInner(skip, dir) {
        if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
          this.value = "";
          this.done = true;
          return this;
        }
        skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
        let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
        if (skip > limit)
          skip = limit;
        limit -= skip;
        let { value: value2 } = this.cursor.next(skip);
        this.pos += (value2.length + skip) * dir;
        this.value = value2.length <= limit ? value2 : dir < 0 ? value2.slice(value2.length - limit) : value2.slice(0, limit);
        this.done = !this.value;
        return this;
      }
      next(skip = 0) {
        if (skip < 0)
          skip = Math.max(skip, this.from - this.pos);
        else if (skip > 0)
          skip = Math.min(skip, this.to - this.pos);
        return this.nextInner(skip, this.cursor.dir);
      }
      get lineBreak() {
        return this.cursor.lineBreak && this.value != "";
      }
    }
    class LineCursor {
      constructor(inner) {
        this.inner = inner;
        this.afterBreak = true;
        this.value = "";
        this.done = false;
      }
      next(skip = 0) {
        let { done, lineBreak, value: value2 } = this.inner.next(skip);
        if (done && this.afterBreak) {
          this.value = "";
          this.afterBreak = false;
        } else if (done) {
          this.done = true;
          this.value = "";
        } else if (lineBreak) {
          if (this.afterBreak) {
            this.value = "";
          } else {
            this.afterBreak = true;
            this.next();
          }
        } else {
          this.value = value2;
          this.afterBreak = false;
        }
        return this;
      }
      get lineBreak() {
        return false;
      }
    }
    if (typeof Symbol != "undefined") {
      Text.prototype[Symbol.iterator] = function() {
        return this.iter();
      };
      RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function() {
        return this;
      };
    }
    let Line$1 = class Line {
      /**
      @internal
      */
      constructor(from, to2, number2, text2) {
        this.from = from;
        this.to = to2;
        this.number = number2;
        this.text = text2;
      }
      /**
      The length of the line (not including any line break after it).
      */
      get length() {
        return this.to - this.from;
      }
    };
    function clip(text2, from, to2) {
      from = Math.max(0, Math.min(text2.length, from));
      return [from, Math.max(from, Math.min(text2.length, to2))];
    }
    function findClusterBreak(str2, pos2, forward = true, includeExtending = true) {
      return findClusterBreak$1(str2, pos2, forward, includeExtending);
    }
    function surrogateLow(ch3) {
      return ch3 >= 56320 && ch3 < 57344;
    }
    function surrogateHigh(ch3) {
      return ch3 >= 55296 && ch3 < 56320;
    }
    function codePointAt(str2, pos2) {
      let code0 = str2.charCodeAt(pos2);
      if (!surrogateHigh(code0) || pos2 + 1 == str2.length)
        return code0;
      let code1 = str2.charCodeAt(pos2 + 1);
      if (!surrogateLow(code1))
        return code0;
      return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
    }
    function fromCodePoint(code2) {
      if (code2 <= 65535)
        return String.fromCharCode(code2);
      code2 -= 65536;
      return String.fromCharCode((code2 >> 10) + 55296, (code2 & 1023) + 56320);
    }
    function codePointSize(code2) {
      return code2 < 65536 ? 1 : 2;
    }
    const DefaultSplit = /\r\n?|\n/;
    var MapMode = /* @__PURE__ */ function(MapMode2) {
      MapMode2[MapMode2["Simple"] = 0] = "Simple";
      MapMode2[MapMode2["TrackDel"] = 1] = "TrackDel";
      MapMode2[MapMode2["TrackBefore"] = 2] = "TrackBefore";
      MapMode2[MapMode2["TrackAfter"] = 3] = "TrackAfter";
      return MapMode2;
    }(MapMode || (MapMode = {}));
    class ChangeDesc {
      // Sections are encoded as pairs of integers. The first is the
      // length in the current document, and the second is -1 for
      // unaffected sections, and the length of the replacement content
      // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
      // 0), and a replacement two positive numbers.
      /**
      @internal
      */
      constructor(sections) {
        this.sections = sections;
      }
      /**
      The length of the document before the change.
      */
      get length() {
        let result2 = 0;
        for (let i2 = 0; i2 < this.sections.length; i2 += 2)
          result2 += this.sections[i2];
        return result2;
      }
      /**
      The length of the document after the change.
      */
      get newLength() {
        let result2 = 0;
        for (let i2 = 0; i2 < this.sections.length; i2 += 2) {
          let ins = this.sections[i2 + 1];
          result2 += ins < 0 ? this.sections[i2] : ins;
        }
        return result2;
      }
      /**
      False when there are actual changes in this set.
      */
      get empty() {
        return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
      }
      /**
      Iterate over the unchanged parts left by these changes. `posA`
      provides the position of the range in the old document, `posB`
      the new position in the changed document.
      */
      iterGaps(f) {
        for (let i2 = 0, posA = 0, posB = 0; i2 < this.sections.length; ) {
          let len = this.sections[i2++], ins = this.sections[i2++];
          if (ins < 0) {
            f(posA, posB, len);
            posB += len;
          } else {
            posB += ins;
          }
          posA += len;
        }
      }
      /**
      Iterate over the ranges changed by these changes. (See
      [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
      variant that also provides you with the inserted text.)
      `fromA`/`toA` provides the extent of the change in the starting
      document, `fromB`/`toB` the extent of the replacement in the
      changed document.
      
      When `individual` is true, adjacent changes (which are kept
      separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
      reported separately.
      */
      iterChangedRanges(f, individual = false) {
        iterChanges(this, f, individual);
      }
      /**
      Get a description of the inverted form of these changes.
      */
      get invertedDesc() {
        let sections = [];
        for (let i2 = 0; i2 < this.sections.length; ) {
          let len = this.sections[i2++], ins = this.sections[i2++];
          if (ins < 0)
            sections.push(len, ins);
          else
            sections.push(ins, len);
        }
        return new ChangeDesc(sections);
      }
      /**
      Compute the combined effect of applying another set of changes
      after this one. The length of the document after this set should
      match the length before `other`.
      */
      composeDesc(other) {
        return this.empty ? other : other.empty ? this : composeSets(this, other);
      }
      /**
      Map this description, which should start with the same document
      as `other`, over another set of changes, so that it can be
      applied after it. When `before` is true, map as if the changes
      in `this` happened before the ones in `other`.
      */
      mapDesc(other, before = false) {
        return other.empty ? this : mapSet(this, other, before);
      }
      mapPos(pos2, assoc = -1, mode = MapMode.Simple) {
        let posA = 0, posB = 0;
        for (let i2 = 0; i2 < this.sections.length; ) {
          let len = this.sections[i2++], ins = this.sections[i2++], endA = posA + len;
          if (ins < 0) {
            if (endA > pos2)
              return posB + (pos2 - posA);
            posB += len;
          } else {
            if (mode != MapMode.Simple && endA >= pos2 && (mode == MapMode.TrackDel && posA < pos2 && endA > pos2 || mode == MapMode.TrackBefore && posA < pos2 || mode == MapMode.TrackAfter && endA > pos2))
              return null;
            if (endA > pos2 || endA == pos2 && assoc < 0 && !len)
              return pos2 == posA || assoc < 0 ? posB : posB + ins;
            posB += ins;
          }
          posA = endA;
        }
        if (pos2 > posA)
          throw new RangeError(`Position ${pos2} is out of range for changeset of length ${posA}`);
        return posB;
      }
      /**
      Check whether these changes touch a given range. When one of the
      changes entirely covers the range, the string `"cover"` is
      returned.
      */
      touchesRange(from, to2 = from) {
        for (let i2 = 0, pos2 = 0; i2 < this.sections.length && pos2 <= to2; ) {
          let len = this.sections[i2++], ins = this.sections[i2++], end = pos2 + len;
          if (ins >= 0 && pos2 <= to2 && end >= from)
            return pos2 < from && end > to2 ? "cover" : true;
          pos2 = end;
        }
        return false;
      }
      /**
      @internal
      */
      toString() {
        let result2 = "";
        for (let i2 = 0; i2 < this.sections.length; ) {
          let len = this.sections[i2++], ins = this.sections[i2++];
          result2 += (result2 ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
        }
        return result2;
      }
      /**
      Serialize this change desc to a JSON-representable value.
      */
      toJSON() {
        return this.sections;
      }
      /**
      Create a change desc from its JSON representation (as produced
      by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
      */
      static fromJSON(json) {
        if (!Array.isArray(json) || json.length % 2 || json.some((a) => typeof a != "number"))
          throw new RangeError("Invalid JSON representation of ChangeDesc");
        return new ChangeDesc(json);
      }
      /**
      @internal
      */
      static create(sections) {
        return new ChangeDesc(sections);
      }
    }
    class ChangeSet extends ChangeDesc {
      constructor(sections, inserted) {
        super(sections);
        this.inserted = inserted;
      }
      /**
      Apply the changes to a document, returning the modified
      document.
      */
      apply(doc2) {
        if (this.length != doc2.length)
          throw new RangeError("Applying change set to a document with the wrong length");
        iterChanges(this, (fromA, toA, fromB, _toB, text2) => doc2 = doc2.replace(fromB, fromB + (toA - fromA), text2), false);
        return doc2;
      }
      mapDesc(other, before = false) {
        return mapSet(this, other, before, true);
      }
      /**
      Given the document as it existed _before_ the changes, return a
      change set that represents the inverse of this set, which could
      be used to go from the document created by the changes back to
      the document as it existed before the changes.
      */
      invert(doc2) {
        let sections = this.sections.slice(), inserted = [];
        for (let i2 = 0, pos2 = 0; i2 < sections.length; i2 += 2) {
          let len = sections[i2], ins = sections[i2 + 1];
          if (ins >= 0) {
            sections[i2] = ins;
            sections[i2 + 1] = len;
            let index2 = i2 >> 1;
            while (inserted.length < index2)
              inserted.push(Text.empty);
            inserted.push(len ? doc2.slice(pos2, pos2 + len) : Text.empty);
          }
          pos2 += len;
        }
        return new ChangeSet(sections, inserted);
      }
      /**
      Combine two subsequent change sets into a single set. `other`
      must start in the document produced by `this`. If `this` goes
      `docA` → `docB` and `other` represents `docB` → `docC`, the
      returned value will represent the change `docA` → `docC`.
      */
      compose(other) {
        return this.empty ? other : other.empty ? this : composeSets(this, other, true);
      }
      /**
      Given another change set starting in the same document, maps this
      change set over the other, producing a new change set that can be
      applied to the document produced by applying `other`. When
      `before` is `true`, order changes as if `this` comes before
      `other`, otherwise (the default) treat `other` as coming first.
      
      Given two changes `A` and `B`, `A.compose(B.map(A))` and
      `B.compose(A.map(B, true))` will produce the same document. This
      provides a basic form of [operational
      transformation](https://en.wikipedia.org/wiki/Operational_transformation),
      and can be used for collaborative editing.
      */
      map(other, before = false) {
        return other.empty ? this : mapSet(this, other, before, true);
      }
      /**
      Iterate over the changed ranges in the document, calling `f` for
      each, with the range in the original document (`fromA`-`toA`)
      and the range that replaces it in the new document
      (`fromB`-`toB`).
      
      When `individual` is true, adjacent changes are reported
      separately.
      */
      iterChanges(f, individual = false) {
        iterChanges(this, f, individual);
      }
      /**
      Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
      set.
      */
      get desc() {
        return ChangeDesc.create(this.sections);
      }
      /**
      @internal
      */
      filter(ranges) {
        let resultSections = [], resultInserted = [], filteredSections = [];
        let iter = new SectionIter(this);
        done: for (let i2 = 0, pos2 = 0; ; ) {
          let next = i2 == ranges.length ? 1e9 : ranges[i2++];
          while (pos2 < next || pos2 == next && iter.len == 0) {
            if (iter.done)
              break done;
            let len = Math.min(iter.len, next - pos2);
            addSection(filteredSections, len, -1);
            let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
            addSection(resultSections, len, ins);
            if (ins > 0)
              addInsert(resultInserted, resultSections, iter.text);
            iter.forward(len);
            pos2 += len;
          }
          let end = ranges[i2++];
          while (pos2 < end) {
            if (iter.done)
              break done;
            let len = Math.min(iter.len, end - pos2);
            addSection(resultSections, len, -1);
            addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
            iter.forward(len);
            pos2 += len;
          }
        }
        return {
          changes: new ChangeSet(resultSections, resultInserted),
          filtered: ChangeDesc.create(filteredSections)
        };
      }
      /**
      Serialize this change set to a JSON-representable value.
      */
      toJSON() {
        let parts = [];
        for (let i2 = 0; i2 < this.sections.length; i2 += 2) {
          let len = this.sections[i2], ins = this.sections[i2 + 1];
          if (ins < 0)
            parts.push(len);
          else if (ins == 0)
            parts.push([len]);
          else
            parts.push([len].concat(this.inserted[i2 >> 1].toJSON()));
        }
        return parts;
      }
      /**
      Create a change set for the given changes, for a document of the
      given length, using `lineSep` as line separator.
      */
      static of(changes, length, lineSep) {
        let sections = [], inserted = [], pos2 = 0;
        let total = null;
        function flush(force = false) {
          if (!force && !sections.length)
            return;
          if (pos2 < length)
            addSection(sections, length - pos2, -1);
          let set = new ChangeSet(sections, inserted);
          total = total ? total.compose(set.map(total)) : set;
          sections = [];
          inserted = [];
          pos2 = 0;
        }
        function process2(spec) {
          if (Array.isArray(spec)) {
            for (let sub of spec)
              process2(sub);
          } else if (spec instanceof ChangeSet) {
            if (spec.length != length)
              throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
            flush();
            total = total ? total.compose(spec.map(total)) : spec;
          } else {
            let { from, to: to2 = from, insert: insert2 } = spec;
            if (from > to2 || from < 0 || to2 > length)
              throw new RangeError(`Invalid change range ${from} to ${to2} (in doc of length ${length})`);
            let insText = !insert2 ? Text.empty : typeof insert2 == "string" ? Text.of(insert2.split(lineSep || DefaultSplit)) : insert2;
            let insLen = insText.length;
            if (from == to2 && insLen == 0)
              return;
            if (from < pos2)
              flush();
            if (from > pos2)
              addSection(sections, from - pos2, -1);
            addSection(sections, to2 - from, insLen);
            addInsert(inserted, sections, insText);
            pos2 = to2;
          }
        }
        process2(changes);
        flush(!total);
        return total;
      }
      /**
      Create an empty changeset of the given length.
      */
      static empty(length) {
        return new ChangeSet(length ? [length, -1] : [], []);
      }
      /**
      Create a changeset from its JSON representation (as produced by
      [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
      */
      static fromJSON(json) {
        if (!Array.isArray(json))
          throw new RangeError("Invalid JSON representation of ChangeSet");
        let sections = [], inserted = [];
        for (let i2 = 0; i2 < json.length; i2++) {
          let part = json[i2];
          if (typeof part == "number") {
            sections.push(part, -1);
          } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i3) => i3 && typeof e != "string")) {
            throw new RangeError("Invalid JSON representation of ChangeSet");
          } else if (part.length == 1) {
            sections.push(part[0], 0);
          } else {
            while (inserted.length < i2)
              inserted.push(Text.empty);
            inserted[i2] = Text.of(part.slice(1));
            sections.push(part[0], inserted[i2].length);
          }
        }
        return new ChangeSet(sections, inserted);
      }
      /**
      @internal
      */
      static createSet(sections, inserted) {
        return new ChangeSet(sections, inserted);
      }
    }
    function addSection(sections, len, ins, forceJoin = false) {
      if (len == 0 && ins <= 0)
        return;
      let last = sections.length - 2;
      if (last >= 0 && ins <= 0 && ins == sections[last + 1])
        sections[last] += len;
      else if (last >= 0 && len == 0 && sections[last] == 0)
        sections[last + 1] += ins;
      else if (forceJoin) {
        sections[last] += len;
        sections[last + 1] += ins;
      } else
        sections.push(len, ins);
    }
    function addInsert(values, sections, value2) {
      if (value2.length == 0)
        return;
      let index2 = sections.length - 2 >> 1;
      if (index2 < values.length) {
        values[values.length - 1] = values[values.length - 1].append(value2);
      } else {
        while (values.length < index2)
          values.push(Text.empty);
        values.push(value2);
      }
    }
    function iterChanges(desc, f, individual) {
      let inserted = desc.inserted;
      for (let posA = 0, posB = 0, i2 = 0; i2 < desc.sections.length; ) {
        let len = desc.sections[i2++], ins = desc.sections[i2++];
        if (ins < 0) {
          posA += len;
          posB += len;
        } else {
          let endA = posA, endB = posB, text2 = Text.empty;
          for (; ; ) {
            endA += len;
            endB += ins;
            if (ins && inserted)
              text2 = text2.append(inserted[i2 - 2 >> 1]);
            if (individual || i2 == desc.sections.length || desc.sections[i2 + 1] < 0)
              break;
            len = desc.sections[i2++];
            ins = desc.sections[i2++];
          }
          f(posA, endA, posB, endB, text2);
          posA = endA;
          posB = endB;
        }
      }
    }
    function mapSet(setA, setB, before, mkSet = false) {
      let sections = [], insert2 = mkSet ? [] : null;
      let a = new SectionIter(setA), b = new SectionIter(setB);
      for (let inserted = -1; ; ) {
        if (a.done && b.len || b.done && a.len) {
          throw new Error("Mismatched change set lengths");
        } else if (a.ins == -1 && b.ins == -1) {
          let len = Math.min(a.len, b.len);
          addSection(sections, len, -1);
          a.forward(len);
          b.forward(len);
        } else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
          let len = b.len;
          addSection(sections, b.ins, -1);
          while (len) {
            let piece = Math.min(a.len, len);
            if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
              addSection(sections, 0, a.ins);
              if (insert2)
                addInsert(insert2, sections, a.text);
              inserted = a.i;
            }
            a.forward(piece);
            len -= piece;
          }
          b.next();
        } else if (a.ins >= 0) {
          let len = 0, left = a.len;
          while (left) {
            if (b.ins == -1) {
              let piece = Math.min(left, b.len);
              len += piece;
              left -= piece;
              b.forward(piece);
            } else if (b.ins == 0 && b.len < left) {
              left -= b.len;
              b.next();
            } else {
              break;
            }
          }
          addSection(sections, len, inserted < a.i ? a.ins : 0);
          if (insert2 && inserted < a.i)
            addInsert(insert2, sections, a.text);
          inserted = a.i;
          a.forward(a.len - left);
        } else if (a.done && b.done) {
          return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections);
        } else {
          throw new Error("Mismatched change set lengths");
        }
      }
    }
    function composeSets(setA, setB, mkSet = false) {
      let sections = [];
      let insert2 = mkSet ? [] : null;
      let a = new SectionIter(setA), b = new SectionIter(setB);
      for (let open = false; ; ) {
        if (a.done && b.done) {
          return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections);
        } else if (a.ins == 0) {
          addSection(sections, a.len, 0, open);
          a.next();
        } else if (b.len == 0 && !b.done) {
          addSection(sections, 0, b.ins, open);
          if (insert2)
            addInsert(insert2, sections, b.text);
          b.next();
        } else if (a.done || b.done) {
          throw new Error("Mismatched change set lengths");
        } else {
          let len = Math.min(a.len2, b.len), sectionLen = sections.length;
          if (a.ins == -1) {
            let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
            addSection(sections, len, insB, open);
            if (insert2 && insB)
              addInsert(insert2, sections, b.text);
          } else if (b.ins == -1) {
            addSection(sections, a.off ? 0 : a.len, len, open);
            if (insert2)
              addInsert(insert2, sections, a.textBit(len));
          } else {
            addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
            if (insert2 && !b.off)
              addInsert(insert2, sections, b.text);
          }
          open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
          a.forward2(len);
          b.forward(len);
        }
      }
    }
    class SectionIter {
      constructor(set) {
        this.set = set;
        this.i = 0;
        this.next();
      }
      next() {
        let { sections } = this.set;
        if (this.i < sections.length) {
          this.len = sections[this.i++];
          this.ins = sections[this.i++];
        } else {
          this.len = 0;
          this.ins = -2;
        }
        this.off = 0;
      }
      get done() {
        return this.ins == -2;
      }
      get len2() {
        return this.ins < 0 ? this.len : this.ins;
      }
      get text() {
        let { inserted } = this.set, index2 = this.i - 2 >> 1;
        return index2 >= inserted.length ? Text.empty : inserted[index2];
      }
      textBit(len) {
        let { inserted } = this.set, index2 = this.i - 2 >> 1;
        return index2 >= inserted.length && !len ? Text.empty : inserted[index2].slice(this.off, len == null ? void 0 : this.off + len);
      }
      forward(len) {
        if (len == this.len)
          this.next();
        else {
          this.len -= len;
          this.off += len;
        }
      }
      forward2(len) {
        if (this.ins == -1)
          this.forward(len);
        else if (len == this.ins)
          this.next();
        else {
          this.ins -= len;
          this.off += len;
        }
      }
    }
    class SelectionRange {
      constructor(from, to2, flags) {
        this.from = from;
        this.to = to2;
        this.flags = flags;
      }
      /**
      The anchor of the range—the side that doesn't move when you
      extend it.
      */
      get anchor() {
        return this.flags & 32 ? this.to : this.from;
      }
      /**
      The head of the range, which is moved when the range is
      [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
      */
      get head() {
        return this.flags & 32 ? this.from : this.to;
      }
      /**
      True when `anchor` and `head` are at the same position.
      */
      get empty() {
        return this.from == this.to;
      }
      /**
      If this is a cursor that is explicitly associated with the
      character on one of its sides, this returns the side. -1 means
      the character before its position, 1 the character after, and 0
      means no association.
      */
      get assoc() {
        return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0;
      }
      /**
      The bidirectional text level associated with this cursor, if
      any.
      */
      get bidiLevel() {
        let level = this.flags & 7;
        return level == 7 ? null : level;
      }
      /**
      The goal column (stored vertical offset) associated with a
      cursor. This is used to preserve the vertical position when
      [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
      lines of different length.
      */
      get goalColumn() {
        let value2 = this.flags >> 6;
        return value2 == 16777215 ? void 0 : value2;
      }
      /**
      Map this range through a change, producing a valid range in the
      updated document.
      */
      map(change, assoc = -1) {
        let from, to2;
        if (this.empty) {
          from = to2 = change.mapPos(this.from, assoc);
        } else {
          from = change.mapPos(this.from, 1);
          to2 = change.mapPos(this.to, -1);
        }
        return from == this.from && to2 == this.to ? this : new SelectionRange(from, to2, this.flags);
      }
      /**
      Extend this range to cover at least `from` to `to`.
      */
      extend(from, to2 = from) {
        if (from <= this.anchor && to2 >= this.anchor)
          return EditorSelection.range(from, to2);
        let head = Math.abs(from - this.anchor) > Math.abs(to2 - this.anchor) ? from : to2;
        return EditorSelection.range(this.anchor, head);
      }
      /**
      Compare this range to another range.
      */
      eq(other, includeAssoc = false) {
        return this.anchor == other.anchor && this.head == other.head && (!includeAssoc || !this.empty || this.assoc == other.assoc);
      }
      /**
      Return a JSON-serializable object representing the range.
      */
      toJSON() {
        return { anchor: this.anchor, head: this.head };
      }
      /**
      Convert a JSON representation of a range to a `SelectionRange`
      instance.
      */
      static fromJSON(json) {
        if (!json || typeof json.anchor != "number" || typeof json.head != "number")
          throw new RangeError("Invalid JSON representation for SelectionRange");
        return EditorSelection.range(json.anchor, json.head);
      }
      /**
      @internal
      */
      static create(from, to2, flags) {
        return new SelectionRange(from, to2, flags);
      }
    }
    class EditorSelection {
      constructor(ranges, mainIndex) {
        this.ranges = ranges;
        this.mainIndex = mainIndex;
      }
      /**
      Map a selection through a change. Used to adjust the selection
      position for changes.
      */
      map(change, assoc = -1) {
        if (change.empty)
          return this;
        return EditorSelection.create(this.ranges.map((r2) => r2.map(change, assoc)), this.mainIndex);
      }
      /**
      Compare this selection to another selection. By default, ranges
      are compared only by position. When `includeAssoc` is true,
      cursor ranges must also have the same
      [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
      */
      eq(other, includeAssoc = false) {
        if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex)
          return false;
        for (let i2 = 0; i2 < this.ranges.length; i2++)
          if (!this.ranges[i2].eq(other.ranges[i2], includeAssoc))
            return false;
        return true;
      }
      /**
      Get the primary selection range. Usually, you should make sure
      your code applies to _all_ ranges, by using methods like
      [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
      */
      get main() {
        return this.ranges[this.mainIndex];
      }
      /**
      Make sure the selection only has one range. Returns a selection
      holding only the main range from this selection.
      */
      asSingle() {
        return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
      }
      /**
      Extend this selection with an extra range.
      */
      addRange(range, main = true) {
        return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
      }
      /**
      Replace a given range with another range, and then normalize the
      selection to merge and sort ranges if necessary.
      */
      replaceRange(range, which = this.mainIndex) {
        let ranges = this.ranges.slice();
        ranges[which] = range;
        return EditorSelection.create(ranges, this.mainIndex);
      }
      /**
      Convert this selection to an object that can be serialized to
      JSON.
      */
      toJSON() {
        return { ranges: this.ranges.map((r2) => r2.toJSON()), main: this.mainIndex };
      }
      /**
      Create a selection from a JSON representation.
      */
      static fromJSON(json) {
        if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
          throw new RangeError("Invalid JSON representation for EditorSelection");
        return new EditorSelection(json.ranges.map((r2) => SelectionRange.fromJSON(r2)), json.main);
      }
      /**
      Create a selection holding a single range.
      */
      static single(anchor, head = anchor) {
        return new EditorSelection([EditorSelection.range(anchor, head)], 0);
      }
      /**
      Sort and merge the given set of ranges, creating a valid
      selection.
      */
      static create(ranges, mainIndex = 0) {
        if (ranges.length == 0)
          throw new RangeError("A selection needs at least one range");
        for (let pos2 = 0, i2 = 0; i2 < ranges.length; i2++) {
          let range = ranges[i2];
          if (range.empty ? range.from <= pos2 : range.from < pos2)
            return EditorSelection.normalized(ranges.slice(), mainIndex);
          pos2 = range.to;
        }
        return new EditorSelection(ranges, mainIndex);
      }
      /**
      Create a cursor selection range at the given position. You can
      safely ignore the optional arguments in most situations.
      */
      static cursor(pos2, assoc = 0, bidiLevel, goalColumn) {
        return SelectionRange.create(pos2, pos2, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) | (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6);
      }
      /**
      Create a selection range.
      */
      static range(anchor, head, goalColumn, bidiLevel) {
        let flags = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
        return head < anchor ? SelectionRange.create(head, anchor, 32 | 16 | flags) : SelectionRange.create(anchor, head, (head > anchor ? 8 : 0) | flags);
      }
      /**
      @internal
      */
      static normalized(ranges, mainIndex = 0) {
        let main = ranges[mainIndex];
        ranges.sort((a, b) => a.from - b.from);
        mainIndex = ranges.indexOf(main);
        for (let i2 = 1; i2 < ranges.length; i2++) {
          let range = ranges[i2], prev = ranges[i2 - 1];
          if (range.empty ? range.from <= prev.to : range.from < prev.to) {
            let from = prev.from, to2 = Math.max(range.to, prev.to);
            if (i2 <= mainIndex)
              mainIndex--;
            ranges.splice(--i2, 2, range.anchor > range.head ? EditorSelection.range(to2, from) : EditorSelection.range(from, to2));
          }
        }
        return new EditorSelection(ranges, mainIndex);
      }
    }
    function checkSelection(selection, docLength) {
      for (let range of selection.ranges)
        if (range.to > docLength)
          throw new RangeError("Selection points outside of document");
    }
    let nextID = 0;
    class Facet {
      constructor(combine, compareInput, compare2, isStatic, enables) {
        this.combine = combine;
        this.compareInput = compareInput;
        this.compare = compare2;
        this.isStatic = isStatic;
        this.id = nextID++;
        this.default = combine([]);
        this.extensions = typeof enables == "function" ? enables(this) : enables;
      }
      /**
      Returns a facet reader for this facet, which can be used to
      [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
      */
      get reader() {
        return this;
      }
      /**
      Define a new facet.
      */
      static define(config2 = {}) {
        return new Facet(config2.combine || ((a) => a), config2.compareInput || ((a, b) => a === b), config2.compare || (!config2.combine ? sameArray$1 : (a, b) => a === b), !!config2.static, config2.enables);
      }
      /**
      Returns an extension that adds the given value to this facet.
      */
      of(value2) {
        return new FacetProvider([], this, 0, value2);
      }
      /**
      Create an extension that computes a value for the facet from a
      state. You must take care to declare the parts of the state that
      this value depends on, since your function is only called again
      for a new state when one of those parts changed.
      
      In cases where your value depends only on a single field, you'll
      want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
      */
      compute(deps, get2) {
        if (this.isStatic)
          throw new Error("Can't compute a static facet");
        return new FacetProvider(deps, this, 1, get2);
      }
      /**
      Create an extension that computes zero or more values for this
      facet from a state.
      */
      computeN(deps, get2) {
        if (this.isStatic)
          throw new Error("Can't compute a static facet");
        return new FacetProvider(deps, this, 2, get2);
      }
      from(field, get2) {
        if (!get2)
          get2 = (x2) => x2;
        return this.compute([field], (state) => get2(state.field(field)));
      }
    }
    function sameArray$1(a, b) {
      return a == b || a.length == b.length && a.every((e, i2) => e === b[i2]);
    }
    class FacetProvider {
      constructor(dependencies, facet, type, value2) {
        this.dependencies = dependencies;
        this.facet = facet;
        this.type = type;
        this.value = value2;
        this.id = nextID++;
      }
      dynamicSlot(addresses) {
        var _a2;
        let getter = this.value;
        let compare2 = this.facet.compareInput;
        let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2;
        let depDoc = false, depSel = false, depAddrs = [];
        for (let dep of this.dependencies) {
          if (dep == "doc")
            depDoc = true;
          else if (dep == "selection")
            depSel = true;
          else if ((((_a2 = addresses[dep.id]) !== null && _a2 !== void 0 ? _a2 : 1) & 1) == 0)
            depAddrs.push(addresses[dep.id]);
        }
        return {
          create(state) {
            state.values[idx] = getter(state);
            return 1;
          },
          update(state, tr2) {
            if (depDoc && tr2.docChanged || depSel && (tr2.docChanged || tr2.selection) || ensureAll(state, depAddrs)) {
              let newVal = getter(state);
              if (multi ? !compareArray(newVal, state.values[idx], compare2) : !compare2(newVal, state.values[idx])) {
                state.values[idx] = newVal;
                return 1;
              }
            }
            return 0;
          },
          reconfigure: (state, oldState) => {
            let newVal, oldAddr = oldState.config.address[id];
            if (oldAddr != null) {
              let oldVal = getAddr(oldState, oldAddr);
              if (this.dependencies.every((dep) => {
                return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
              }) || (multi ? compareArray(newVal = getter(state), oldVal, compare2) : compare2(newVal = getter(state), oldVal))) {
                state.values[idx] = oldVal;
                return 0;
              }
            } else {
              newVal = getter(state);
            }
            state.values[idx] = newVal;
            return 1;
          }
        };
      }
    }
    function compareArray(a, b, compare2) {
      if (a.length != b.length)
        return false;
      for (let i2 = 0; i2 < a.length; i2++)
        if (!compare2(a[i2], b[i2]))
          return false;
      return true;
    }
    function ensureAll(state, addrs) {
      let changed = false;
      for (let addr of addrs)
        if (ensureAddr(state, addr) & 1)
          changed = true;
      return changed;
    }
    function dynamicFacetSlot(addresses, facet, providers) {
      let providerAddrs = providers.map((p) => addresses[p.id]);
      let providerTypes = providers.map((p) => p.type);
      let dynamic = providerAddrs.filter((p) => !(p & 1));
      let idx = addresses[facet.id] >> 1;
      function get2(state) {
        let values = [];
        for (let i2 = 0; i2 < providerAddrs.length; i2++) {
          let value2 = getAddr(state, providerAddrs[i2]);
          if (providerTypes[i2] == 2)
            for (let val of value2)
              values.push(val);
          else
            values.push(value2);
        }
        return facet.combine(values);
      }
      return {
        create(state) {
          for (let addr of providerAddrs)
            ensureAddr(state, addr);
          state.values[idx] = get2(state);
          return 1;
        },
        update(state, tr2) {
          if (!ensureAll(state, dynamic))
            return 0;
          let value2 = get2(state);
          if (facet.compare(value2, state.values[idx]))
            return 0;
          state.values[idx] = value2;
          return 1;
        },
        reconfigure(state, oldState) {
          let depChanged = ensureAll(state, providerAddrs);
          let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
          if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) {
            state.values[idx] = oldValue;
            return 0;
          }
          let value2 = get2(state);
          if (facet.compare(value2, oldValue)) {
            state.values[idx] = oldValue;
            return 0;
          }
          state.values[idx] = value2;
          return 1;
        }
      };
    }
    const initField = /* @__PURE__ */ Facet.define({ static: true });
    class StateField {
      constructor(id, createF, updateF, compareF, spec) {
        this.id = id;
        this.createF = createF;
        this.updateF = updateF;
        this.compareF = compareF;
        this.spec = spec;
        this.provides = void 0;
      }
      /**
      Define a state field.
      */
      static define(config2) {
        let field = new StateField(nextID++, config2.create, config2.update, config2.compare || ((a, b) => a === b), config2);
        if (config2.provide)
          field.provides = config2.provide(field);
        return field;
      }
      create(state) {
        let init = state.facet(initField).find((i2) => i2.field == this);
        return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
      }
      /**
      @internal
      */
      slot(addresses) {
        let idx = addresses[this.id] >> 1;
        return {
          create: (state) => {
            state.values[idx] = this.create(state);
            return 1;
          },
          update: (state, tr2) => {
            let oldVal = state.values[idx];
            let value2 = this.updateF(oldVal, tr2);
            if (this.compareF(oldVal, value2))
              return 0;
            state.values[idx] = value2;
            return 1;
          },
          reconfigure: (state, oldState) => {
            let init = state.facet(initField), oldInit = oldState.facet(initField), reInit;
            if ((reInit = init.find((i2) => i2.field == this)) && reInit != oldInit.find((i2) => i2.field == this)) {
              state.values[idx] = reInit.create(state);
              return 1;
            }
            if (oldState.config.address[this.id] != null) {
              state.values[idx] = oldState.field(this);
              return 0;
            }
            state.values[idx] = this.create(state);
            return 1;
          }
        };
      }
      /**
      Returns an extension that enables this field and overrides the
      way it is initialized. Can be useful when you need to provide a
      non-default starting value for the field.
      */
      init(create2) {
        return [this, initField.of({ field: this, create: create2 })];
      }
      /**
      State field instances can be used as
      [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
      given state.
      */
      get extension() {
        return this;
      }
    }
    const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
    function prec(value2) {
      return (ext) => new PrecExtension(ext, value2);
    }
    const Prec = {
      /**
      The highest precedence level, for extensions that should end up
      near the start of the precedence ordering.
      */
      highest: /* @__PURE__ */ prec(Prec_.highest),
      /**
      A higher-than-default precedence, for extensions that should
      come before those with default precedence.
      */
      high: /* @__PURE__ */ prec(Prec_.high),
      /**
      The default precedence, which is also used for extensions
      without an explicit precedence.
      */
      default: /* @__PURE__ */ prec(Prec_.default),
      /**
      A lower-than-default precedence.
      */
      low: /* @__PURE__ */ prec(Prec_.low),
      /**
      The lowest precedence level. Meant for things that should end up
      near the end of the extension order.
      */
      lowest: /* @__PURE__ */ prec(Prec_.lowest)
    };
    class PrecExtension {
      constructor(inner, prec2) {
        this.inner = inner;
        this.prec = prec2;
      }
    }
    class Compartment {
      /**
      Create an instance of this compartment to add to your [state
      configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
      */
      of(ext) {
        return new CompartmentInstance(this, ext);
      }
      /**
      Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
      reconfigures this compartment.
      */
      reconfigure(content2) {
        return Compartment.reconfigure.of({ compartment: this, extension: content2 });
      }
      /**
      Get the current content of the compartment in the state, or
      `undefined` if it isn't present.
      */
      get(state) {
        return state.config.compartments.get(this);
      }
    }
    class CompartmentInstance {
      constructor(compartment, inner) {
        this.compartment = compartment;
        this.inner = inner;
      }
    }
    class Configuration {
      constructor(base2, compartments, dynamicSlots, address, staticValues, facets) {
        this.base = base2;
        this.compartments = compartments;
        this.dynamicSlots = dynamicSlots;
        this.address = address;
        this.staticValues = staticValues;
        this.facets = facets;
        this.statusTemplate = [];
        while (this.statusTemplate.length < dynamicSlots.length)
          this.statusTemplate.push(
            0
            /* SlotStatus.Unresolved */
          );
      }
      staticFacet(facet) {
        let addr = this.address[facet.id];
        return addr == null ? facet.default : this.staticValues[addr >> 1];
      }
      static resolve(base2, compartments, oldState) {
        let fields = [];
        let facets = /* @__PURE__ */ Object.create(null);
        let newCompartments = /* @__PURE__ */ new Map();
        for (let ext of flatten(base2, compartments, newCompartments)) {
          if (ext instanceof StateField)
            fields.push(ext);
          else
            (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
        }
        let address = /* @__PURE__ */ Object.create(null);
        let staticValues = [];
        let dynamicSlots = [];
        for (let field of fields) {
          address[field.id] = dynamicSlots.length << 1;
          dynamicSlots.push((a) => field.slot(a));
        }
        let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
        for (let id in facets) {
          let providers = facets[id], facet = providers[0].facet;
          let oldProviders = oldFacets && oldFacets[id] || [];
          if (providers.every(
            (p) => p.type == 0
            /* Provider.Static */
          )) {
            address[facet.id] = staticValues.length << 1 | 1;
            if (sameArray$1(oldProviders, providers)) {
              staticValues.push(oldState.facet(facet));
            } else {
              let value2 = facet.combine(providers.map((p) => p.value));
              staticValues.push(oldState && facet.compare(value2, oldState.facet(facet)) ? oldState.facet(facet) : value2);
            }
          } else {
            for (let p of providers) {
              if (p.type == 0) {
                address[p.id] = staticValues.length << 1 | 1;
                staticValues.push(p.value);
              } else {
                address[p.id] = dynamicSlots.length << 1;
                dynamicSlots.push((a) => p.dynamicSlot(a));
              }
            }
            address[facet.id] = dynamicSlots.length << 1;
            dynamicSlots.push((a) => dynamicFacetSlot(a, facet, providers));
          }
        }
        let dynamic = dynamicSlots.map((f) => f(address));
        return new Configuration(base2, newCompartments, dynamic, address, staticValues, facets);
      }
    }
    function flatten(extension, compartments, newCompartments) {
      let result2 = [[], [], [], [], []];
      let seen = /* @__PURE__ */ new Map();
      function inner(ext, prec2) {
        let known = seen.get(ext);
        if (known != null) {
          if (known <= prec2)
            return;
          let found = result2[known].indexOf(ext);
          if (found > -1)
            result2[known].splice(found, 1);
          if (ext instanceof CompartmentInstance)
            newCompartments.delete(ext.compartment);
        }
        seen.set(ext, prec2);
        if (Array.isArray(ext)) {
          for (let e of ext)
            inner(e, prec2);
        } else if (ext instanceof CompartmentInstance) {
          if (newCompartments.has(ext.compartment))
            throw new RangeError(`Duplicate use of compartment in extensions`);
          let content2 = compartments.get(ext.compartment) || ext.inner;
          newCompartments.set(ext.compartment, content2);
          inner(content2, prec2);
        } else if (ext instanceof PrecExtension) {
          inner(ext.inner, ext.prec);
        } else if (ext instanceof StateField) {
          result2[prec2].push(ext);
          if (ext.provides)
            inner(ext.provides, prec2);
        } else if (ext instanceof FacetProvider) {
          result2[prec2].push(ext);
          if (ext.facet.extensions)
            inner(ext.facet.extensions, Prec_.default);
        } else {
          let content2 = ext.extension;
          if (!content2)
            throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
          inner(content2, prec2);
        }
      }
      inner(extension, Prec_.default);
      return result2.reduce((a, b) => a.concat(b));
    }
    function ensureAddr(state, addr) {
      if (addr & 1)
        return 2;
      let idx = addr >> 1;
      let status = state.status[idx];
      if (status == 4)
        throw new Error("Cyclic dependency between fields and/or facets");
      if (status & 2)
        return status;
      state.status[idx] = 4;
      let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
      return state.status[idx] = 2 | changed;
    }
    function getAddr(state, addr) {
      return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
    }
    const languageData = /* @__PURE__ */ Facet.define();
    const allowMultipleSelections = /* @__PURE__ */ Facet.define({
      combine: (values) => values.some((v) => v),
      static: true
    });
    const lineSeparator = /* @__PURE__ */ Facet.define({
      combine: (values) => values.length ? values[0] : void 0,
      static: true
    });
    const changeFilter = /* @__PURE__ */ Facet.define();
    const transactionFilter = /* @__PURE__ */ Facet.define();
    const transactionExtender = /* @__PURE__ */ Facet.define();
    const readOnly = /* @__PURE__ */ Facet.define({
      combine: (values) => values.length ? values[0] : false
    });
    class Annotation {
      /**
      @internal
      */
      constructor(type, value2) {
        this.type = type;
        this.value = value2;
      }
      /**
      Define a new type of annotation.
      */
      static define() {
        return new AnnotationType();
      }
    }
    class AnnotationType {
      /**
      Create an instance of this annotation.
      */
      of(value2) {
        return new Annotation(this, value2);
      }
    }
    class StateEffectType {
      /**
      @internal
      */
      constructor(map2) {
        this.map = map2;
      }
      /**
      Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
      type.
      */
      of(value2) {
        return new StateEffect(this, value2);
      }
    }
    class StateEffect {
      /**
      @internal
      */
      constructor(type, value2) {
        this.type = type;
        this.value = value2;
      }
      /**
      Map this effect through a position mapping. Will return
      `undefined` when that ends up deleting the effect.
      */
      map(mapping) {
        let mapped = this.type.map(this.value, mapping);
        return mapped === void 0 ? void 0 : mapped == this.value ? this : new StateEffect(this.type, mapped);
      }
      /**
      Tells you whether this effect object is of a given
      [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
      */
      is(type) {
        return this.type == type;
      }
      /**
      Define a new effect type. The type parameter indicates the type
      of values that his effect holds. It should be a type that
      doesn't include `undefined`, since that is used in
      [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
      removed.
      */
      static define(spec = {}) {
        return new StateEffectType(spec.map || ((v) => v));
      }
      /**
      Map an array of effects through a change set.
      */
      static mapEffects(effects, mapping) {
        if (!effects.length)
          return effects;
        let result2 = [];
        for (let effect of effects) {
          let mapped = effect.map(mapping);
          if (mapped)
            result2.push(mapped);
        }
        return result2;
      }
    }
    StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define();
    StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define();
    class Transaction {
      constructor(startState, changes, selection, effects, annotations, scrollIntoView2) {
        this.startState = startState;
        this.changes = changes;
        this.selection = selection;
        this.effects = effects;
        this.annotations = annotations;
        this.scrollIntoView = scrollIntoView2;
        this._doc = null;
        this._state = null;
        if (selection)
          checkSelection(selection, changes.newLength);
        if (!annotations.some((a) => a.type == Transaction.time))
          this.annotations = annotations.concat(Transaction.time.of(Date.now()));
      }
      /**
      @internal
      */
      static create(startState, changes, selection, effects, annotations, scrollIntoView2) {
        return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView2);
      }
      /**
      The new document produced by the transaction. Contrary to
      [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
      force the entire new state to be computed right away, so it is
      recommended that [transaction
      filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
      when they need to look at the new document.
      */
      get newDoc() {
        return this._doc || (this._doc = this.changes.apply(this.startState.doc));
      }
      /**
      The new selection produced by the transaction. If
      [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
      this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
      current selection through the changes made by the transaction.
      */
      get newSelection() {
        return this.selection || this.startState.selection.map(this.changes);
      }
      /**
      The new state created by the transaction. Computed on demand
      (but retained for subsequent access), so it is recommended not to
      access it in [transaction
      filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
      */
      get state() {
        if (!this._state)
          this.startState.applyTransaction(this);
        return this._state;
      }
      /**
      Get the value of the given annotation type, if any.
      */
      annotation(type) {
        for (let ann of this.annotations)
          if (ann.type == type)
            return ann.value;
        return void 0;
      }
      /**
      Indicates whether the transaction changed the document.
      */
      get docChanged() {
        return !this.changes.empty;
      }
      /**
      Indicates whether this transaction reconfigures the state
      (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
      with a top-level configuration
      [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
      */
      get reconfigured() {
        return this.startState.config != this.state.config;
      }
      /**
      Returns true if the transaction has a [user
      event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
      or more specific than `event`. For example, if the transaction
      has `"select.pointer"` as user event, `"select"` and
      `"select.pointer"` will match it.
      */
      isUserEvent(event) {
        let e = this.annotation(Transaction.userEvent);
        return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
      }
    }
    Transaction.time = /* @__PURE__ */ Annotation.define();
    Transaction.userEvent = /* @__PURE__ */ Annotation.define();
    Transaction.addToHistory = /* @__PURE__ */ Annotation.define();
    Transaction.remote = /* @__PURE__ */ Annotation.define();
    function joinRanges(a, b) {
      let result2 = [];
      for (let iA = 0, iB = 0; ; ) {
        let from, to2;
        if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
          from = a[iA++];
          to2 = a[iA++];
        } else if (iB < b.length) {
          from = b[iB++];
          to2 = b[iB++];
        } else
          return result2;
        if (!result2.length || result2[result2.length - 1] < from)
          result2.push(from, to2);
        else if (result2[result2.length - 1] < to2)
          result2[result2.length - 1] = to2;
      }
    }
    function mergeTransaction(a, b, sequential) {
      var _a2;
      let mapForA, mapForB, changes;
      if (sequential) {
        mapForA = b.changes;
        mapForB = ChangeSet.empty(b.changes.length);
        changes = a.changes.compose(b.changes);
      } else {
        mapForA = b.changes.map(a.changes);
        mapForB = a.changes.mapDesc(b.changes, true);
        changes = a.changes.compose(mapForA);
      }
      return {
        changes,
        selection: b.selection ? b.selection.map(mapForB) : (_a2 = a.selection) === null || _a2 === void 0 ? void 0 : _a2.map(mapForA),
        effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
        annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
        scrollIntoView: a.scrollIntoView || b.scrollIntoView
      };
    }
    function resolveTransactionInner(state, spec, docSize) {
      let sel = spec.selection, annotations = asArray(spec.annotations);
      if (spec.userEvent)
        annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
      return {
        changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
        selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
        effects: asArray(spec.effects),
        annotations,
        scrollIntoView: !!spec.scrollIntoView
      };
    }
    function resolveTransaction(state, specs, filter) {
      let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
      if (specs.length && specs[0].filter === false)
        filter = false;
      for (let i2 = 1; i2 < specs.length; i2++) {
        if (specs[i2].filter === false)
          filter = false;
        let seq = !!specs[i2].sequential;
        s = mergeTransaction(s, resolveTransactionInner(state, specs[i2], seq ? s.changes.newLength : state.doc.length), seq);
      }
      let tr2 = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
      return extendTransaction(filter ? filterTransaction(tr2) : tr2);
    }
    function filterTransaction(tr2) {
      let state = tr2.startState;
      let result2 = true;
      for (let filter of state.facet(changeFilter)) {
        let value2 = filter(tr2);
        if (value2 === false) {
          result2 = false;
          break;
        }
        if (Array.isArray(value2))
          result2 = result2 === true ? value2 : joinRanges(result2, value2);
      }
      if (result2 !== true) {
        let changes, back;
        if (result2 === false) {
          back = tr2.changes.invertedDesc;
          changes = ChangeSet.empty(state.doc.length);
        } else {
          let filtered = tr2.changes.filter(result2);
          changes = filtered.changes;
          back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
        }
        tr2 = Transaction.create(state, changes, tr2.selection && tr2.selection.map(back), StateEffect.mapEffects(tr2.effects, back), tr2.annotations, tr2.scrollIntoView);
      }
      let filters = state.facet(transactionFilter);
      for (let i2 = filters.length - 1; i2 >= 0; i2--) {
        let filtered = filters[i2](tr2);
        if (filtered instanceof Transaction)
          tr2 = filtered;
        else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
          tr2 = filtered[0];
        else
          tr2 = resolveTransaction(state, asArray(filtered), false);
      }
      return tr2;
    }
    function extendTransaction(tr2) {
      let state = tr2.startState, extenders = state.facet(transactionExtender), spec = tr2;
      for (let i2 = extenders.length - 1; i2 >= 0; i2--) {
        let extension = extenders[i2](tr2);
        if (extension && Object.keys(extension).length)
          spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr2.changes.newLength), true);
      }
      return spec == tr2 ? tr2 : Transaction.create(state, tr2.changes, tr2.selection, spec.effects, spec.annotations, spec.scrollIntoView);
    }
    const none$2 = [];
    function asArray(value2) {
      return value2 == null ? none$2 : Array.isArray(value2) ? value2 : [value2];
    }
    var CharCategory = /* @__PURE__ */ function(CharCategory2) {
      CharCategory2[CharCategory2["Word"] = 0] = "Word";
      CharCategory2[CharCategory2["Space"] = 1] = "Space";
      CharCategory2[CharCategory2["Other"] = 2] = "Other";
      return CharCategory2;
    }(CharCategory || (CharCategory = {}));
    const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
    let wordChar;
    try {
      wordChar = /* @__PURE__ */ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
    } catch (_) {
    }
    function hasWordChar(str2) {
      if (wordChar)
        return wordChar.test(str2);
      for (let i2 = 0; i2 < str2.length; i2++) {
        let ch3 = str2[i2];
        if (/\w/.test(ch3) || ch3 > "" && (ch3.toUpperCase() != ch3.toLowerCase() || nonASCIISingleCaseWordChar.test(ch3)))
          return true;
      }
      return false;
    }
    function makeCategorizer(wordChars) {
      return (char) => {
        if (!/\S/.test(char))
          return CharCategory.Space;
        if (hasWordChar(char))
          return CharCategory.Word;
        for (let i2 = 0; i2 < wordChars.length; i2++)
          if (char.indexOf(wordChars[i2]) > -1)
            return CharCategory.Word;
        return CharCategory.Other;
      };
    }
    class EditorState {
      constructor(config2, doc2, selection, values, computeSlot, tr2) {
        this.config = config2;
        this.doc = doc2;
        this.selection = selection;
        this.values = values;
        this.status = config2.statusTemplate.slice();
        this.computeSlot = computeSlot;
        if (tr2)
          tr2._state = this;
        for (let i2 = 0; i2 < this.config.dynamicSlots.length; i2++)
          ensureAddr(this, i2 << 1);
        this.computeSlot = null;
      }
      field(field, require2 = true) {
        let addr = this.config.address[field.id];
        if (addr == null) {
          if (require2)
            throw new RangeError("Field is not present in this state");
          return void 0;
        }
        ensureAddr(this, addr);
        return getAddr(this, addr);
      }
      /**
      Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
      state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
      can be passed. Unless
      [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
      [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
      are assumed to start in the _current_ document (not the document
      produced by previous specs), and its
      [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
      [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
      to the document created by its _own_ changes. The resulting
      transaction contains the combined effect of all the different
      specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
      specs take precedence over earlier ones.
      */
      update(...specs) {
        return resolveTransaction(this, specs, true);
      }
      /**
      @internal
      */
      applyTransaction(tr2) {
        let conf = this.config, { base: base2, compartments } = conf;
        for (let effect of tr2.effects) {
          if (effect.is(Compartment.reconfigure)) {
            if (conf) {
              compartments = /* @__PURE__ */ new Map();
              conf.compartments.forEach((val, key2) => compartments.set(key2, val));
              conf = null;
            }
            compartments.set(effect.value.compartment, effect.value.extension);
          } else if (effect.is(StateEffect.reconfigure)) {
            conf = null;
            base2 = effect.value;
          } else if (effect.is(StateEffect.appendConfig)) {
            conf = null;
            base2 = asArray(base2).concat(effect.value);
          }
        }
        let startValues;
        if (!conf) {
          conf = Configuration.resolve(base2, compartments, this);
          let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
          startValues = intermediateState.values;
        } else {
          startValues = tr2.startState.values.slice();
        }
        let selection = tr2.startState.facet(allowMultipleSelections) ? tr2.newSelection : tr2.newSelection.asSingle();
        new EditorState(conf, tr2.newDoc, selection, startValues, (state, slot) => slot.update(state, tr2), tr2);
      }
      /**
      Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
      replaces every selection range with the given content.
      */
      replaceSelection(text2) {
        if (typeof text2 == "string")
          text2 = this.toText(text2);
        return this.changeByRange((range) => ({
          changes: { from: range.from, to: range.to, insert: text2 },
          range: EditorSelection.cursor(range.from + text2.length)
        }));
      }
      /**
      Create a set of changes and a new selection by running the given
      function for each range in the active selection. The function
      can return an optional set of changes (in the coordinate space
      of the start document), plus an updated range (in the coordinate
      space of the document produced by the call's own changes). This
      method will merge all the changes and ranges into a single
      changeset and selection, and return it as a [transaction
      spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
      [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
      */
      changeByRange(f) {
        let sel = this.selection;
        let result1 = f(sel.ranges[0]);
        let changes = this.changes(result1.changes), ranges = [result1.range];
        let effects = asArray(result1.effects);
        for (let i2 = 1; i2 < sel.ranges.length; i2++) {
          let result2 = f(sel.ranges[i2]);
          let newChanges = this.changes(result2.changes), newMapped = newChanges.map(changes);
          for (let j2 = 0; j2 < i2; j2++)
            ranges[j2] = ranges[j2].map(newMapped);
          let mapBy = changes.mapDesc(newChanges, true);
          ranges.push(result2.range.map(mapBy));
          changes = changes.compose(newMapped);
          effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result2.effects), mapBy));
        }
        return {
          changes,
          selection: EditorSelection.create(ranges, sel.mainIndex),
          effects
        };
      }
      /**
      Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
      description, taking the state's document length and line
      separator into account.
      */
      changes(spec = []) {
        if (spec instanceof ChangeSet)
          return spec;
        return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
      }
      /**
      Using the state's [line
      separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
      [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
      */
      toText(string2) {
        return Text.of(string2.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
      }
      /**
      Return the given range of the document as a string.
      */
      sliceDoc(from = 0, to2 = this.doc.length) {
        return this.doc.sliceString(from, to2, this.lineBreak);
      }
      /**
      Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
      */
      facet(facet) {
        let addr = this.config.address[facet.id];
        if (addr == null)
          return facet.default;
        ensureAddr(this, addr);
        return getAddr(this, addr);
      }
      /**
      Convert this state to a JSON-serializable object. When custom
      fields should be serialized, you can pass them in as an object
      mapping property names (in the resulting object, which should
      not use `doc` or `selection`) to fields.
      */
      toJSON(fields) {
        let result2 = {
          doc: this.sliceDoc(),
          selection: this.selection.toJSON()
        };
        if (fields)
          for (let prop in fields) {
            let value2 = fields[prop];
            if (value2 instanceof StateField && this.config.address[value2.id] != null)
              result2[prop] = value2.spec.toJSON(this.field(fields[prop]), this);
          }
        return result2;
      }
      /**
      Deserialize a state from its JSON representation. When custom
      fields should be deserialized, pass the same object you passed
      to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
      third argument.
      */
      static fromJSON(json, config2 = {}, fields) {
        if (!json || typeof json.doc != "string")
          throw new RangeError("Invalid JSON representation for EditorState");
        let fieldInit = [];
        if (fields)
          for (let prop in fields) {
            if (Object.prototype.hasOwnProperty.call(json, prop)) {
              let field = fields[prop], value2 = json[prop];
              fieldInit.push(field.init((state) => field.spec.fromJSON(value2, state)));
            }
          }
        return EditorState.create({
          doc: json.doc,
          selection: EditorSelection.fromJSON(json.selection),
          extensions: config2.extensions ? fieldInit.concat([config2.extensions]) : fieldInit
        });
      }
      /**
      Create a new state. You'll usually only need this when
      initializing an editor—updated states are created by applying
      transactions.
      */
      static create(config2 = {}) {
        let configuration = Configuration.resolve(config2.extensions || [], /* @__PURE__ */ new Map());
        let doc2 = config2.doc instanceof Text ? config2.doc : Text.of((config2.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
        let selection = !config2.selection ? EditorSelection.single(0) : config2.selection instanceof EditorSelection ? config2.selection : EditorSelection.single(config2.selection.anchor, config2.selection.head);
        checkSelection(selection, doc2.length);
        if (!configuration.staticFacet(allowMultipleSelections))
          selection = selection.asSingle();
        return new EditorState(configuration, doc2, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
      }
      /**
      The size (in columns) of a tab in the document, determined by
      the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
      */
      get tabSize() {
        return this.facet(EditorState.tabSize);
      }
      /**
      Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
      string for this state.
      */
      get lineBreak() {
        return this.facet(EditorState.lineSeparator) || "\n";
      }
      /**
      Returns true when the editor is
      [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
      */
      get readOnly() {
        return this.facet(readOnly);
      }
      /**
      Look up a translation for the given phrase (via the
      [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
      original string if no translation is found.
      
      If additional arguments are passed, they will be inserted in
      place of markers like `$1` (for the first value) and `$2`, etc.
      A single `$` is equivalent to `$1`, and `$$` will produce a
      literal dollar sign.
      */
      phrase(phrase, ...insert2) {
        for (let map2 of this.facet(EditorState.phrases))
          if (Object.prototype.hasOwnProperty.call(map2, phrase)) {
            phrase = map2[phrase];
            break;
          }
        if (insert2.length)
          phrase = phrase.replace(/\$(\$|\d*)/g, (m, i2) => {
            if (i2 == "$")
              return "$";
            let n = +(i2 || 1);
            return !n || n > insert2.length ? m : insert2[n - 1];
          });
        return phrase;
      }
      /**
      Find the values for a given language data field, provided by the
      the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
      
      Examples of language data fields are...
      
      - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
        comment syntax.
      - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
        for providing language-specific completion sources.
      - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
        characters that should be considered part of words in this
        language.
      - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
        bracket closing behavior.
      */
      languageDataAt(name2, pos2, side = -1) {
        let values = [];
        for (let provider of this.facet(languageData)) {
          for (let result2 of provider(this, pos2, side)) {
            if (Object.prototype.hasOwnProperty.call(result2, name2))
              values.push(result2[name2]);
          }
        }
        return values;
      }
      /**
      Return a function that can categorize strings (expected to
      represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
      into one of:
      
       - Word (contains an alphanumeric character or a character
         explicitly listed in the local language's `"wordChars"`
         language data, which should be a string)
       - Space (contains only whitespace)
       - Other (anything else)
      */
      charCategorizer(at2) {
        return makeCategorizer(this.languageDataAt("wordChars", at2).join(""));
      }
      /**
      Find the word at the given position, meaning the range
      containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
      around it. If no word characters are adjacent to the position,
      this returns null.
      */
      wordAt(pos2) {
        let { text: text2, from, length } = this.doc.lineAt(pos2);
        let cat = this.charCategorizer(pos2);
        let start = pos2 - from, end = pos2 - from;
        while (start > 0) {
          let prev = findClusterBreak(text2, start, false);
          if (cat(text2.slice(prev, start)) != CharCategory.Word)
            break;
          start = prev;
        }
        while (end < length) {
          let next = findClusterBreak(text2, end);
          if (cat(text2.slice(end, next)) != CharCategory.Word)
            break;
          end = next;
        }
        return start == end ? null : EditorSelection.range(start + from, end + from);
      }
    }
    EditorState.allowMultipleSelections = allowMultipleSelections;
    EditorState.tabSize = /* @__PURE__ */ Facet.define({
      combine: (values) => values.length ? values[0] : 4
    });
    EditorState.lineSeparator = lineSeparator;
    EditorState.readOnly = readOnly;
    EditorState.phrases = /* @__PURE__ */ Facet.define({
      compare(a, b) {
        let kA = Object.keys(a), kB = Object.keys(b);
        return kA.length == kB.length && kA.every((k) => a[k] == b[k]);
      }
    });
    EditorState.languageData = languageData;
    EditorState.changeFilter = changeFilter;
    EditorState.transactionFilter = transactionFilter;
    EditorState.transactionExtender = transactionExtender;
    Compartment.reconfigure = /* @__PURE__ */ StateEffect.define();
    function combineConfig(configs, defaults, combine = {}) {
      let result2 = {};
      for (let config2 of configs)
        for (let key2 of Object.keys(config2)) {
          let value2 = config2[key2], current = result2[key2];
          if (current === void 0)
            result2[key2] = value2;
          else if (current === value2 || value2 === void 0) ;
          else if (Object.hasOwnProperty.call(combine, key2))
            result2[key2] = combine[key2](current, value2);
          else
            throw new Error("Config merge conflict for field " + key2);
        }
      for (let key2 in defaults)
        if (result2[key2] === void 0)
          result2[key2] = defaults[key2];
      return result2;
    }
    class RangeValue {
      /**
      Compare this value with another value. Used when comparing
      rangesets. The default implementation compares by identity.
      Unless you are only creating a fixed number of unique instances
      of your value type, it is a good idea to implement this
      properly.
      */
      eq(other) {
        return this == other;
      }
      /**
      Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
      */
      range(from, to2 = from) {
        return Range$1.create(from, to2, this);
      }
    }
    RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
    RangeValue.prototype.point = false;
    RangeValue.prototype.mapMode = MapMode.TrackDel;
    let Range$1 = class Range2 {
      constructor(from, to2, value2) {
        this.from = from;
        this.to = to2;
        this.value = value2;
      }
      /**
      @internal
      */
      static create(from, to2, value2) {
        return new Range2(from, to2, value2);
      }
    };
    function cmpRange(a, b) {
      return a.from - b.from || a.value.startSide - b.value.startSide;
    }
    class Chunk {
      constructor(from, to2, value2, maxPoint) {
        this.from = from;
        this.to = to2;
        this.value = value2;
        this.maxPoint = maxPoint;
      }
      get length() {
        return this.to[this.to.length - 1];
      }
      // Find the index of the given position and side. Use the ranges'
      // `from` pos when `end == false`, `to` when `end == true`.
      findIndex(pos2, side, end, startAt = 0) {
        let arr2 = end ? this.to : this.from;
        for (let lo2 = startAt, hi = arr2.length; ; ) {
          if (lo2 == hi)
            return lo2;
          let mid = lo2 + hi >> 1;
          let diff2 = arr2[mid] - pos2 || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
          if (mid == lo2)
            return diff2 >= 0 ? lo2 : hi;
          if (diff2 >= 0)
            hi = mid;
          else
            lo2 = mid + 1;
        }
      }
      between(offset, from, to2, f) {
        for (let i2 = this.findIndex(from, -1e9, true), e = this.findIndex(to2, 1e9, false, i2); i2 < e; i2++)
          if (f(this.from[i2] + offset, this.to[i2] + offset, this.value[i2]) === false)
            return false;
      }
      map(offset, changes) {
        let value2 = [], from = [], to2 = [], newPos = -1, maxPoint = -1;
        for (let i2 = 0; i2 < this.value.length; i2++) {
          let val = this.value[i2], curFrom = this.from[i2] + offset, curTo = this.to[i2] + offset, newFrom, newTo;
          if (curFrom == curTo) {
            let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
            if (mapped == null)
              continue;
            newFrom = newTo = mapped;
            if (val.startSide != val.endSide) {
              newTo = changes.mapPos(curFrom, val.endSide);
              if (newTo < newFrom)
                continue;
            }
          } else {
            newFrom = changes.mapPos(curFrom, val.startSide);
            newTo = changes.mapPos(curTo, val.endSide);
            if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
              continue;
          }
          if ((newTo - newFrom || val.endSide - val.startSide) < 0)
            continue;
          if (newPos < 0)
            newPos = newFrom;
          if (val.point)
            maxPoint = Math.max(maxPoint, newTo - newFrom);
          value2.push(val);
          from.push(newFrom - newPos);
          to2.push(newTo - newPos);
        }
        return { mapped: value2.length ? new Chunk(from, to2, value2, maxPoint) : null, pos: newPos };
      }
    }
    class RangeSet {
      constructor(chunkPos, chunk, nextLayer, maxPoint) {
        this.chunkPos = chunkPos;
        this.chunk = chunk;
        this.nextLayer = nextLayer;
        this.maxPoint = maxPoint;
      }
      /**
      @internal
      */
      static create(chunkPos, chunk, nextLayer, maxPoint) {
        return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
      }
      /**
      @internal
      */
      get length() {
        let last = this.chunk.length - 1;
        return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
      }
      /**
      The number of ranges in the set.
      */
      get size() {
        if (this.isEmpty)
          return 0;
        let size = this.nextLayer.size;
        for (let chunk of this.chunk)
          size += chunk.value.length;
        return size;
      }
      /**
      @internal
      */
      chunkEnd(index2) {
        return this.chunkPos[index2] + this.chunk[index2].length;
      }
      /**
      Update the range set, optionally adding new ranges or filtering
      out existing ones.
      
      (Note: The type parameter is just there as a kludge to work
      around TypeScript variance issues that prevented `RangeSet<X>`
      from being a subtype of `RangeSet<Y>` when `X` is a subtype of
      `Y`.)
      */
      update(updateSpec) {
        let { add: add2 = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
        let filter = updateSpec.filter;
        if (add2.length == 0 && !filter)
          return this;
        if (sort)
          add2 = add2.slice().sort(cmpRange);
        if (this.isEmpty)
          return add2.length ? RangeSet.of(add2) : this;
        let cur2 = new LayerCursor(this, null, -1).goto(0), i2 = 0, spill = [];
        let builder = new RangeSetBuilder();
        while (cur2.value || i2 < add2.length) {
          if (i2 < add2.length && (cur2.from - add2[i2].from || cur2.startSide - add2[i2].value.startSide) >= 0) {
            let range = add2[i2++];
            if (!builder.addInner(range.from, range.to, range.value))
              spill.push(range);
          } else if (cur2.rangeIndex == 1 && cur2.chunkIndex < this.chunk.length && (i2 == add2.length || this.chunkEnd(cur2.chunkIndex) < add2[i2].from) && (!filter || filterFrom > this.chunkEnd(cur2.chunkIndex) || filterTo < this.chunkPos[cur2.chunkIndex]) && builder.addChunk(this.chunkPos[cur2.chunkIndex], this.chunk[cur2.chunkIndex])) {
            cur2.nextChunk();
          } else {
            if (!filter || filterFrom > cur2.to || filterTo < cur2.from || filter(cur2.from, cur2.to, cur2.value)) {
              if (!builder.addInner(cur2.from, cur2.to, cur2.value))
                spill.push(Range$1.create(cur2.from, cur2.to, cur2.value));
            }
            cur2.next();
          }
        }
        return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
      }
      /**
      Map this range set through a set of changes, return the new set.
      */
      map(changes) {
        if (changes.empty || this.isEmpty)
          return this;
        let chunks = [], chunkPos = [], maxPoint = -1;
        for (let i2 = 0; i2 < this.chunk.length; i2++) {
          let start = this.chunkPos[i2], chunk = this.chunk[i2];
          let touch = changes.touchesRange(start, start + chunk.length);
          if (touch === false) {
            maxPoint = Math.max(maxPoint, chunk.maxPoint);
            chunks.push(chunk);
            chunkPos.push(changes.mapPos(start));
          } else if (touch === true) {
            let { mapped, pos: pos2 } = chunk.map(start, changes);
            if (mapped) {
              maxPoint = Math.max(maxPoint, mapped.maxPoint);
              chunks.push(mapped);
              chunkPos.push(pos2);
            }
          }
        }
        let next = this.nextLayer.map(changes);
        return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
      }
      /**
      Iterate over the ranges that touch the region `from` to `to`,
      calling `f` for each. There is no guarantee that the ranges will
      be reported in any specific order. When the callback returns
      `false`, iteration stops.
      */
      between(from, to2, f) {
        if (this.isEmpty)
          return;
        for (let i2 = 0; i2 < this.chunk.length; i2++) {
          let start = this.chunkPos[i2], chunk = this.chunk[i2];
          if (to2 >= start && from <= start + chunk.length && chunk.between(start, from - start, to2 - start, f) === false)
            return;
        }
        this.nextLayer.between(from, to2, f);
      }
      /**
      Iterate over the ranges in this set, in order, including all
      ranges that end at or after `from`.
      */
      iter(from = 0) {
        return HeapCursor.from([this]).goto(from);
      }
      /**
      @internal
      */
      get isEmpty() {
        return this.nextLayer == this;
      }
      /**
      Iterate over the ranges in a collection of sets, in order,
      starting from `from`.
      */
      static iter(sets, from = 0) {
        return HeapCursor.from(sets).goto(from);
      }
      /**
      Iterate over two groups of sets, calling methods on `comparator`
      to notify it of possible differences.
      */
      static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) {
        let a = oldSets.filter((set) => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
        let b = newSets.filter((set) => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
        let sharedChunks = findSharedChunks(a, b, textDiff);
        let sideA = new SpanCursor(a, sharedChunks, minPointSize);
        let sideB = new SpanCursor(b, sharedChunks, minPointSize);
        textDiff.iterGaps((fromA, fromB, length) => compare$1(sideA, fromA, sideB, fromB, length, comparator));
        if (textDiff.empty && textDiff.length == 0)
          compare$1(sideA, 0, sideB, 0, 0, comparator);
      }
      /**
      Compare the contents of two groups of range sets, returning true
      if they are equivalent in the given range.
      */
      static eq(oldSets, newSets, from = 0, to2) {
        if (to2 == null)
          to2 = 1e9 - 1;
        let a = oldSets.filter((set) => !set.isEmpty && newSets.indexOf(set) < 0);
        let b = newSets.filter((set) => !set.isEmpty && oldSets.indexOf(set) < 0);
        if (a.length != b.length)
          return false;
        if (!a.length)
          return true;
        let sharedChunks = findSharedChunks(a, b);
        let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
        for (; ; ) {
          if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))
            return false;
          if (sideA.to > to2)
            return true;
          sideA.next();
          sideB.next();
        }
      }
      /**
      Iterate over a group of range sets at the same time, notifying
      the iterator about the ranges covering every given piece of
      content. Returns the open count (see
      [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
      of the iteration.
      */
      static spans(sets, from, to2, iterator, minPointSize = -1) {
        let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos2 = from;
        let openRanges = cursor.openStart;
        for (; ; ) {
          let curTo = Math.min(cursor.to, to2);
          if (cursor.point) {
            let active2 = cursor.activeForPoint(cursor.to);
            let openCount = cursor.pointFrom < from ? active2.length + 1 : cursor.point.startSide < 0 ? active2.length : Math.min(active2.length, openRanges);
            iterator.point(pos2, curTo, cursor.point, active2, openCount, cursor.pointRank);
            openRanges = Math.min(cursor.openEnd(curTo), active2.length);
          } else if (curTo > pos2) {
            iterator.span(pos2, curTo, cursor.active, openRanges);
            openRanges = cursor.openEnd(curTo);
          }
          if (cursor.to > to2)
            return openRanges + (cursor.point && cursor.to > to2 ? 1 : 0);
          pos2 = cursor.to;
          cursor.next();
        }
      }
      /**
      Create a range set for the given range or array of ranges. By
      default, this expects the ranges to be _sorted_ (by start
      position and, if two start at the same position,
      `value.startSide`). You can pass `true` as second argument to
      cause the method to sort them.
      */
      static of(ranges, sort = false) {
        let build = new RangeSetBuilder();
        for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges)
          build.add(range.from, range.to, range.value);
        return build.finish();
      }
      /**
      Join an array of range sets into a single set.
      */
      static join(sets) {
        if (!sets.length)
          return RangeSet.empty;
        let result2 = sets[sets.length - 1];
        for (let i2 = sets.length - 2; i2 >= 0; i2--) {
          for (let layer2 = sets[i2]; layer2 != RangeSet.empty; layer2 = layer2.nextLayer)
            result2 = new RangeSet(layer2.chunkPos, layer2.chunk, result2, Math.max(layer2.maxPoint, result2.maxPoint));
        }
        return result2;
      }
    }
    RangeSet.empty = /* @__PURE__ */ new RangeSet([], [], null, -1);
    function lazySort(ranges) {
      if (ranges.length > 1)
        for (let prev = ranges[0], i2 = 1; i2 < ranges.length; i2++) {
          let cur2 = ranges[i2];
          if (cmpRange(prev, cur2) > 0)
            return ranges.slice().sort(cmpRange);
          prev = cur2;
        }
      return ranges;
    }
    RangeSet.empty.nextLayer = RangeSet.empty;
    class RangeSetBuilder {
      finishChunk(newArrays) {
        this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
        this.chunkPos.push(this.chunkStart);
        this.chunkStart = -1;
        this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
        this.maxPoint = -1;
        if (newArrays) {
          this.from = [];
          this.to = [];
          this.value = [];
        }
      }
      /**
      Create an empty builder.
      */
      constructor() {
        this.chunks = [];
        this.chunkPos = [];
        this.chunkStart = -1;
        this.last = null;
        this.lastFrom = -1e9;
        this.lastTo = -1e9;
        this.from = [];
        this.to = [];
        this.value = [];
        this.maxPoint = -1;
        this.setMaxPoint = -1;
        this.nextLayer = null;
      }
      /**
      Add a range. Ranges should be added in sorted (by `from` and
      `value.startSide`) order.
      */
      add(from, to2, value2) {
        if (!this.addInner(from, to2, value2))
          (this.nextLayer || (this.nextLayer = new RangeSetBuilder())).add(from, to2, value2);
      }
      /**
      @internal
      */
      addInner(from, to2, value2) {
        let diff2 = from - this.lastTo || value2.startSide - this.last.endSide;
        if (diff2 <= 0 && (from - this.lastFrom || value2.startSide - this.last.startSide) < 0)
          throw new Error("Ranges must be added sorted by `from` position and `startSide`");
        if (diff2 < 0)
          return false;
        if (this.from.length == 250)
          this.finishChunk(true);
        if (this.chunkStart < 0)
          this.chunkStart = from;
        this.from.push(from - this.chunkStart);
        this.to.push(to2 - this.chunkStart);
        this.last = value2;
        this.lastFrom = from;
        this.lastTo = to2;
        this.value.push(value2);
        if (value2.point)
          this.maxPoint = Math.max(this.maxPoint, to2 - from);
        return true;
      }
      /**
      @internal
      */
      addChunk(from, chunk) {
        if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
          return false;
        if (this.from.length)
          this.finishChunk(true);
        this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
        this.chunks.push(chunk);
        this.chunkPos.push(from);
        let last = chunk.value.length - 1;
        this.last = chunk.value[last];
        this.lastFrom = chunk.from[last] + from;
        this.lastTo = chunk.to[last] + from;
        return true;
      }
      /**
      Finish the range set. Returns the new set. The builder can't be
      used anymore after this has been called.
      */
      finish() {
        return this.finishInner(RangeSet.empty);
      }
      /**
      @internal
      */
      finishInner(next) {
        if (this.from.length)
          this.finishChunk(false);
        if (this.chunks.length == 0)
          return next;
        let result2 = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
        this.from = null;
        return result2;
      }
    }
    function findSharedChunks(a, b, textDiff) {
      let inA = /* @__PURE__ */ new Map();
      for (let set of a)
        for (let i2 = 0; i2 < set.chunk.length; i2++)
          if (set.chunk[i2].maxPoint <= 0)
            inA.set(set.chunk[i2], set.chunkPos[i2]);
      let shared = /* @__PURE__ */ new Set();
      for (let set of b)
        for (let i2 = 0; i2 < set.chunk.length; i2++) {
          let known = inA.get(set.chunk[i2]);
          if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i2] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i2].length)))
            shared.add(set.chunk[i2]);
        }
      return shared;
    }
    class LayerCursor {
      constructor(layer2, skip, minPoint, rank = 0) {
        this.layer = layer2;
        this.skip = skip;
        this.minPoint = minPoint;
        this.rank = rank;
      }
      get startSide() {
        return this.value ? this.value.startSide : 0;
      }
      get endSide() {
        return this.value ? this.value.endSide : 0;
      }
      goto(pos2, side = -1e9) {
        this.chunkIndex = this.rangeIndex = 0;
        this.gotoInner(pos2, side, false);
        return this;
      }
      gotoInner(pos2, side, forward) {
        while (this.chunkIndex < this.layer.chunk.length) {
          let next = this.layer.chunk[this.chunkIndex];
          if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos2 || next.maxPoint < this.minPoint))
            break;
          this.chunkIndex++;
          forward = false;
        }
        if (this.chunkIndex < this.layer.chunk.length) {
          let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos2 - this.layer.chunkPos[this.chunkIndex], side, true);
          if (!forward || this.rangeIndex < rangeIndex)
            this.setRangeIndex(rangeIndex);
        }
        this.next();
      }
      forward(pos2, side) {
        if ((this.to - pos2 || this.endSide - side) < 0)
          this.gotoInner(pos2, side, true);
      }
      next() {
        for (; ; ) {
          if (this.chunkIndex == this.layer.chunk.length) {
            this.from = this.to = 1e9;
            this.value = null;
            break;
          } else {
            let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
            let from = chunkPos + chunk.from[this.rangeIndex];
            this.from = from;
            this.to = chunkPos + chunk.to[this.rangeIndex];
            this.value = chunk.value[this.rangeIndex];
            this.setRangeIndex(this.rangeIndex + 1);
            if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
              break;
          }
        }
      }
      setRangeIndex(index2) {
        if (index2 == this.layer.chunk[this.chunkIndex].value.length) {
          this.chunkIndex++;
          if (this.skip) {
            while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
              this.chunkIndex++;
          }
          this.rangeIndex = 0;
        } else {
          this.rangeIndex = index2;
        }
      }
      nextChunk() {
        this.chunkIndex++;
        this.rangeIndex = 0;
        this.next();
      }
      compare(other) {
        return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide;
      }
    }
    class HeapCursor {
      constructor(heap2) {
        this.heap = heap2;
      }
      static from(sets, skip = null, minPoint = -1) {
        let heap2 = [];
        for (let i2 = 0; i2 < sets.length; i2++) {
          for (let cur2 = sets[i2]; !cur2.isEmpty; cur2 = cur2.nextLayer) {
            if (cur2.maxPoint >= minPoint)
              heap2.push(new LayerCursor(cur2, skip, minPoint, i2));
          }
        }
        return heap2.length == 1 ? heap2[0] : new HeapCursor(heap2);
      }
      get startSide() {
        return this.value ? this.value.startSide : 0;
      }
      goto(pos2, side = -1e9) {
        for (let cur2 of this.heap)
          cur2.goto(pos2, side);
        for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)
          heapBubble(this.heap, i2);
        this.next();
        return this;
      }
      forward(pos2, side) {
        for (let cur2 of this.heap)
          cur2.forward(pos2, side);
        for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)
          heapBubble(this.heap, i2);
        if ((this.to - pos2 || this.value.endSide - side) < 0)
          this.next();
      }
      next() {
        if (this.heap.length == 0) {
          this.from = this.to = 1e9;
          this.value = null;
          this.rank = -1;
        } else {
          let top2 = this.heap[0];
          this.from = top2.from;
          this.to = top2.to;
          this.value = top2.value;
          this.rank = top2.rank;
          if (top2.value)
            top2.next();
          heapBubble(this.heap, 0);
        }
      }
    }
    function heapBubble(heap2, index2) {
      for (let cur2 = heap2[index2]; ; ) {
        let childIndex = (index2 << 1) + 1;
        if (childIndex >= heap2.length)
          break;
        let child = heap2[childIndex];
        if (childIndex + 1 < heap2.length && child.compare(heap2[childIndex + 1]) >= 0) {
          child = heap2[childIndex + 1];
          childIndex++;
        }
        if (cur2.compare(child) < 0)
          break;
        heap2[childIndex] = cur2;
        heap2[index2] = child;
        index2 = childIndex;
      }
    }
    class SpanCursor {
      constructor(sets, skip, minPoint) {
        this.minPoint = minPoint;
        this.active = [];
        this.activeTo = [];
        this.activeRank = [];
        this.minActive = -1;
        this.point = null;
        this.pointFrom = 0;
        this.pointRank = 0;
        this.to = -1e9;
        this.endSide = 0;
        this.openStart = -1;
        this.cursor = HeapCursor.from(sets, skip, minPoint);
      }
      goto(pos2, side = -1e9) {
        this.cursor.goto(pos2, side);
        this.active.length = this.activeTo.length = this.activeRank.length = 0;
        this.minActive = -1;
        this.to = pos2;
        this.endSide = side;
        this.openStart = -1;
        this.next();
        return this;
      }
      forward(pos2, side) {
        while (this.minActive > -1 && (this.activeTo[this.minActive] - pos2 || this.active[this.minActive].endSide - side) < 0)
          this.removeActive(this.minActive);
        this.cursor.forward(pos2, side);
      }
      removeActive(index2) {
        remove(this.active, index2);
        remove(this.activeTo, index2);
        remove(this.activeRank, index2);
        this.minActive = findMinIndex(this.active, this.activeTo);
      }
      addActive(trackOpen) {
        let i2 = 0, { value: value2, to: to2, rank } = this.cursor;
        while (i2 < this.activeRank.length && (rank - this.activeRank[i2] || to2 - this.activeTo[i2]) > 0)
          i2++;
        insert$1(this.active, i2, value2);
        insert$1(this.activeTo, i2, to2);
        insert$1(this.activeRank, i2, rank);
        if (trackOpen)
          insert$1(trackOpen, i2, this.cursor.from);
        this.minActive = findMinIndex(this.active, this.activeTo);
      }
      // After calling this, if `this.point` != null, the next range is a
      // point. Otherwise, it's a regular range, covered by `this.active`.
      next() {
        let from = this.to, wasPoint = this.point;
        this.point = null;
        let trackOpen = this.openStart < 0 ? [] : null;
        for (; ; ) {
          let a = this.minActive;
          if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
            if (this.activeTo[a] > from) {
              this.to = this.activeTo[a];
              this.endSide = this.active[a].endSide;
              break;
            }
            this.removeActive(a);
            if (trackOpen)
              remove(trackOpen, a);
          } else if (!this.cursor.value) {
            this.to = this.endSide = 1e9;
            break;
          } else if (this.cursor.from > from) {
            this.to = this.cursor.from;
            this.endSide = this.cursor.startSide;
            break;
          } else {
            let nextVal = this.cursor.value;
            if (!nextVal.point) {
              this.addActive(trackOpen);
              this.cursor.next();
            } else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
              this.cursor.next();
            } else {
              this.point = nextVal;
              this.pointFrom = this.cursor.from;
              this.pointRank = this.cursor.rank;
              this.to = this.cursor.to;
              this.endSide = nextVal.endSide;
              this.cursor.next();
              this.forward(this.to, this.endSide);
              break;
            }
          }
        }
        if (trackOpen) {
          this.openStart = 0;
          for (let i2 = trackOpen.length - 1; i2 >= 0 && trackOpen[i2] < from; i2--)
            this.openStart++;
        }
      }
      activeForPoint(to2) {
        if (!this.active.length)
          return this.active;
        let active2 = [];
        for (let i2 = this.active.length - 1; i2 >= 0; i2--) {
          if (this.activeRank[i2] < this.pointRank)
            break;
          if (this.activeTo[i2] > to2 || this.activeTo[i2] == to2 && this.active[i2].endSide >= this.point.endSide)
            active2.push(this.active[i2]);
        }
        return active2.reverse();
      }
      openEnd(to2) {
        let open = 0;
        for (let i2 = this.activeTo.length - 1; i2 >= 0 && this.activeTo[i2] > to2; i2--)
          open++;
        return open;
      }
    }
    function compare$1(a, startA, b, startB, length, comparator) {
      a.goto(startA);
      b.goto(startB);
      let endB = startB + length;
      let pos2 = startB, dPos = startB - startA;
      for (; ; ) {
        let dEnd = a.to + dPos - b.to, diff2 = dEnd || a.endSide - b.endSide;
        let end = diff2 < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
        if (a.point || b.point) {
          if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
            comparator.comparePoint(pos2, clipEnd, a.point, b.point);
        } else {
          if (clipEnd > pos2 && !sameValues(a.active, b.active))
            comparator.compareRange(pos2, clipEnd, a.active, b.active);
        }
        if (end > endB)
          break;
        if ((dEnd || a.openEnd != b.openEnd) && comparator.boundChange)
          comparator.boundChange(end);
        pos2 = end;
        if (diff2 <= 0)
          a.next();
        if (diff2 >= 0)
          b.next();
      }
    }
    function sameValues(a, b) {
      if (a.length != b.length)
        return false;
      for (let i2 = 0; i2 < a.length; i2++)
        if (a[i2] != b[i2] && !a[i2].eq(b[i2]))
          return false;
      return true;
    }
    function remove(array, index2) {
      for (let i2 = index2, e = array.length - 1; i2 < e; i2++)
        array[i2] = array[i2 + 1];
      array.pop();
    }
    function insert$1(array, index2, value2) {
      for (let i2 = array.length - 1; i2 >= index2; i2--)
        array[i2 + 1] = array[i2];
      array[index2] = value2;
    }
    function findMinIndex(value2, array) {
      let found = -1, foundPos = 1e9;
      for (let i2 = 0; i2 < array.length; i2++)
        if ((array[i2] - foundPos || value2[i2].endSide - value2[found].endSide) < 0) {
          found = i2;
          foundPos = array[i2];
        }
      return found;
    }
    function countColumn(string2, tabSize, to2 = string2.length) {
      let n = 0;
      for (let i2 = 0; i2 < to2 && i2 < string2.length; ) {
        if (string2.charCodeAt(i2) == 9) {
          n += tabSize - n % tabSize;
          i2++;
        } else {
          n++;
          i2 = findClusterBreak(string2, i2);
        }
      }
      return n;
    }
    function findColumn(string2, col, tabSize, strict) {
      for (let i2 = 0, n = 0; ; ) {
        if (n >= col)
          return i2;
        if (i2 == string2.length)
          break;
        n += string2.charCodeAt(i2) == 9 ? tabSize - n % tabSize : 1;
        i2 = findClusterBreak(string2, i2);
      }
      return string2.length;
    }
    const C = "ͼ";
    const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
    const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
    const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
    class StyleModule {
      // :: (Object<Style>, ?{finish: ?(string) → string})
      // Create a style module from the given spec.
      //
      // When `finish` is given, it is called on regular (non-`@`)
      // selectors (after `&` expansion) to compute the final selector.
      constructor(spec, options2) {
        this.rules = [];
        let { finish } = options2 || {};
        function splitSelector(selector) {
          return /^@/.test(selector) ? [selector] : selector.split(/,\s*/);
        }
        function render2(selectors, spec2, target2, isKeyframes) {
          let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes";
          if (isAt && spec2 == null) return target2.push(selectors[0] + ";");
          for (let prop in spec2) {
            let value2 = spec2[prop];
            if (/&/.test(prop)) {
              render2(
                prop.split(/,\s*/).map((part) => selectors.map((sel) => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),
                value2,
                target2
              );
            } else if (value2 && typeof value2 == "object") {
              if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.");
              render2(splitSelector(prop), value2, local, keyframes);
            } else if (value2 != null) {
              local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, (l) => "-" + l.toLowerCase()) + ": " + value2 + ";");
            }
          }
          if (local.length || keyframes) {
            target2.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}");
          }
        }
        for (let prop in spec) render2(splitSelector(prop), spec[prop], this.rules);
      }
      // :: () → string
      // Returns a string containing the module's CSS rules.
      getRules() {
        return this.rules.join("\n");
      }
      // :: () → string
      // Generate a new unique CSS class name.
      static newName() {
        let id = top[COUNT] || 1;
        top[COUNT] = id + 1;
        return C + id.toString(36);
      }
      // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
      //
      // Mount the given set of modules in the given DOM root, which ensures
      // that the CSS rules defined by the module are available in that
      // context.
      //
      // Rules are only added to the document once per root.
      //
      // Rule order will follow the order of the modules, so that rules from
      // modules later in the array take precedence of those from earlier
      // modules. If you call this function multiple times for the same root
      // in a way that changes the order of already mounted modules, the old
      // order will be changed.
      //
      // If a Content Security Policy nonce is provided, it is added to
      // the `<style>` tag generated by the library.
      static mount(root2, modules, options2) {
        let set = root2[SET], nonce = options2 && options2.nonce;
        if (!set) set = new StyleSet(root2, nonce);
        else if (nonce) set.setNonce(nonce);
        set.mount(Array.isArray(modules) ? modules : [modules], root2);
      }
    }
    let adoptedSet = /* @__PURE__ */ new Map();
    class StyleSet {
      constructor(root2, nonce) {
        let doc2 = root2.ownerDocument || root2, win = doc2.defaultView;
        if (!root2.head && root2.adoptedStyleSheets && win.CSSStyleSheet) {
          let adopted = adoptedSet.get(doc2);
          if (adopted) return root2[SET] = adopted;
          this.sheet = new win.CSSStyleSheet();
          adoptedSet.set(doc2, this);
        } else {
          this.styleTag = doc2.createElement("style");
          if (nonce) this.styleTag.setAttribute("nonce", nonce);
        }
        this.modules = [];
        root2[SET] = this;
      }
      mount(modules, root2) {
        let sheet = this.sheet;
        let pos2 = 0, j2 = 0;
        for (let i2 = 0; i2 < modules.length; i2++) {
          let mod2 = modules[i2], index2 = this.modules.indexOf(mod2);
          if (index2 < j2 && index2 > -1) {
            this.modules.splice(index2, 1);
            j2--;
            index2 = -1;
          }
          if (index2 == -1) {
            this.modules.splice(j2++, 0, mod2);
            if (sheet) for (let k = 0; k < mod2.rules.length; k++)
              sheet.insertRule(mod2.rules[k], pos2++);
          } else {
            while (j2 < index2) pos2 += this.modules[j2++].rules.length;
            pos2 += mod2.rules.length;
            j2++;
          }
        }
        if (sheet) {
          if (root2.adoptedStyleSheets.indexOf(this.sheet) < 0)
            root2.adoptedStyleSheets = [this.sheet, ...root2.adoptedStyleSheets];
        } else {
          let text2 = "";
          for (let i2 = 0; i2 < this.modules.length; i2++)
            text2 += this.modules[i2].getRules() + "\n";
          this.styleTag.textContent = text2;
          let target2 = root2.head || root2;
          if (this.styleTag.parentNode != target2)
            target2.insertBefore(this.styleTag, target2.firstChild);
        }
      }
      setNonce(nonce) {
        if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
          this.styleTag.setAttribute("nonce", nonce);
      }
    }
    var base = {
      8: "Backspace",
      9: "Tab",
      10: "Enter",
      12: "NumLock",
      13: "Enter",
      16: "Shift",
      17: "Control",
      18: "Alt",
      20: "CapsLock",
      27: "Escape",
      32: " ",
      33: "PageUp",
      34: "PageDown",
      35: "End",
      36: "Home",
      37: "ArrowLeft",
      38: "ArrowUp",
      39: "ArrowRight",
      40: "ArrowDown",
      44: "PrintScreen",
      45: "Insert",
      46: "Delete",
      59: ";",
      61: "=",
      91: "Meta",
      92: "Meta",
      106: "*",
      107: "+",
      108: ",",
      109: "-",
      110: ".",
      111: "/",
      144: "NumLock",
      145: "ScrollLock",
      160: "Shift",
      161: "Shift",
      162: "Control",
      163: "Control",
      164: "Alt",
      165: "Alt",
      173: "-",
      186: ";",
      187: "=",
      188: ",",
      189: "-",
      190: ".",
      191: "/",
      192: "`",
      219: "[",
      220: "\\",
      221: "]",
      222: "'"
    };
    var shift = {
      48: ")",
      49: "!",
      50: "@",
      51: "#",
      52: "$",
      53: "%",
      54: "^",
      55: "&",
      56: "*",
      57: "(",
      59: ":",
      61: "+",
      173: "_",
      186: ":",
      187: "+",
      188: "<",
      189: "_",
      190: ">",
      191: "?",
      192: "~",
      219: "{",
      220: "|",
      221: "}",
      222: '"'
    };
    var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
    var ie$2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
    for (var i$1 = 0; i$1 < 10; i$1++) base[48 + i$1] = base[96 + i$1] = String(i$1);
    for (var i$1 = 1; i$1 <= 24; i$1++) base[i$1 + 111] = "F" + i$1;
    for (var i$1 = 65; i$1 <= 90; i$1++) {
      base[i$1] = String.fromCharCode(i$1 + 32);
      shift[i$1] = String.fromCharCode(i$1);
    }
    for (var code$2 in base) if (!shift.hasOwnProperty(code$2)) shift[code$2] = base[code$2];
    function keyName(event) {
      var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie$2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
      var name2 = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
      if (name2 == "Esc") name2 = "Escape";
      if (name2 == "Del") name2 = "Delete";
      if (name2 == "Left") name2 = "ArrowLeft";
      if (name2 == "Up") name2 = "ArrowUp";
      if (name2 == "Right") name2 = "ArrowRight";
      if (name2 == "Down") name2 = "ArrowDown";
      return name2;
    }
    function getSelection(root2) {
      let target2;
      if (root2.nodeType == 11) {
        target2 = root2.getSelection ? root2 : root2.ownerDocument;
      } else {
        target2 = root2;
      }
      return target2.getSelection();
    }
    function contains(dom, node2) {
      return node2 ? dom == node2 || dom.contains(node2.nodeType != 1 ? node2.parentNode : node2) : false;
    }
    function hasSelection(dom, selection) {
      if (!selection.anchorNode)
        return false;
      try {
        return contains(dom, selection.anchorNode);
      } catch (_) {
        return false;
      }
    }
    function clientRectsFor(dom) {
      if (dom.nodeType == 3)
        return textRange(dom, 0, dom.nodeValue.length).getClientRects();
      else if (dom.nodeType == 1)
        return dom.getClientRects();
      else
        return [];
    }
    function isEquivalentPosition(node2, off, targetNode, targetOff) {
      return targetNode ? scanFor(node2, off, targetNode, targetOff, -1) || scanFor(node2, off, targetNode, targetOff, 1) : false;
    }
    function domIndex(node2) {
      for (var index2 = 0; ; index2++) {
        node2 = node2.previousSibling;
        if (!node2)
          return index2;
      }
    }
    function isBlockElement(node2) {
      return node2.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node2.nodeName);
    }
    function scanFor(node2, off, targetNode, targetOff, dir) {
      for (; ; ) {
        if (node2 == targetNode && off == targetOff)
          return true;
        if (off == (dir < 0 ? 0 : maxOffset(node2))) {
          if (node2.nodeName == "DIV")
            return false;
          let parent = node2.parentNode;
          if (!parent || parent.nodeType != 1)
            return false;
          off = domIndex(node2) + (dir < 0 ? 0 : 1);
          node2 = parent;
        } else if (node2.nodeType == 1) {
          node2 = node2.childNodes[off + (dir < 0 ? -1 : 0)];
          if (node2.nodeType == 1 && node2.contentEditable == "false")
            return false;
          off = dir < 0 ? maxOffset(node2) : 0;
        } else {
          return false;
        }
      }
    }
    function maxOffset(node2) {
      return node2.nodeType == 3 ? node2.nodeValue.length : node2.childNodes.length;
    }
    function flattenRect(rect, left) {
      let x2 = left ? rect.left : rect.right;
      return { left: x2, right: x2, top: rect.top, bottom: rect.bottom };
    }
    function windowRect(win) {
      let vp = win.visualViewport;
      if (vp)
        return {
          left: 0,
          right: vp.width,
          top: 0,
          bottom: vp.height
        };
      return {
        left: 0,
        right: win.innerWidth,
        top: 0,
        bottom: win.innerHeight
      };
    }
    function getScale(elt, rect) {
      let scaleX = rect.width / elt.offsetWidth;
      let scaleY = rect.height / elt.offsetHeight;
      if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)
        scaleX = 1;
      if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)
        scaleY = 1;
      return { scaleX, scaleY };
    }
    function scrollRectIntoView(dom, rect, side, x2, y, xMargin, yMargin, ltr) {
      let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
      for (let cur2 = dom, stop = false; cur2 && !stop; ) {
        if (cur2.nodeType == 1) {
          let bounding, top2 = cur2 == doc2.body;
          let scaleX = 1, scaleY = 1;
          if (top2) {
            bounding = windowRect(win);
          } else {
            if (/^(fixed|sticky)$/.test(getComputedStyle(cur2).position))
              stop = true;
            if (cur2.scrollHeight <= cur2.clientHeight && cur2.scrollWidth <= cur2.clientWidth) {
              cur2 = cur2.assignedSlot || cur2.parentNode;
              continue;
            }
            let rect2 = cur2.getBoundingClientRect();
            ({ scaleX, scaleY } = getScale(cur2, rect2));
            bounding = {
              left: rect2.left,
              right: rect2.left + cur2.clientWidth * scaleX,
              top: rect2.top,
              bottom: rect2.top + cur2.clientHeight * scaleY
            };
          }
          let moveX = 0, moveY = 0;
          if (y == "nearest") {
            if (rect.top < bounding.top) {
              moveY = rect.top - (bounding.top + yMargin);
              if (side > 0 && rect.bottom > bounding.bottom + moveY)
                moveY = rect.bottom - bounding.bottom + yMargin;
            } else if (rect.bottom > bounding.bottom) {
              moveY = rect.bottom - bounding.bottom + yMargin;
              if (side < 0 && rect.top - moveY < bounding.top)
                moveY = rect.top - (bounding.top + yMargin);
            }
          } else {
            let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;
            let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y == "start" || y == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin;
            moveY = targetTop - bounding.top;
          }
          if (x2 == "nearest") {
            if (rect.left < bounding.left) {
              moveX = rect.left - (bounding.left + xMargin);
              if (side > 0 && rect.right > bounding.right + moveX)
                moveX = rect.right - bounding.right + xMargin;
            } else if (rect.right > bounding.right) {
              moveX = rect.right - bounding.right + xMargin;
              if (side < 0 && rect.left < bounding.left + moveX)
                moveX = rect.left - (bounding.left + xMargin);
            }
          } else {
            let targetLeft = x2 == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x2 == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin;
            moveX = targetLeft - bounding.left;
          }
          if (moveX || moveY) {
            if (top2) {
              win.scrollBy(moveX, moveY);
            } else {
              let movedX = 0, movedY = 0;
              if (moveY) {
                let start = cur2.scrollTop;
                cur2.scrollTop += moveY / scaleY;
                movedY = (cur2.scrollTop - start) * scaleY;
              }
              if (moveX) {
                let start = cur2.scrollLeft;
                cur2.scrollLeft += moveX / scaleX;
                movedX = (cur2.scrollLeft - start) * scaleX;
              }
              rect = {
                left: rect.left - movedX,
                top: rect.top - movedY,
                right: rect.right - movedX,
                bottom: rect.bottom - movedY
              };
              if (movedX && Math.abs(movedX - moveX) < 1)
                x2 = "nearest";
              if (movedY && Math.abs(movedY - moveY) < 1)
                y = "nearest";
            }
          }
          if (top2)
            break;
          if (rect.top < bounding.top || rect.bottom > bounding.bottom || rect.left < bounding.left || rect.right > bounding.right)
            rect = {
              left: Math.max(rect.left, bounding.left),
              right: Math.min(rect.right, bounding.right),
              top: Math.max(rect.top, bounding.top),
              bottom: Math.min(rect.bottom, bounding.bottom)
            };
          cur2 = cur2.assignedSlot || cur2.parentNode;
        } else if (cur2.nodeType == 11) {
          cur2 = cur2.host;
        } else {
          break;
        }
      }
    }
    function scrollableParents(dom) {
      let doc2 = dom.ownerDocument, x2, y;
      for (let cur2 = dom.parentNode; cur2; ) {
        if (cur2 == doc2.body || x2 && y) {
          break;
        } else if (cur2.nodeType == 1) {
          if (!y && cur2.scrollHeight > cur2.clientHeight)
            y = cur2;
          if (!x2 && cur2.scrollWidth > cur2.clientWidth)
            x2 = cur2;
          cur2 = cur2.assignedSlot || cur2.parentNode;
        } else if (cur2.nodeType == 11) {
          cur2 = cur2.host;
        } else {
          break;
        }
      }
      return { x: x2, y };
    }
    class DOMSelectionState {
      constructor() {
        this.anchorNode = null;
        this.anchorOffset = 0;
        this.focusNode = null;
        this.focusOffset = 0;
      }
      eq(domSel) {
        return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
      }
      setRange(range) {
        let { anchorNode, focusNode } = range;
        this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));
      }
      set(anchorNode, anchorOffset, focusNode, focusOffset) {
        this.anchorNode = anchorNode;
        this.anchorOffset = anchorOffset;
        this.focusNode = focusNode;
        this.focusOffset = focusOffset;
      }
    }
    let preventScrollSupported = null;
    function focusPreventScroll(dom) {
      if (dom.setActive)
        return dom.setActive();
      if (preventScrollSupported)
        return dom.focus(preventScrollSupported);
      let stack2 = [];
      for (let cur2 = dom; cur2; cur2 = cur2.parentNode) {
        stack2.push(cur2, cur2.scrollTop, cur2.scrollLeft);
        if (cur2 == cur2.ownerDocument)
          break;
      }
      dom.focus(preventScrollSupported == null ? {
        get preventScroll() {
          preventScrollSupported = { preventScroll: true };
          return true;
        }
      } : void 0);
      if (!preventScrollSupported) {
        preventScrollSupported = false;
        for (let i2 = 0; i2 < stack2.length; ) {
          let elt = stack2[i2++], top2 = stack2[i2++], left = stack2[i2++];
          if (elt.scrollTop != top2)
            elt.scrollTop = top2;
          if (elt.scrollLeft != left)
            elt.scrollLeft = left;
        }
      }
    }
    let scratchRange;
    function textRange(node2, from, to2 = from) {
      let range = scratchRange || (scratchRange = document.createRange());
      range.setEnd(node2, to2);
      range.setStart(node2, from);
      return range;
    }
    function dispatchKey(elt, name2, code2, mods) {
      let options2 = { key: name2, code: name2, keyCode: code2, which: code2, cancelable: true };
      if (mods)
        ({ altKey: options2.altKey, ctrlKey: options2.ctrlKey, shiftKey: options2.shiftKey, metaKey: options2.metaKey } = mods);
      let down = new KeyboardEvent("keydown", options2);
      down.synthetic = true;
      elt.dispatchEvent(down);
      let up = new KeyboardEvent("keyup", options2);
      up.synthetic = true;
      elt.dispatchEvent(up);
      return down.defaultPrevented || up.defaultPrevented;
    }
    function getRoot(node2) {
      while (node2) {
        if (node2 && (node2.nodeType == 9 || node2.nodeType == 11 && node2.host))
          return node2;
        node2 = node2.assignedSlot || node2.parentNode;
      }
      return null;
    }
    function clearAttributes(node2) {
      while (node2.attributes.length)
        node2.removeAttributeNode(node2.attributes[0]);
    }
    function atElementStart(doc2, selection) {
      let node2 = selection.focusNode, offset = selection.focusOffset;
      if (!node2 || selection.anchorNode != node2 || selection.anchorOffset != offset)
        return false;
      offset = Math.min(offset, maxOffset(node2));
      for (; ; ) {
        if (offset) {
          if (node2.nodeType != 1)
            return false;
          let prev = node2.childNodes[offset - 1];
          if (prev.contentEditable == "false")
            offset--;
          else {
            node2 = prev;
            offset = maxOffset(node2);
          }
        } else if (node2 == doc2) {
          return true;
        } else {
          offset = domIndex(node2);
          node2 = node2.parentNode;
        }
      }
    }
    function isScrolledToBottom(elt) {
      return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
    }
    function textNodeBefore(startNode, startOffset) {
      for (let node2 = startNode, offset = startOffset; ; ) {
        if (node2.nodeType == 3 && offset > 0) {
          return { node: node2, offset };
        } else if (node2.nodeType == 1 && offset > 0) {
          if (node2.contentEditable == "false")
            return null;
          node2 = node2.childNodes[offset - 1];
          offset = maxOffset(node2);
        } else if (node2.parentNode && !isBlockElement(node2)) {
          offset = domIndex(node2);
          node2 = node2.parentNode;
        } else {
          return null;
        }
      }
    }
    function textNodeAfter(startNode, startOffset) {
      for (let node2 = startNode, offset = startOffset; ; ) {
        if (node2.nodeType == 3 && offset < node2.nodeValue.length) {
          return { node: node2, offset };
        } else if (node2.nodeType == 1 && offset < node2.childNodes.length) {
          if (node2.contentEditable == "false")
            return null;
          node2 = node2.childNodes[offset];
          offset = 0;
        } else if (node2.parentNode && !isBlockElement(node2)) {
          offset = domIndex(node2) + 1;
          node2 = node2.parentNode;
        } else {
          return null;
        }
      }
    }
    class DOMPos {
      constructor(node2, offset, precise = true) {
        this.node = node2;
        this.offset = offset;
        this.precise = precise;
      }
      static before(dom, precise) {
        return new DOMPos(dom.parentNode, domIndex(dom), precise);
      }
      static after(dom, precise) {
        return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise);
      }
    }
    const noChildren = [];
    class ContentView {
      constructor() {
        this.parent = null;
        this.dom = null;
        this.flags = 2;
      }
      get overrideDOMText() {
        return null;
      }
      get posAtStart() {
        return this.parent ? this.parent.posBefore(this) : 0;
      }
      get posAtEnd() {
        return this.posAtStart + this.length;
      }
      posBefore(view) {
        let pos2 = this.posAtStart;
        for (let child of this.children) {
          if (child == view)
            return pos2;
          pos2 += child.length + child.breakAfter;
        }
        throw new RangeError("Invalid child in posBefore");
      }
      posAfter(view) {
        return this.posBefore(view) + view.length;
      }
      sync(view, track2) {
        if (this.flags & 2) {
          let parent = this.dom;
          let prev = null, next;
          for (let child of this.children) {
            if (child.flags & 7) {
              if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {
                let contentView = ContentView.get(next);
                if (!contentView || !contentView.parent && contentView.canReuseDOM(child))
                  child.reuseDOM(next);
              }
              child.sync(view, track2);
              child.flags &= -8;
            }
            next = prev ? prev.nextSibling : parent.firstChild;
            if (track2 && !track2.written && track2.node == parent && next != child.dom)
              track2.written = true;
            if (child.dom.parentNode == parent) {
              while (next && next != child.dom)
                next = rm$1(next);
            } else {
              parent.insertBefore(child.dom, next);
            }
            prev = child.dom;
          }
          next = prev ? prev.nextSibling : parent.firstChild;
          if (next && track2 && track2.node == parent)
            track2.written = true;
          while (next)
            next = rm$1(next);
        } else if (this.flags & 1) {
          for (let child of this.children)
            if (child.flags & 7) {
              child.sync(view, track2);
              child.flags &= -8;
            }
        }
      }
      reuseDOM(_dom) {
      }
      localPosFromDOM(node2, offset) {
        let after;
        if (node2 == this.dom) {
          after = this.dom.childNodes[offset];
        } else {
          let bias = maxOffset(node2) == 0 ? 0 : offset == 0 ? -1 : 1;
          for (; ; ) {
            let parent = node2.parentNode;
            if (parent == this.dom)
              break;
            if (bias == 0 && parent.firstChild != parent.lastChild) {
              if (node2 == parent.firstChild)
                bias = -1;
              else
                bias = 1;
            }
            node2 = parent;
          }
          if (bias < 0)
            after = node2;
          else
            after = node2.nextSibling;
        }
        if (after == this.dom.firstChild)
          return 0;
        while (after && !ContentView.get(after))
          after = after.nextSibling;
        if (!after)
          return this.length;
        for (let i2 = 0, pos2 = 0; ; i2++) {
          let child = this.children[i2];
          if (child.dom == after)
            return pos2;
          pos2 += child.length + child.breakAfter;
        }
      }
      domBoundsAround(from, to2, offset = 0) {
        let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
        for (let i2 = 0, pos2 = offset, prevEnd = offset; i2 < this.children.length; i2++) {
          let child = this.children[i2], end = pos2 + child.length;
          if (pos2 < from && end > to2)
            return child.domBoundsAround(from, to2, pos2);
          if (end >= from && fromI == -1) {
            fromI = i2;
            fromStart = pos2;
          }
          if (pos2 > to2 && child.dom.parentNode == this.dom) {
            toI = i2;
            toEnd = prevEnd;
            break;
          }
          prevEnd = end;
          pos2 = end + child.breakAfter;
        }
        return {
          from: fromStart,
          to: toEnd < 0 ? offset + this.length : toEnd,
          startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,
          endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null
        };
      }
      markDirty(andParent = false) {
        this.flags |= 2;
        this.markParentsDirty(andParent);
      }
      markParentsDirty(childList) {
        for (let parent = this.parent; parent; parent = parent.parent) {
          if (childList)
            parent.flags |= 2;
          if (parent.flags & 1)
            return;
          parent.flags |= 1;
          childList = false;
        }
      }
      setParent(parent) {
        if (this.parent != parent) {
          this.parent = parent;
          if (this.flags & 7)
            this.markParentsDirty(true);
        }
      }
      setDOM(dom) {
        if (this.dom == dom)
          return;
        if (this.dom)
          this.dom.cmView = null;
        this.dom = dom;
        dom.cmView = this;
      }
      get rootView() {
        for (let v = this; ; ) {
          let parent = v.parent;
          if (!parent)
            return v;
          v = parent;
        }
      }
      replaceChildren(from, to2, children2 = noChildren) {
        this.markDirty();
        for (let i2 = from; i2 < to2; i2++) {
          let child = this.children[i2];
          if (child.parent == this && children2.indexOf(child) < 0)
            child.destroy();
        }
        if (children2.length < 250)
          this.children.splice(from, to2 - from, ...children2);
        else
          this.children = [].concat(this.children.slice(0, from), children2, this.children.slice(to2));
        for (let i2 = 0; i2 < children2.length; i2++)
          children2[i2].setParent(this);
      }
      ignoreMutation(_rec) {
        return false;
      }
      ignoreEvent(_event) {
        return false;
      }
      childCursor(pos2 = this.length) {
        return new ChildCursor(this.children, pos2, this.children.length);
      }
      childPos(pos2, bias = 1) {
        return this.childCursor().findPos(pos2, bias);
      }
      toString() {
        let name2 = this.constructor.name.replace("View", "");
        return name2 + (this.children.length ? "(" + this.children.join() + ")" : this.length ? "[" + (name2 == "Text" ? this.text : this.length) + "]" : "") + (this.breakAfter ? "#" : "");
      }
      static get(node2) {
        return node2.cmView;
      }
      get isEditable() {
        return true;
      }
      get isWidget() {
        return false;
      }
      get isHidden() {
        return false;
      }
      merge(from, to2, source2, hasStart, openStart, openEnd) {
        return false;
      }
      become(other) {
        return false;
      }
      canReuseDOM(other) {
        return other.constructor == this.constructor && !((this.flags | other.flags) & 8);
      }
      // When this is a zero-length view with a side, this should return a
      // number <= 0 to indicate it is before its position, or a
      // number > 0 when after its position.
      getSide() {
        return 0;
      }
      destroy() {
        for (let child of this.children)
          if (child.parent == this)
            child.destroy();
        this.parent = null;
      }
    }
    ContentView.prototype.breakAfter = 0;
    function rm$1(dom) {
      let next = dom.nextSibling;
      dom.parentNode.removeChild(dom);
      return next;
    }
    class ChildCursor {
      constructor(children2, pos2, i2) {
        this.children = children2;
        this.pos = pos2;
        this.i = i2;
        this.off = 0;
      }
      findPos(pos2, bias = 1) {
        for (; ; ) {
          if (pos2 > this.pos || pos2 == this.pos && (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
            this.off = pos2 - this.pos;
            return this;
          }
          let next = this.children[--this.i];
          this.pos -= next.length + next.breakAfter;
        }
      }
    }
    function replaceRange(parent, fromI, fromOff, toI, toOff, insert2, breakAtStart, openStart, openEnd) {
      let { children: children2 } = parent;
      let before = children2.length ? children2[fromI] : null;
      let last = insert2.length ? insert2[insert2.length - 1] : null;
      let breakAtEnd = last ? last.breakAfter : breakAtStart;
      if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert2.length < 2 && before.merge(fromOff, toOff, insert2.length ? last : null, fromOff == 0, openStart, openEnd))
        return;
      if (toI < children2.length) {
        let after = children2[toI];
        if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {
          if (fromI == toI) {
            after = after.split(toOff);
            toOff = 0;
          }
          if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {
            insert2[insert2.length - 1] = after;
          } else {
            if (toOff || after.children.length && !after.children[0].length)
              after.merge(0, toOff, null, false, 0, openEnd);
            insert2.push(after);
          }
        } else if (after === null || after === void 0 ? void 0 : after.breakAfter) {
          if (last)
            last.breakAfter = 1;
          else
            breakAtStart = 1;
        }
        toI++;
      }
      if (before) {
        before.breakAfter = breakAtStart;
        if (fromOff > 0) {
          if (!breakAtStart && insert2.length && before.merge(fromOff, before.length, insert2[0], false, openStart, 0)) {
            before.breakAfter = insert2.shift().breakAfter;
          } else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {
            before.merge(fromOff, before.length, null, false, openStart, 0);
          }
          fromI++;
        }
      }
      while (fromI < toI && insert2.length) {
        if (children2[toI - 1].become(insert2[insert2.length - 1])) {
          toI--;
          insert2.pop();
          openEnd = insert2.length ? 0 : openStart;
        } else if (children2[fromI].become(insert2[0])) {
          fromI++;
          insert2.shift();
          openStart = insert2.length ? 0 : openEnd;
        } else {
          break;
        }
      }
      if (!insert2.length && fromI && toI < children2.length && !children2[fromI - 1].breakAfter && children2[toI].merge(0, 0, children2[fromI - 1], false, openStart, openEnd))
        fromI--;
      if (fromI < toI || insert2.length)
        parent.replaceChildren(fromI, toI, insert2);
    }
    function mergeChildrenInto(parent, from, to2, insert2, openStart, openEnd) {
      let cur2 = parent.childCursor();
      let { i: toI, off: toOff } = cur2.findPos(to2, 1);
      let { i: fromI, off: fromOff } = cur2.findPos(from, -1);
      let dLen = from - to2;
      for (let view of insert2)
        dLen += view.length;
      parent.length += dLen;
      replaceRange(parent, fromI, fromOff, toI, toOff, insert2, 0, openStart, openEnd);
    }
    let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
    let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
    const ie_edge = /* @__PURE__ */ /Edge\/(\d+)/.exec(nav.userAgent);
    const ie_upto10 = /* @__PURE__ */ /MSIE \d/.test(nav.userAgent);
    const ie_11up = /* @__PURE__ */ /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
    const ie$1 = !!(ie_upto10 || ie_11up || ie_edge);
    const gecko = !ie$1 && /* @__PURE__ */ /gecko\/(\d+)/i.test(nav.userAgent);
    const chrome = !ie$1 && /* @__PURE__ */ /Chrome\/(\d+)/.exec(nav.userAgent);
    const webkit = "webkitFontSmoothing" in doc.documentElement.style;
    const safari = !ie$1 && /* @__PURE__ */ /Apple Computer/.test(nav.vendor);
    const ios = safari && (/* @__PURE__ */ /Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
    var browser = {
      mac: ios || /* @__PURE__ */ /Mac/.test(nav.platform),
      windows: /* @__PURE__ */ /Win/.test(nav.platform),
      linux: /* @__PURE__ */ /Linux|X11/.test(nav.platform),
      ie: ie$1,
      ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
      gecko,
      gecko_version: gecko ? +(/* @__PURE__ */ /Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
      chrome: !!chrome,
      chrome_version: chrome ? +chrome[1] : 0,
      ios,
      android: /* @__PURE__ */ /Android\b/.test(nav.userAgent),
      webkit,
      safari,
      webkit_version: webkit ? +(/* @__PURE__ */ /\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
      tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
    };
    const MaxJoinLen = 256;
    class TextView extends ContentView {
      constructor(text2) {
        super();
        this.text = text2;
      }
      get length() {
        return this.text.length;
      }
      createDOM(textDOM) {
        this.setDOM(textDOM || document.createTextNode(this.text));
      }
      sync(view, track2) {
        if (!this.dom)
          this.createDOM();
        if (this.dom.nodeValue != this.text) {
          if (track2 && track2.node == this.dom)
            track2.written = true;
          this.dom.nodeValue = this.text;
        }
      }
      reuseDOM(dom) {
        if (dom.nodeType == 3)
          this.createDOM(dom);
      }
      merge(from, to2, source2) {
        if (this.flags & 8 || source2 && (!(source2 instanceof TextView) || this.length - (to2 - from) + source2.length > MaxJoinLen || source2.flags & 8))
          return false;
        this.text = this.text.slice(0, from) + (source2 ? source2.text : "") + this.text.slice(to2);
        this.markDirty();
        return true;
      }
      split(from) {
        let result2 = new TextView(this.text.slice(from));
        this.text = this.text.slice(0, from);
        this.markDirty();
        result2.flags |= this.flags & 8;
        return result2;
      }
      localPosFromDOM(node2, offset) {
        return node2 == this.dom ? offset : offset ? this.text.length : 0;
      }
      domAtPos(pos2) {
        return new DOMPos(this.dom, pos2);
      }
      domBoundsAround(_from, _to, offset) {
        return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };
      }
      coordsAt(pos2, side) {
        return textCoords(this.dom, pos2, side);
      }
    }
    class MarkView extends ContentView {
      constructor(mark, children2 = [], length = 0) {
        super();
        this.mark = mark;
        this.children = children2;
        this.length = length;
        for (let ch3 of children2)
          ch3.setParent(this);
      }
      setAttrs(dom) {
        clearAttributes(dom);
        if (this.mark.class)
          dom.className = this.mark.class;
        if (this.mark.attrs)
          for (let name2 in this.mark.attrs)
            dom.setAttribute(name2, this.mark.attrs[name2]);
        return dom;
      }
      canReuseDOM(other) {
        return super.canReuseDOM(other) && !((this.flags | other.flags) & 8);
      }
      reuseDOM(node2) {
        if (node2.nodeName == this.mark.tagName.toUpperCase()) {
          this.setDOM(node2);
          this.flags |= 4 | 2;
        }
      }
      sync(view, track2) {
        if (!this.dom)
          this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));
        else if (this.flags & 4)
          this.setAttrs(this.dom);
        super.sync(view, track2);
      }
      merge(from, to2, source2, _hasStart, openStart, openEnd) {
        if (source2 && (!(source2 instanceof MarkView && source2.mark.eq(this.mark)) || from && openStart <= 0 || to2 < this.length && openEnd <= 0))
          return false;
        mergeChildrenInto(this, from, to2, source2 ? source2.children.slice() : [], openStart - 1, openEnd - 1);
        this.markDirty();
        return true;
      }
      split(from) {
        let result2 = [], off = 0, detachFrom = -1, i2 = 0;
        for (let elt of this.children) {
          let end = off + elt.length;
          if (end > from)
            result2.push(off < from ? elt.split(from - off) : elt);
          if (detachFrom < 0 && off >= from)
            detachFrom = i2;
          off = end;
          i2++;
        }
        let length = this.length - from;
        this.length = from;
        if (detachFrom > -1) {
          this.children.length = detachFrom;
          this.markDirty();
        }
        return new MarkView(this.mark, result2, length);
      }
      domAtPos(pos2) {
        return inlineDOMAtPos(this, pos2);
      }
      coordsAt(pos2, side) {
        return coordsInChildren(this, pos2, side);
      }
    }
    function textCoords(text2, pos2, side) {
      let length = text2.nodeValue.length;
      if (pos2 > length)
        pos2 = length;
      let from = pos2, to2 = pos2, flatten2 = 0;
      if (pos2 == 0 && side < 0 || pos2 == length && side >= 0) {
        if (!(browser.chrome || browser.gecko)) {
          if (pos2) {
            from--;
            flatten2 = 1;
          } else if (to2 < length) {
            to2++;
            flatten2 = -1;
          }
        }
      } else {
        if (side < 0)
          from--;
        else if (to2 < length)
          to2++;
      }
      let rects = textRange(text2, from, to2).getClientRects();
      if (!rects.length)
        return null;
      let rect = rects[(flatten2 ? flatten2 < 0 : side >= 0) ? 0 : rects.length - 1];
      if (browser.safari && !flatten2 && rect.width == 0)
        rect = Array.prototype.find.call(rects, (r2) => r2.width) || rect;
      return flatten2 ? flattenRect(rect, flatten2 < 0) : rect || null;
    }
    class WidgetView extends ContentView {
      static create(widget, length, side) {
        return new WidgetView(widget, length, side);
      }
      constructor(widget, length, side) {
        super();
        this.widget = widget;
        this.length = length;
        this.side = side;
        this.prevWidget = null;
      }
      split(from) {
        let result2 = WidgetView.create(this.widget, this.length - from, this.side);
        this.length -= from;
        return result2;
      }
      sync(view) {
        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
          if (this.dom && this.prevWidget)
            this.prevWidget.destroy(this.dom);
          this.prevWidget = null;
          this.setDOM(this.widget.toDOM(view));
          if (!this.widget.editable)
            this.dom.contentEditable = "false";
        }
      }
      getSide() {
        return this.side;
      }
      merge(from, to2, source2, hasStart, openStart, openEnd) {
        if (source2 && (!(source2 instanceof WidgetView) || !this.widget.compare(source2.widget) || from > 0 && openStart <= 0 || to2 < this.length && openEnd <= 0))
          return false;
        this.length = from + (source2 ? source2.length : 0) + (this.length - to2);
        return true;
      }
      become(other) {
        if (other instanceof WidgetView && other.side == this.side && this.widget.constructor == other.widget.constructor) {
          if (!this.widget.compare(other.widget))
            this.markDirty(true);
          if (this.dom && !this.prevWidget)
            this.prevWidget = this.widget;
          this.widget = other.widget;
          this.length = other.length;
          return true;
        }
        return false;
      }
      ignoreMutation() {
        return true;
      }
      ignoreEvent(event) {
        return this.widget.ignoreEvent(event);
      }
      get overrideDOMText() {
        if (this.length == 0)
          return Text.empty;
        let top2 = this;
        while (top2.parent)
          top2 = top2.parent;
        let { view } = top2, text2 = view && view.state.doc, start = this.posAtStart;
        return text2 ? text2.slice(start, start + this.length) : Text.empty;
      }
      domAtPos(pos2) {
        return (this.length ? pos2 == 0 : this.side > 0) ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos2 == this.length);
      }
      domBoundsAround() {
        return null;
      }
      coordsAt(pos2, side) {
        let custom = this.widget.coordsAt(this.dom, pos2, side);
        if (custom)
          return custom;
        let rects = this.dom.getClientRects(), rect = null;
        if (!rects.length)
          return null;
        let fromBack = this.side ? this.side < 0 : pos2 > 0;
        for (let i2 = fromBack ? rects.length - 1 : 0; ; i2 += fromBack ? -1 : 1) {
          rect = rects[i2];
          if (pos2 > 0 ? i2 == 0 : i2 == rects.length - 1 || rect.top < rect.bottom)
            break;
        }
        return flattenRect(rect, !fromBack);
      }
      get isEditable() {
        return false;
      }
      get isWidget() {
        return true;
      }
      get isHidden() {
        return this.widget.isHidden;
      }
      destroy() {
        super.destroy();
        if (this.dom)
          this.widget.destroy(this.dom);
      }
    }
    class WidgetBufferView extends ContentView {
      constructor(side) {
        super();
        this.side = side;
      }
      get length() {
        return 0;
      }
      merge() {
        return false;
      }
      become(other) {
        return other instanceof WidgetBufferView && other.side == this.side;
      }
      split() {
        return new WidgetBufferView(this.side);
      }
      sync() {
        if (!this.dom) {
          let dom = document.createElement("img");
          dom.className = "cm-widgetBuffer";
          dom.setAttribute("aria-hidden", "true");
          this.setDOM(dom);
        }
      }
      getSide() {
        return this.side;
      }
      domAtPos(pos2) {
        return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom);
      }
      localPosFromDOM() {
        return 0;
      }
      domBoundsAround() {
        return null;
      }
      coordsAt(pos2) {
        return this.dom.getBoundingClientRect();
      }
      get overrideDOMText() {
        return Text.empty;
      }
      get isHidden() {
        return true;
      }
    }
    TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
    function inlineDOMAtPos(parent, pos2) {
      let dom = parent.dom, { children: children2 } = parent, i2 = 0;
      for (let off = 0; i2 < children2.length; i2++) {
        let child = children2[i2], end = off + child.length;
        if (end == off && child.getSide() <= 0)
          continue;
        if (pos2 > off && pos2 < end && child.dom.parentNode == dom)
          return child.domAtPos(pos2 - off);
        if (pos2 <= off)
          break;
        off = end;
      }
      for (let j2 = i2; j2 > 0; j2--) {
        let prev = children2[j2 - 1];
        if (prev.dom.parentNode == dom)
          return prev.domAtPos(prev.length);
      }
      for (let j2 = i2; j2 < children2.length; j2++) {
        let next = children2[j2];
        if (next.dom.parentNode == dom)
          return next.domAtPos(0);
      }
      return new DOMPos(dom, 0);
    }
    function joinInlineInto(parent, view, open) {
      let last, { children: children2 } = parent;
      if (open > 0 && view instanceof MarkView && children2.length && (last = children2[children2.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {
        joinInlineInto(last, view.children[0], open - 1);
      } else {
        children2.push(view);
        view.setParent(parent);
      }
      parent.length += view.length;
    }
    function coordsInChildren(view, pos2, side) {
      let before = null, beforePos = -1, after = null, afterPos = -1;
      function scan(view2, pos3) {
        for (let i2 = 0, off = 0; i2 < view2.children.length && off <= pos3; i2++) {
          let child = view2.children[i2], end = off + child.length;
          if (end >= pos3) {
            if (child.children.length) {
              scan(child, pos3 - off);
            } else if ((!after || after.isHidden && side > 0) && (end > pos3 || off == end && child.getSide() > 0)) {
              after = child;
              afterPos = pos3 - off;
            } else if (off < pos3 || off == end && child.getSide() < 0 && !child.isHidden) {
              before = child;
              beforePos = pos3 - off;
            }
          }
          off = end;
        }
      }
      scan(view, pos2);
      let target2 = (side < 0 ? before : after) || before || after;
      if (target2)
        return target2.coordsAt(Math.max(0, target2 == before ? beforePos : afterPos), side);
      return fallbackRect(view);
    }
    function fallbackRect(view) {
      let last = view.dom.lastChild;
      if (!last)
        return view.dom.getBoundingClientRect();
      let rects = clientRectsFor(last);
      return rects[rects.length - 1] || null;
    }
    function combineAttrs(source2, target2) {
      for (let name2 in source2) {
        if (name2 == "class" && target2.class)
          target2.class += " " + source2.class;
        else if (name2 == "style" && target2.style)
          target2.style += ";" + source2.style;
        else
          target2[name2] = source2[name2];
      }
      return target2;
    }
    const noAttrs$1 = /* @__PURE__ */ Object.create(null);
    function attrsEq(a, b, ignore) {
      if (a == b)
        return true;
      if (!a)
        a = noAttrs$1;
      if (!b)
        b = noAttrs$1;
      let keysA = Object.keys(a), keysB = Object.keys(b);
      if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) != keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))
        return false;
      for (let key2 of keysA) {
        if (key2 != ignore && (keysB.indexOf(key2) == -1 || a[key2] !== b[key2]))
          return false;
      }
      return true;
    }
    function updateAttrs(dom, prev, attrs) {
      let changed = false;
      if (prev) {
        for (let name2 in prev)
          if (!(attrs && name2 in attrs)) {
            changed = true;
            if (name2 == "style")
              dom.style.cssText = "";
            else
              dom.removeAttribute(name2);
          }
      }
      if (attrs) {
        for (let name2 in attrs)
          if (!(prev && prev[name2] == attrs[name2])) {
            changed = true;
            if (name2 == "style")
              dom.style.cssText = attrs[name2];
            else
              dom.setAttribute(name2, attrs[name2]);
          }
      }
      return changed;
    }
    function getAttrs(dom) {
      let attrs = /* @__PURE__ */ Object.create(null);
      for (let i2 = 0; i2 < dom.attributes.length; i2++) {
        let attr = dom.attributes[i2];
        attrs[attr.name] = attr.value;
      }
      return attrs;
    }
    class WidgetType {
      /**
      Compare this instance to another instance of the same type.
      (TypeScript can't express this, but only instances of the same
      specific class will be passed to this method.) This is used to
      avoid redrawing widgets when they are replaced by a new
      decoration of the same type. The default implementation just
      returns `false`, which will cause new instances of the widget to
      always be redrawn.
      */
      eq(widget) {
        return false;
      }
      /**
      Update a DOM element created by a widget of the same type (but
      different, non-`eq` content) to reflect this widget. May return
      true to indicate that it could update, false to indicate it
      couldn't (in which case the widget will be redrawn). The default
      implementation just returns false.
      */
      updateDOM(dom, view) {
        return false;
      }
      /**
      @internal
      */
      compare(other) {
        return this == other || this.constructor == other.constructor && this.eq(other);
      }
      /**
      The estimated height this widget will have, to be used when
      estimating the height of content that hasn't been drawn. May
      return -1 to indicate you don't know. The default implementation
      returns -1.
      */
      get estimatedHeight() {
        return -1;
      }
      /**
      For inline widgets that are displayed inline (as opposed to
      `inline-block`) and introduce line breaks (through `<br>` tags
      or textual newlines), this must indicate the amount of line
      breaks they introduce. Defaults to 0.
      */
      get lineBreaks() {
        return 0;
      }
      /**
      Can be used to configure which kinds of events inside the widget
      should be ignored by the editor. The default is to ignore all
      events.
      */
      ignoreEvent(event) {
        return true;
      }
      /**
      Override the way screen coordinates for positions at/in the
      widget are found. `pos` will be the offset into the widget, and
      `side` the side of the position that is being queried—less than
      zero for before, greater than zero for after, and zero for
      directly at that position.
      */
      coordsAt(dom, pos2, side) {
        return null;
      }
      /**
      @internal
      */
      get isHidden() {
        return false;
      }
      /**
      @internal
      */
      get editable() {
        return false;
      }
      /**
      This is called when the an instance of the widget is removed
      from the editor view.
      */
      destroy(dom) {
      }
    }
    var BlockType = /* @__PURE__ */ function(BlockType2) {
      BlockType2[BlockType2["Text"] = 0] = "Text";
      BlockType2[BlockType2["WidgetBefore"] = 1] = "WidgetBefore";
      BlockType2[BlockType2["WidgetAfter"] = 2] = "WidgetAfter";
      BlockType2[BlockType2["WidgetRange"] = 3] = "WidgetRange";
      return BlockType2;
    }(BlockType || (BlockType = {}));
    class Decoration extends RangeValue {
      constructor(startSide, endSide, widget, spec) {
        super();
        this.startSide = startSide;
        this.endSide = endSide;
        this.widget = widget;
        this.spec = spec;
      }
      /**
      @internal
      */
      get heightRelevant() {
        return false;
      }
      /**
      Create a mark decoration, which influences the styling of the
      content in its range. Nested mark decorations will cause nested
      DOM elements to be created. Nesting order is determined by
      precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
      the higher-precedence decorations creating the inner DOM nodes.
      Such elements are split on line boundaries and on the boundaries
      of lower-precedence decorations.
      */
      static mark(spec) {
        return new MarkDecoration(spec);
      }
      /**
      Create a widget decoration, which displays a DOM element at the
      given position.
      */
      static widget(spec) {
        let side = Math.max(-1e4, Math.min(1e4, spec.side || 0)), block2 = !!spec.block;
        side += block2 && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8;
        return new PointDecoration(spec, side, side, block2, spec.widget || null, false);
      }
      /**
      Create a replace decoration which replaces the given range with
      a widget, or simply hides it.
      */
      static replace(spec) {
        let block2 = !!spec.block, startSide, endSide;
        if (spec.isBlockGap) {
          startSide = -5e8;
          endSide = 4e8;
        } else {
          let { start, end } = getInclusive(spec, block2);
          startSide = (start ? block2 ? -3e8 : -1 : 5e8) - 1;
          endSide = (end ? block2 ? 2e8 : 1 : -6e8) + 1;
        }
        return new PointDecoration(spec, startSide, endSide, block2, spec.widget || null, true);
      }
      /**
      Create a line decoration, which can add DOM attributes to the
      line starting at the given position.
      */
      static line(spec) {
        return new LineDecoration(spec);
      }
      /**
      Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
      decorated range or ranges. If the ranges aren't already sorted,
      pass `true` for `sort` to make the library sort them for you.
      */
      static set(of, sort = false) {
        return RangeSet.of(of, sort);
      }
      /**
      @internal
      */
      hasHeight() {
        return this.widget ? this.widget.estimatedHeight > -1 : false;
      }
    }
    Decoration.none = RangeSet.empty;
    class MarkDecoration extends Decoration {
      constructor(spec) {
        let { start, end } = getInclusive(spec);
        super(start ? -1 : 5e8, end ? 1 : -6e8, null, spec);
        this.tagName = spec.tagName || "span";
        this.class = spec.class || "";
        this.attrs = spec.attributes || null;
      }
      eq(other) {
        var _a2, _b2;
        return this == other || other instanceof MarkDecoration && this.tagName == other.tagName && (this.class || ((_a2 = this.attrs) === null || _a2 === void 0 ? void 0 : _a2.class)) == (other.class || ((_b2 = other.attrs) === null || _b2 === void 0 ? void 0 : _b2.class)) && attrsEq(this.attrs, other.attrs, "class");
      }
      range(from, to2 = from) {
        if (from >= to2)
          throw new RangeError("Mark decorations may not be empty");
        return super.range(from, to2);
      }
    }
    MarkDecoration.prototype.point = false;
    class LineDecoration extends Decoration {
      constructor(spec) {
        super(-2e8, -2e8, null, spec);
      }
      eq(other) {
        return other instanceof LineDecoration && this.spec.class == other.spec.class && attrsEq(this.spec.attributes, other.spec.attributes);
      }
      range(from, to2 = from) {
        if (to2 != from)
          throw new RangeError("Line decoration ranges must be zero-length");
        return super.range(from, to2);
      }
    }
    LineDecoration.prototype.mapMode = MapMode.TrackBefore;
    LineDecoration.prototype.point = true;
    class PointDecoration extends Decoration {
      constructor(spec, startSide, endSide, block2, widget, isReplace) {
        super(startSide, endSide, widget, spec);
        this.block = block2;
        this.isReplace = isReplace;
        this.mapMode = !block2 ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
      }
      // Only relevant when this.block == true
      get type() {
        return this.startSide != this.endSide ? BlockType.WidgetRange : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
      }
      get heightRelevant() {
        return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
      }
      eq(other) {
        return other instanceof PointDecoration && widgetsEq(this.widget, other.widget) && this.block == other.block && this.startSide == other.startSide && this.endSide == other.endSide;
      }
      range(from, to2 = from) {
        if (this.isReplace && (from > to2 || from == to2 && this.startSide > 0 && this.endSide <= 0))
          throw new RangeError("Invalid range for replacement decoration");
        if (!this.isReplace && to2 != from)
          throw new RangeError("Widget decorations can only have zero-length ranges");
        return super.range(from, to2);
      }
    }
    PointDecoration.prototype.point = true;
    function getInclusive(spec, block2 = false) {
      let { inclusiveStart: start, inclusiveEnd: end } = spec;
      if (start == null)
        start = spec.inclusive;
      if (end == null)
        end = spec.inclusive;
      return { start: start !== null && start !== void 0 ? start : block2, end: end !== null && end !== void 0 ? end : block2 };
    }
    function widgetsEq(a, b) {
      return a == b || !!(a && b && a.compare(b));
    }
    function addRange(from, to2, ranges, margin = 0) {
      let last = ranges.length - 1;
      if (last >= 0 && ranges[last] + margin >= from)
        ranges[last] = Math.max(ranges[last], to2);
      else
        ranges.push(from, to2);
    }
    class LineView extends ContentView {
      constructor() {
        super(...arguments);
        this.children = [];
        this.length = 0;
        this.prevAttrs = void 0;
        this.attrs = null;
        this.breakAfter = 0;
      }
      // Consumes source
      merge(from, to2, source2, hasStart, openStart, openEnd) {
        if (source2) {
          if (!(source2 instanceof LineView))
            return false;
          if (!this.dom)
            source2.transferDOM(this);
        }
        if (hasStart)
          this.setDeco(source2 ? source2.attrs : null);
        mergeChildrenInto(this, from, to2, source2 ? source2.children.slice() : [], openStart, openEnd);
        return true;
      }
      split(at2) {
        let end = new LineView();
        end.breakAfter = this.breakAfter;
        if (this.length == 0)
          return end;
        let { i: i2, off } = this.childPos(at2);
        if (off) {
          end.append(this.children[i2].split(off), 0);
          this.children[i2].merge(off, this.children[i2].length, null, false, 0, 0);
          i2++;
        }
        for (let j2 = i2; j2 < this.children.length; j2++)
          end.append(this.children[j2], 0);
        while (i2 > 0 && this.children[i2 - 1].length == 0)
          this.children[--i2].destroy();
        this.children.length = i2;
        this.markDirty();
        this.length = at2;
        return end;
      }
      transferDOM(other) {
        if (!this.dom)
          return;
        this.markDirty();
        other.setDOM(this.dom);
        other.prevAttrs = this.prevAttrs === void 0 ? this.attrs : this.prevAttrs;
        this.prevAttrs = void 0;
        this.dom = null;
      }
      setDeco(attrs) {
        if (!attrsEq(this.attrs, attrs)) {
          if (this.dom) {
            this.prevAttrs = this.attrs;
            this.markDirty();
          }
          this.attrs = attrs;
        }
      }
      append(child, openStart) {
        joinInlineInto(this, child, openStart);
      }
      // Only called when building a line view in ContentBuilder
      addLineDeco(deco) {
        let attrs = deco.spec.attributes, cls = deco.spec.class;
        if (attrs)
          this.attrs = combineAttrs(attrs, this.attrs || {});
        if (cls)
          this.attrs = combineAttrs({ class: cls }, this.attrs || {});
      }
      domAtPos(pos2) {
        return inlineDOMAtPos(this, pos2);
      }
      reuseDOM(node2) {
        if (node2.nodeName == "DIV") {
          this.setDOM(node2);
          this.flags |= 4 | 2;
        }
      }
      sync(view, track2) {
        var _a2;
        if (!this.dom) {
          this.setDOM(document.createElement("div"));
          this.dom.className = "cm-line";
          this.prevAttrs = this.attrs ? null : void 0;
        } else if (this.flags & 4) {
          clearAttributes(this.dom);
          this.dom.className = "cm-line";
          this.prevAttrs = this.attrs ? null : void 0;
        }
        if (this.prevAttrs !== void 0) {
          updateAttrs(this.dom, this.prevAttrs, this.attrs);
          this.dom.classList.add("cm-line");
          this.prevAttrs = void 0;
        }
        super.sync(view, track2);
        let last = this.dom.lastChild;
        while (last && ContentView.get(last) instanceof MarkView)
          last = last.lastChild;
        if (!last || !this.length || last.nodeName != "BR" && ((_a2 = ContentView.get(last)) === null || _a2 === void 0 ? void 0 : _a2.isEditable) == false && (!browser.ios || !this.children.some((ch3) => ch3 instanceof TextView))) {
          let hack = document.createElement("BR");
          hack.cmIgnore = true;
          this.dom.appendChild(hack);
        }
      }
      measureTextSize() {
        if (this.children.length == 0 || this.length > 20)
          return null;
        let totalWidth = 0, textHeight;
        for (let child of this.children) {
          if (!(child instanceof TextView) || /[^ -~]/.test(child.text))
            return null;
          let rects = clientRectsFor(child.dom);
          if (rects.length != 1)
            return null;
          totalWidth += rects[0].width;
          textHeight = rects[0].height;
        }
        return !totalWidth ? null : {
          lineHeight: this.dom.getBoundingClientRect().height,
          charWidth: totalWidth / this.length,
          textHeight
        };
      }
      coordsAt(pos2, side) {
        let rect = coordsInChildren(this, pos2, side);
        if (!this.children.length && rect && this.parent) {
          let { heightOracle } = this.parent.view.viewState, height = rect.bottom - rect.top;
          if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {
            let dist2 = (height - heightOracle.textHeight) / 2;
            return { top: rect.top + dist2, bottom: rect.bottom - dist2, left: rect.left, right: rect.left };
          }
        }
        return rect;
      }
      become(other) {
        return other instanceof LineView && this.children.length == 0 && other.children.length == 0 && attrsEq(this.attrs, other.attrs) && this.breakAfter == other.breakAfter;
      }
      covers() {
        return true;
      }
      static find(docView, pos2) {
        for (let i2 = 0, off = 0; i2 < docView.children.length; i2++) {
          let block2 = docView.children[i2], end = off + block2.length;
          if (end >= pos2) {
            if (block2 instanceof LineView)
              return block2;
            if (end > pos2)
              break;
          }
          off = end + block2.breakAfter;
        }
        return null;
      }
    }
    class BlockWidgetView extends ContentView {
      constructor(widget, length, deco) {
        super();
        this.widget = widget;
        this.length = length;
        this.deco = deco;
        this.breakAfter = 0;
        this.prevWidget = null;
      }
      merge(from, to2, source2, _takeDeco, openStart, openEnd) {
        if (source2 && (!(source2 instanceof BlockWidgetView) || !this.widget.compare(source2.widget) || from > 0 && openStart <= 0 || to2 < this.length && openEnd <= 0))
          return false;
        this.length = from + (source2 ? source2.length : 0) + (this.length - to2);
        return true;
      }
      domAtPos(pos2) {
        return pos2 == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos2 == this.length);
      }
      split(at2) {
        let len = this.length - at2;
        this.length = at2;
        let end = new BlockWidgetView(this.widget, len, this.deco);
        end.breakAfter = this.breakAfter;
        return end;
      }
      get children() {
        return noChildren;
      }
      sync(view) {
        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
          if (this.dom && this.prevWidget)
            this.prevWidget.destroy(this.dom);
          this.prevWidget = null;
          this.setDOM(this.widget.toDOM(view));
          if (!this.widget.editable)
            this.dom.contentEditable = "false";
        }
      }
      get overrideDOMText() {
        return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
      }
      domBoundsAround() {
        return null;
      }
      become(other) {
        if (other instanceof BlockWidgetView && other.widget.constructor == this.widget.constructor) {
          if (!other.widget.compare(this.widget))
            this.markDirty(true);
          if (this.dom && !this.prevWidget)
            this.prevWidget = this.widget;
          this.widget = other.widget;
          this.length = other.length;
          this.deco = other.deco;
          this.breakAfter = other.breakAfter;
          return true;
        }
        return false;
      }
      ignoreMutation() {
        return true;
      }
      ignoreEvent(event) {
        return this.widget.ignoreEvent(event);
      }
      get isEditable() {
        return false;
      }
      get isWidget() {
        return true;
      }
      coordsAt(pos2, side) {
        let custom = this.widget.coordsAt(this.dom, pos2, side);
        if (custom)
          return custom;
        if (this.widget instanceof BlockGapWidget)
          return null;
        return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos2 == 0 : side <= 0);
      }
      destroy() {
        super.destroy();
        if (this.dom)
          this.widget.destroy(this.dom);
      }
      covers(side) {
        let { startSide, endSide } = this.deco;
        return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;
      }
    }
    class BlockGapWidget extends WidgetType {
      constructor(height) {
        super();
        this.height = height;
      }
      toDOM() {
        let elt = document.createElement("div");
        elt.className = "cm-gap";
        this.updateDOM(elt);
        return elt;
      }
      eq(other) {
        return other.height == this.height;
      }
      updateDOM(elt) {
        elt.style.height = this.height + "px";
        return true;
      }
      get editable() {
        return true;
      }
      get estimatedHeight() {
        return this.height;
      }
      ignoreEvent() {
        return false;
      }
    }
    class ContentBuilder {
      constructor(doc2, pos2, end, disallowBlockEffectsFor) {
        this.doc = doc2;
        this.pos = pos2;
        this.end = end;
        this.disallowBlockEffectsFor = disallowBlockEffectsFor;
        this.content = [];
        this.curLine = null;
        this.breakAtStart = 0;
        this.pendingBuffer = 0;
        this.bufferMarks = [];
        this.atCursorPos = true;
        this.openStart = -1;
        this.openEnd = -1;
        this.text = "";
        this.textOff = 0;
        this.cursor = doc2.iter();
        this.skip = pos2;
      }
      posCovered() {
        if (this.content.length == 0)
          return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
        let last = this.content[this.content.length - 1];
        return !(last.breakAfter || last instanceof BlockWidgetView && last.deco.endSide < 0);
      }
      getLine() {
        if (!this.curLine) {
          this.content.push(this.curLine = new LineView());
          this.atCursorPos = true;
        }
        return this.curLine;
      }
      flushBuffer(active2 = this.bufferMarks) {
        if (this.pendingBuffer) {
          this.curLine.append(wrapMarks(new WidgetBufferView(-1), active2), active2.length);
          this.pendingBuffer = 0;
        }
      }
      addBlockWidget(view) {
        this.flushBuffer();
        this.curLine = null;
        this.content.push(view);
      }
      finish(openEnd) {
        if (this.pendingBuffer && openEnd <= this.bufferMarks.length)
          this.flushBuffer();
        else
          this.pendingBuffer = 0;
        if (!this.posCovered() && !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView))
          this.getLine();
      }
      buildText(length, active2, openStart) {
        while (length > 0) {
          if (this.textOff == this.text.length) {
            let { value: value2, lineBreak, done } = this.cursor.next(this.skip);
            this.skip = 0;
            if (done)
              throw new Error("Ran out of text content when drawing inline views");
            if (lineBreak) {
              if (!this.posCovered())
                this.getLine();
              if (this.content.length)
                this.content[this.content.length - 1].breakAfter = 1;
              else
                this.breakAtStart = 1;
              this.flushBuffer();
              this.curLine = null;
              this.atCursorPos = true;
              length--;
              continue;
            } else {
              this.text = value2;
              this.textOff = 0;
            }
          }
          let take = Math.min(
            this.text.length - this.textOff,
            length,
            512
            /* T.Chunk */
          );
          this.flushBuffer(active2.slice(active2.length - openStart));
          this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active2), openStart);
          this.atCursorPos = true;
          this.textOff += take;
          length -= take;
          openStart = 0;
        }
      }
      span(from, to2, active2, openStart) {
        this.buildText(to2 - from, active2, openStart);
        this.pos = to2;
        if (this.openStart < 0)
          this.openStart = openStart;
      }
      point(from, to2, deco, active2, openStart, index2) {
        if (this.disallowBlockEffectsFor[index2] && deco instanceof PointDecoration) {
          if (deco.block)
            throw new RangeError("Block decorations may not be specified via plugins");
          if (to2 > this.doc.lineAt(this.pos).to)
            throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
        }
        let len = to2 - from;
        if (deco instanceof PointDecoration) {
          if (deco.block) {
            if (deco.startSide > 0 && !this.posCovered())
              this.getLine();
            this.addBlockWidget(new BlockWidgetView(deco.widget || NullWidget.block, len, deco));
          } else {
            let view = WidgetView.create(deco.widget || NullWidget.inline, len, len ? 0 : deco.startSide);
            let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active2.length && (from < to2 || deco.startSide > 0);
            let cursorAfter = !view.isEditable && (from < to2 || openStart > active2.length || deco.startSide <= 0);
            let line2 = this.getLine();
            if (this.pendingBuffer == 2 && !cursorBefore && !view.isEditable)
              this.pendingBuffer = 0;
            this.flushBuffer(active2);
            if (cursorBefore) {
              line2.append(wrapMarks(new WidgetBufferView(1), active2), openStart);
              openStart = active2.length + Math.max(0, openStart - active2.length);
            }
            line2.append(wrapMarks(view, active2), openStart);
            this.atCursorPos = cursorAfter;
            this.pendingBuffer = !cursorAfter ? 0 : from < to2 || openStart > active2.length ? 1 : 2;
            if (this.pendingBuffer)
              this.bufferMarks = active2.slice();
          }
        } else if (this.doc.lineAt(this.pos).from == this.pos) {
          this.getLine().addLineDeco(deco);
        }
        if (len) {
          if (this.textOff + len <= this.text.length) {
            this.textOff += len;
          } else {
            this.skip += len - (this.text.length - this.textOff);
            this.text = "";
            this.textOff = 0;
          }
          this.pos = to2;
        }
        if (this.openStart < 0)
          this.openStart = openStart;
      }
      static build(text2, from, to2, decorations2, dynamicDecorationMap) {
        let builder = new ContentBuilder(text2, from, to2, dynamicDecorationMap);
        builder.openEnd = RangeSet.spans(decorations2, from, to2, builder);
        if (builder.openStart < 0)
          builder.openStart = builder.openEnd;
        builder.finish(builder.openEnd);
        return builder;
      }
    }
    function wrapMarks(view, active2) {
      for (let mark of active2)
        view = new MarkView(mark, [view], view.length);
      return view;
    }
    class NullWidget extends WidgetType {
      constructor(tag) {
        super();
        this.tag = tag;
      }
      eq(other) {
        return other.tag == this.tag;
      }
      toDOM() {
        return document.createElement(this.tag);
      }
      updateDOM(elt) {
        return elt.nodeName.toLowerCase() == this.tag;
      }
      get isHidden() {
        return true;
      }
    }
    NullWidget.inline = /* @__PURE__ */ new NullWidget("span");
    NullWidget.block = /* @__PURE__ */ new NullWidget("div");
    var Direction = /* @__PURE__ */ function(Direction2) {
      Direction2[Direction2["LTR"] = 0] = "LTR";
      Direction2[Direction2["RTL"] = 1] = "RTL";
      return Direction2;
    }(Direction || (Direction = {}));
    const LTR = Direction.LTR, RTL = Direction.RTL;
    function dec(str2) {
      let result2 = [];
      for (let i2 = 0; i2 < str2.length; i2++)
        result2.push(1 << +str2[i2]);
      return result2;
    }
    const LowTypes = /* @__PURE__ */ dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
    const ArabicTypes = /* @__PURE__ */ dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
    const Brackets = /* @__PURE__ */ Object.create(null), BracketStack = [];
    for (let p of ["()", "[]", "{}"]) {
      let l = /* @__PURE__ */ p.charCodeAt(0), r2 = /* @__PURE__ */ p.charCodeAt(1);
      Brackets[l] = r2;
      Brackets[r2] = -l;
    }
    function charType(ch3) {
      return ch3 <= 247 ? LowTypes[ch3] : 1424 <= ch3 && ch3 <= 1524 ? 2 : 1536 <= ch3 && ch3 <= 1785 ? ArabicTypes[ch3 - 1536] : 1774 <= ch3 && ch3 <= 2220 ? 4 : 8192 <= ch3 && ch3 <= 8204 ? 256 : 64336 <= ch3 && ch3 <= 65023 ? 4 : 1;
    }
    const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
    class BidiSpan {
      /**
      The direction of this span.
      */
      get dir() {
        return this.level % 2 ? RTL : LTR;
      }
      /**
      @internal
      */
      constructor(from, to2, level) {
        this.from = from;
        this.to = to2;
        this.level = level;
      }
      /**
      @internal
      */
      side(end, dir) {
        return this.dir == dir == end ? this.to : this.from;
      }
      /**
      @internal
      */
      forward(forward, dir) {
        return forward == (this.dir == dir);
      }
      /**
      @internal
      */
      static find(order, index2, level, assoc) {
        let maybe = -1;
        for (let i2 = 0; i2 < order.length; i2++) {
          let span = order[i2];
          if (span.from <= index2 && span.to >= index2) {
            if (span.level == level)
              return i2;
            if (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index2 : span.to > index2 : order[maybe].level > span.level))
              maybe = i2;
          }
        }
        if (maybe < 0)
          throw new RangeError("Index out of range");
        return maybe;
      }
    }
    function isolatesEq(a, b) {
      if (a.length != b.length)
        return false;
      for (let i2 = 0; i2 < a.length; i2++) {
        let iA = a[i2], iB = b[i2];
        if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))
          return false;
      }
      return true;
    }
    const types = [];
    function computeCharTypes(line2, rFrom, rTo, isolates, outerType) {
      for (let iI = 0; iI <= isolates.length; iI++) {
        let from = iI ? isolates[iI - 1].to : rFrom, to2 = iI < isolates.length ? isolates[iI].from : rTo;
        let prevType = iI ? 256 : outerType;
        for (let i2 = from, prev = prevType, prevStrong = prevType; i2 < to2; i2++) {
          let type = charType(line2.charCodeAt(i2));
          if (type == 512)
            type = prev;
          else if (type == 8 && prevStrong == 4)
            type = 16;
          types[i2] = type == 4 ? 2 : type;
          if (type & 7)
            prevStrong = type;
          prev = type;
        }
        for (let i2 = from, prev = prevType, prevStrong = prevType; i2 < to2; i2++) {
          let type = types[i2];
          if (type == 128) {
            if (i2 < to2 - 1 && prev == types[i2 + 1] && prev & 24)
              type = types[i2] = prev;
            else
              types[i2] = 256;
          } else if (type == 64) {
            let end = i2 + 1;
            while (end < to2 && types[end] == 64)
              end++;
            let replace2 = i2 && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
            for (let j2 = i2; j2 < end; j2++)
              types[j2] = replace2;
            i2 = end - 1;
          } else if (type == 8 && prevStrong == 1) {
            types[i2] = 1;
          }
          prev = type;
          if (type & 7)
            prevStrong = type;
        }
      }
    }
    function processBracketPairs(line2, rFrom, rTo, isolates, outerType) {
      let oppositeType = outerType == 1 ? 2 : 1;
      for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
        let from = iI ? isolates[iI - 1].to : rFrom, to2 = iI < isolates.length ? isolates[iI].from : rTo;
        for (let i2 = from, ch3, br2, type; i2 < to2; i2++) {
          if (br2 = Brackets[ch3 = line2.charCodeAt(i2)]) {
            if (br2 < 0) {
              for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
                if (BracketStack[sJ + 1] == -br2) {
                  let flags = BracketStack[sJ + 2];
                  let type2 = flags & 2 ? outerType : !(flags & 4) ? 0 : flags & 1 ? oppositeType : outerType;
                  if (type2)
                    types[i2] = types[BracketStack[sJ]] = type2;
                  sI = sJ;
                  break;
                }
              }
            } else if (BracketStack.length == 189) {
              break;
            } else {
              BracketStack[sI++] = i2;
              BracketStack[sI++] = ch3;
              BracketStack[sI++] = context;
            }
          } else if ((type = types[i2]) == 2 || type == 1) {
            let embed = type == outerType;
            context = embed ? 0 : 1;
            for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
              let cur2 = BracketStack[sJ + 2];
              if (cur2 & 2)
                break;
              if (embed) {
                BracketStack[sJ + 2] |= 2;
              } else {
                if (cur2 & 4)
                  break;
                BracketStack[sJ + 2] |= 4;
              }
            }
          }
        }
      }
    }
    function processNeutrals(rFrom, rTo, isolates, outerType) {
      for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
        let from = iI ? isolates[iI - 1].to : rFrom, to2 = iI < isolates.length ? isolates[iI].from : rTo;
        for (let i2 = from; i2 < to2; ) {
          let type = types[i2];
          if (type == 256) {
            let end = i2 + 1;
            for (; ; ) {
              if (end == to2) {
                if (iI == isolates.length)
                  break;
                end = isolates[iI++].to;
                to2 = iI < isolates.length ? isolates[iI].from : rTo;
              } else if (types[end] == 256) {
                end++;
              } else {
                break;
              }
            }
            let beforeL = prev == 1;
            let afterL = (end < rTo ? types[end] : outerType) == 1;
            let replace2 = beforeL == afterL ? beforeL ? 1 : 2 : outerType;
            for (let j2 = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j2 > i2; ) {
              if (j2 == fromJ) {
                j2 = isolates[--jI].from;
                fromJ = jI ? isolates[jI - 1].to : rFrom;
              }
              types[--j2] = replace2;
            }
            i2 = end;
          } else {
            prev = type;
            i2++;
          }
        }
      }
    }
    function emitSpans(line2, from, to2, level, baseLevel, isolates, order) {
      let ourType = level % 2 ? 2 : 1;
      if (level % 2 == baseLevel % 2) {
        for (let iCh = from, iI = 0; iCh < to2; ) {
          let sameDir = true, isNum = false;
          if (iI == isolates.length || iCh < isolates[iI].from) {
            let next = types[iCh];
            if (next != ourType) {
              sameDir = false;
              isNum = next == 16;
            }
          }
          let recurse = !sameDir && ourType == 1 ? [] : null;
          let localLevel = sameDir ? level : level + 1;
          let iScan = iCh;
          run: for (; ; ) {
            if (iI < isolates.length && iScan == isolates[iI].from) {
              if (isNum)
                break run;
              let iso = isolates[iI];
              if (!sameDir)
                for (let upto = iso.to, jI = iI + 1; ; ) {
                  if (upto == to2)
                    break run;
                  if (jI < isolates.length && isolates[jI].from == upto)
                    upto = isolates[jI++].to;
                  else if (types[upto] == ourType)
                    break run;
                  else
                    break;
                }
              iI++;
              if (recurse) {
                recurse.push(iso);
              } else {
                if (iso.from > iCh)
                  order.push(new BidiSpan(iCh, iso.from, localLevel));
                let dirSwap = iso.direction == LTR != !(localLevel % 2);
                computeSectionOrder(line2, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
                iCh = iso.to;
              }
              iScan = iso.to;
            } else if (iScan == to2 || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
              break;
            } else {
              iScan++;
            }
          }
          if (recurse)
            emitSpans(line2, iCh, iScan, level + 1, baseLevel, recurse, order);
          else if (iCh < iScan)
            order.push(new BidiSpan(iCh, iScan, localLevel));
          iCh = iScan;
        }
      } else {
        for (let iCh = to2, iI = isolates.length; iCh > from; ) {
          let sameDir = true, isNum = false;
          if (!iI || iCh > isolates[iI - 1].to) {
            let next = types[iCh - 1];
            if (next != ourType) {
              sameDir = false;
              isNum = next == 16;
            }
          }
          let recurse = !sameDir && ourType == 1 ? [] : null;
          let localLevel = sameDir ? level : level + 1;
          let iScan = iCh;
          run: for (; ; ) {
            if (iI && iScan == isolates[iI - 1].to) {
              if (isNum)
                break run;
              let iso = isolates[--iI];
              if (!sameDir)
                for (let upto = iso.from, jI = iI; ; ) {
                  if (upto == from)
                    break run;
                  if (jI && isolates[jI - 1].to == upto)
                    upto = isolates[--jI].from;
                  else if (types[upto - 1] == ourType)
                    break run;
                  else
                    break;
                }
              if (recurse) {
                recurse.push(iso);
              } else {
                if (iso.to < iCh)
                  order.push(new BidiSpan(iso.to, iCh, localLevel));
                let dirSwap = iso.direction == LTR != !(localLevel % 2);
                computeSectionOrder(line2, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
                iCh = iso.from;
              }
              iScan = iso.from;
            } else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
              break;
            } else {
              iScan--;
            }
          }
          if (recurse)
            emitSpans(line2, iScan, iCh, level + 1, baseLevel, recurse, order);
          else if (iScan < iCh)
            order.push(new BidiSpan(iScan, iCh, localLevel));
          iCh = iScan;
        }
      }
    }
    function computeSectionOrder(line2, level, baseLevel, isolates, from, to2, order) {
      let outerType = level % 2 ? 2 : 1;
      computeCharTypes(line2, from, to2, isolates, outerType);
      processBracketPairs(line2, from, to2, isolates, outerType);
      processNeutrals(from, to2, isolates, outerType);
      emitSpans(line2, from, to2, level, baseLevel, isolates, order);
    }
    function computeOrder(line2, direction, isolates) {
      if (!line2)
        return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
      if (direction == LTR && !isolates.length && !BidiRE.test(line2))
        return trivialOrder(line2.length);
      if (isolates.length)
        while (line2.length > types.length)
          types[types.length] = 256;
      let order = [], level = direction == LTR ? 0 : 1;
      computeSectionOrder(line2, level, level, isolates, 0, line2.length, order);
      return order;
    }
    function trivialOrder(length) {
      return [new BidiSpan(0, length, 0)];
    }
    let movedOver = "";
    function moveVisually(line2, order, dir, start, forward) {
      var _a2;
      let startIndex = start.head - line2.from;
      let spanI = BidiSpan.find(order, startIndex, (_a2 = start.bidiLevel) !== null && _a2 !== void 0 ? _a2 : -1, start.assoc);
      let span = order[spanI], spanEnd = span.side(forward, dir);
      if (startIndex == spanEnd) {
        let nextI = spanI += forward ? 1 : -1;
        if (nextI < 0 || nextI >= order.length)
          return null;
        span = order[spanI = nextI];
        startIndex = span.side(!forward, dir);
        spanEnd = span.side(forward, dir);
      }
      let nextIndex = findClusterBreak(line2.text, startIndex, span.forward(forward, dir));
      if (nextIndex < span.from || nextIndex > span.to)
        nextIndex = spanEnd;
      movedOver = line2.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
      let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
      if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)
        return EditorSelection.cursor(nextSpan.side(!forward, dir) + line2.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
      return EditorSelection.cursor(nextIndex + line2.from, span.forward(forward, dir) ? -1 : 1, span.level);
    }
    function autoDirection(text2, from, to2) {
      for (let i2 = from; i2 < to2; i2++) {
        let type = charType(text2.charCodeAt(i2));
        if (type == 1)
          return LTR;
        if (type == 2 || type == 4)
          return RTL;
      }
      return LTR;
    }
    const clickAddsSelectionRange = /* @__PURE__ */ Facet.define();
    const dragMovesSelection$1 = /* @__PURE__ */ Facet.define();
    const mouseSelectionStyle = /* @__PURE__ */ Facet.define();
    const exceptionSink = /* @__PURE__ */ Facet.define();
    const updateListener = /* @__PURE__ */ Facet.define();
    const inputHandler = /* @__PURE__ */ Facet.define();
    const focusChangeEffect = /* @__PURE__ */ Facet.define();
    const clipboardInputFilter = /* @__PURE__ */ Facet.define();
    const clipboardOutputFilter = /* @__PURE__ */ Facet.define();
    const perLineTextDirection = /* @__PURE__ */ Facet.define({
      combine: (values) => values.some((x2) => x2)
    });
    const nativeSelectionHidden = /* @__PURE__ */ Facet.define({
      combine: (values) => values.some((x2) => x2)
    });
    const scrollHandler = /* @__PURE__ */ Facet.define();
    class ScrollTarget {
      constructor(range, y = "nearest", x2 = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
        this.range = range;
        this.y = y;
        this.x = x2;
        this.yMargin = yMargin;
        this.xMargin = xMargin;
        this.isSnapshot = isSnapshot;
      }
      map(changes) {
        return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
      }
      clip(state) {
        return this.range.to <= state.doc.length ? this : new ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
      }
    }
    const scrollIntoView$1 = /* @__PURE__ */ StateEffect.define({ map: (t2, ch3) => t2.map(ch3) });
    const setEditContextFormatting = /* @__PURE__ */ StateEffect.define();
    function logException(state, exception, context) {
      let handler = state.facet(exceptionSink);
      if (handler.length)
        handler[0](exception);
      else if (window.onerror)
        window.onerror(String(exception), context, void 0, void 0, exception);
      else if (context)
        console.error(context + ":", exception);
      else
        console.error(exception);
    }
    const editable = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : true });
    let nextPluginID = 0;
    const viewPlugin = /* @__PURE__ */ Facet.define();
    class ViewPlugin {
      constructor(id, create2, domEventHandlers, domEventObservers, buildExtensions) {
        this.id = id;
        this.create = create2;
        this.domEventHandlers = domEventHandlers;
        this.domEventObservers = domEventObservers;
        this.extension = buildExtensions(this);
      }
      /**
      Define a plugin from a constructor function that creates the
      plugin's value, given an editor view.
      */
      static define(create2, spec) {
        const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
        return new ViewPlugin(nextPluginID++, create2, eventHandlers, eventObservers, (plugin) => {
          let ext = [viewPlugin.of(plugin)];
          if (deco)
            ext.push(decorations.of((view) => {
              let pluginInst = view.plugin(plugin);
              return pluginInst ? deco(pluginInst) : Decoration.none;
            }));
          if (provide)
            ext.push(provide(plugin));
          return ext;
        });
      }
      /**
      Create a plugin for a class whose constructor takes a single
      editor view as argument.
      */
      static fromClass(cls, spec) {
        return ViewPlugin.define((view) => new cls(view), spec);
      }
    }
    class PluginInstance {
      constructor(spec) {
        this.spec = spec;
        this.mustUpdate = null;
        this.value = null;
      }
      update(view) {
        if (!this.value) {
          if (this.spec) {
            try {
              this.value = this.spec.create(view);
            } catch (e) {
              logException(view.state, e, "CodeMirror plugin crashed");
              this.deactivate();
            }
          }
        } else if (this.mustUpdate) {
          let update = this.mustUpdate;
          this.mustUpdate = null;
          if (this.value.update) {
            try {
              this.value.update(update);
            } catch (e) {
              logException(update.state, e, "CodeMirror plugin crashed");
              if (this.value.destroy)
                try {
                  this.value.destroy();
                } catch (_) {
                }
              this.deactivate();
            }
          }
        }
        return this;
      }
      destroy(view) {
        var _a2;
        if ((_a2 = this.value) === null || _a2 === void 0 ? void 0 : _a2.destroy) {
          try {
            this.value.destroy();
          } catch (e) {
            logException(view.state, e, "CodeMirror plugin crashed");
          }
        }
      }
      deactivate() {
        this.spec = this.value = null;
      }
    }
    const editorAttributes = /* @__PURE__ */ Facet.define();
    const contentAttributes = /* @__PURE__ */ Facet.define();
    const decorations = /* @__PURE__ */ Facet.define();
    const outerDecorations = /* @__PURE__ */ Facet.define();
    const atomicRanges = /* @__PURE__ */ Facet.define();
    const bidiIsolatedRanges = /* @__PURE__ */ Facet.define();
    function getIsolatedRanges(view, line2) {
      let isolates = view.state.facet(bidiIsolatedRanges);
      if (!isolates.length)
        return isolates;
      let sets = isolates.map((i2) => i2 instanceof Function ? i2(view) : i2);
      let result2 = [];
      RangeSet.spans(sets, line2.from, line2.to, {
        point() {
        },
        span(fromDoc, toDoc, active2, open) {
          let from = fromDoc - line2.from, to2 = toDoc - line2.from;
          let level = result2;
          for (let i2 = active2.length - 1; i2 >= 0; i2--, open--) {
            let direction = active2[i2].spec.bidiIsolate, update;
            if (direction == null)
              direction = autoDirection(line2.text, from, to2);
            if (open > 0 && level.length && (update = level[level.length - 1]).to == from && update.direction == direction) {
              update.to = to2;
              level = update.inner;
            } else {
              let add2 = { from, to: to2, direction, inner: [] };
              level.push(add2);
              level = add2.inner;
            }
          }
        }
      });
      return result2;
    }
    const scrollMargins = /* @__PURE__ */ Facet.define();
    function getScrollMargins(view) {
      let left = 0, right = 0, top2 = 0, bottom = 0;
      for (let source2 of view.state.facet(scrollMargins)) {
        let m = source2(view);
        if (m) {
          if (m.left != null)
            left = Math.max(left, m.left);
          if (m.right != null)
            right = Math.max(right, m.right);
          if (m.top != null)
            top2 = Math.max(top2, m.top);
          if (m.bottom != null)
            bottom = Math.max(bottom, m.bottom);
        }
      }
      return { left, right, top: top2, bottom };
    }
    const styleModule = /* @__PURE__ */ Facet.define();
    class ChangedRange {
      constructor(fromA, toA, fromB, toB) {
        this.fromA = fromA;
        this.toA = toA;
        this.fromB = fromB;
        this.toB = toB;
      }
      join(other) {
        return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));
      }
      addToSet(set) {
        let i2 = set.length, me = this;
        for (; i2 > 0; i2--) {
          let range = set[i2 - 1];
          if (range.fromA > me.toA)
            continue;
          if (range.toA < me.fromA)
            break;
          me = me.join(range);
          set.splice(i2 - 1, 1);
        }
        set.splice(i2, 0, me);
        return set;
      }
      static extendWithRanges(diff2, ranges) {
        if (ranges.length == 0)
          return diff2;
        let result2 = [];
        for (let dI = 0, rI = 0, posA = 0, posB = 0; ; dI++) {
          let next = dI == diff2.length ? null : diff2[dI], off = posA - posB;
          let end = next ? next.fromB : 1e9;
          while (rI < ranges.length && ranges[rI] < end) {
            let from = ranges[rI], to2 = ranges[rI + 1];
            let fromB = Math.max(posB, from), toB = Math.min(end, to2);
            if (fromB <= toB)
              new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result2);
            if (to2 > end)
              break;
            else
              rI += 2;
          }
          if (!next)
            return result2;
          new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result2);
          posA = next.toA;
          posB = next.toB;
        }
      }
    }
    class ViewUpdate {
      constructor(view, state, transactions) {
        this.view = view;
        this.state = state;
        this.transactions = transactions;
        this.flags = 0;
        this.startState = view.state;
        this.changes = ChangeSet.empty(this.startState.doc.length);
        for (let tr2 of transactions)
          this.changes = this.changes.compose(tr2.changes);
        let changedRanges = [];
        this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
        this.changedRanges = changedRanges;
      }
      /**
      @internal
      */
      static create(view, state, transactions) {
        return new ViewUpdate(view, state, transactions);
      }
      /**
      Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
      [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
      update.
      */
      get viewportChanged() {
        return (this.flags & 4) > 0;
      }
      /**
      Returns true when
      [`viewportChanged`](https://codemirror.net/6/docs/ref/#view.ViewUpdate.viewportChanged) is true
      and the viewport change is not just the result of mapping it in
      response to document changes.
      */
      get viewportMoved() {
        return (this.flags & 8) > 0;
      }
      /**
      Indicates whether the height of a block element in the editor
      changed in this update.
      */
      get heightChanged() {
        return (this.flags & 2) > 0;
      }
      /**
      Returns true when the document was modified or the size of the
      editor, or elements within the editor, changed.
      */
      get geometryChanged() {
        return this.docChanged || (this.flags & (16 | 2)) > 0;
      }
      /**
      True when this update indicates a focus change.
      */
      get focusChanged() {
        return (this.flags & 1) > 0;
      }
      /**
      Whether the document changed in this update.
      */
      get docChanged() {
        return !this.changes.empty;
      }
      /**
      Whether the selection was explicitly set in this update.
      */
      get selectionSet() {
        return this.transactions.some((tr2) => tr2.selection);
      }
      /**
      @internal
      */
      get empty() {
        return this.flags == 0 && this.transactions.length == 0;
      }
    }
    class DocView extends ContentView {
      get length() {
        return this.view.state.doc.length;
      }
      constructor(view) {
        super();
        this.view = view;
        this.decorations = [];
        this.dynamicDecorationMap = [false];
        this.domChanged = null;
        this.hasComposition = null;
        this.markedForComposition = /* @__PURE__ */ new Set();
        this.editContextFormatting = Decoration.none;
        this.lastCompositionAfterCursor = false;
        this.minWidth = 0;
        this.minWidthFrom = 0;
        this.minWidthTo = 0;
        this.impreciseAnchor = null;
        this.impreciseHead = null;
        this.forceSelection = false;
        this.lastUpdate = Date.now();
        this.setDOM(view.contentDOM);
        this.children = [new LineView()];
        this.children[0].setParent(this);
        this.updateDeco();
        this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0, null);
      }
      // Update the document view to a given state.
      update(update) {
        var _a2;
        let changedRanges = update.changedRanges;
        if (this.minWidth > 0 && changedRanges.length) {
          if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
            this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
          } else {
            this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
            this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
          }
        }
        this.updateEditContextFormatting(update);
        let readCompositionAt = -1;
        if (this.view.inputState.composing >= 0 && !this.view.observer.editContext) {
          if ((_a2 = this.domChanged) === null || _a2 === void 0 ? void 0 : _a2.newSel)
            readCompositionAt = this.domChanged.newSel.head;
          else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet)
            readCompositionAt = update.state.selection.main.head;
        }
        let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;
        this.domChanged = null;
        if (this.hasComposition) {
          this.markedForComposition.clear();
          let { from, to: to2 } = this.hasComposition;
          changedRanges = new ChangedRange(from, to2, update.changes.mapPos(from, -1), update.changes.mapPos(to2, 1)).addToSet(changedRanges.slice());
        }
        this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
        if ((browser.ie || browser.chrome) && !composition && update && update.state.doc.lines != update.startState.doc.lines)
          this.forceSelection = true;
        let prevDeco = this.decorations, deco = this.updateDeco();
        let decoDiff = findChangedDeco(prevDeco, deco, update.changes);
        changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
        if (!(this.flags & 7) && changedRanges.length == 0) {
          return false;
        } else {
          this.updateInner(changedRanges, update.startState.doc.length, composition);
          if (update.transactions.length)
            this.lastUpdate = Date.now();
          return true;
        }
      }
      // Used by update and the constructor do perform the actual DOM
      // update
      updateInner(changes, oldLength, composition) {
        this.view.viewState.mustMeasureContent = true;
        this.updateChildren(changes, oldLength, composition);
        let { observer } = this.view;
        observer.ignore(() => {
          this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
          this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
          let track2 = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : void 0;
          this.sync(this.view, track2);
          this.flags &= -8;
          if (track2 && (track2.written || observer.selectionRange.focusNode != track2.node))
            this.forceSelection = true;
          this.dom.style.height = "";
        });
        this.markedForComposition.forEach(
          (cView) => cView.flags &= -9
          /* ViewFlag.Composition */
        );
        let gaps = [];
        if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) {
          for (let child of this.children)
            if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget)
              gaps.push(child.dom);
        }
        observer.updateGaps(gaps);
      }
      updateChildren(changes, oldLength, composition) {
        let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;
        let cursor = this.childCursor(oldLength);
        for (let i2 = ranges.length - 1; ; i2--) {
          let next = i2 >= 0 ? ranges[i2] : null;
          if (!next)
            break;
          let { fromA, toA, fromB, toB } = next, content2, breakAtStart, openStart, openEnd;
          if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {
            let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);
            let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);
            breakAtStart = before.breakAtStart;
            openStart = before.openStart;
            openEnd = after.openEnd;
            let compLine = this.compositionView(composition);
            if (after.breakAtStart) {
              compLine.breakAfter = 1;
            } else if (after.content.length && compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {
              compLine.breakAfter = after.content[0].breakAfter;
              after.content.shift();
            }
            if (before.content.length && compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) {
              before.content.pop();
            }
            content2 = before.content.concat(compLine).concat(after.content);
          } else {
            ({ content: content2, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));
          }
          let { i: toI, off: toOff } = cursor.findPos(toA, 1);
          let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);
          replaceRange(this, fromI, fromOff, toI, toOff, content2, breakAtStart, openStart, openEnd);
        }
        if (composition)
          this.fixCompositionDOM(composition);
      }
      updateEditContextFormatting(update) {
        this.editContextFormatting = this.editContextFormatting.map(update.changes);
        for (let tr2 of update.transactions)
          for (let effect of tr2.effects)
            if (effect.is(setEditContextFormatting)) {
              this.editContextFormatting = effect.value;
            }
      }
      compositionView(composition) {
        let cur2 = new TextView(composition.text.nodeValue);
        cur2.flags |= 8;
        for (let { deco } of composition.marks)
          cur2 = new MarkView(deco, [cur2], cur2.length);
        let line2 = new LineView();
        line2.append(cur2, 0);
        return line2;
      }
      fixCompositionDOM(composition) {
        let fix = (dom, cView2) => {
          cView2.flags |= 8 | (cView2.children.some(
            (c2) => c2.flags & 7
            /* ViewFlag.Dirty */
          ) ? 1 : 0);
          this.markedForComposition.add(cView2);
          let prev = ContentView.get(dom);
          if (prev && prev != cView2)
            prev.dom = null;
          cView2.setDOM(dom);
        };
        let pos2 = this.childPos(composition.range.fromB, 1);
        let cView = this.children[pos2.i];
        fix(composition.line, cView);
        for (let i2 = composition.marks.length - 1; i2 >= -1; i2--) {
          pos2 = cView.childPos(pos2.off, 1);
          cView = cView.children[pos2.i];
          fix(i2 >= 0 ? composition.marks[i2].node : composition.text, cView);
        }
      }
      // Sync the DOM selection to this.state.selection
      updateSelection(mustRead = false, fromPointer = false) {
        if (mustRead || !this.view.observer.selectionRange.focusNode)
          this.view.observer.readSelectionRange();
        let activeElt = this.view.root.activeElement, focused = activeElt == this.dom;
        let selectionNotFocus = !focused && !(this.view.state.facet(editable) || this.dom.tabIndex > -1) && hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));
        if (!(focused || fromPointer || selectionNotFocus))
          return;
        let force = this.forceSelection;
        this.forceSelection = false;
        let main = this.view.state.selection.main;
        let anchor = this.moveToLine(this.domAtPos(main.anchor));
        let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));
        if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {
          let dummy = document.createTextNode("");
          this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
          anchor = head = new DOMPos(dummy, 0);
          force = true;
        }
        let domSel = this.view.observer.selectionRange;
        if (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) {
          this.view.observer.ignore(() => {
            if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && inUneditable(domSel.focusNode, this.dom)) {
              this.dom.blur();
              this.dom.focus({ preventScroll: true });
            }
            let rawSel = getSelection(this.view.root);
            if (!rawSel) ;
            else if (main.empty) {
              if (browser.gecko) {
                let nextTo = nextToUneditable(anchor.node, anchor.offset);
                if (nextTo && nextTo != (1 | 2)) {
                  let text2 = (nextTo == 1 ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);
                  if (text2)
                    anchor = new DOMPos(text2.node, text2.offset);
                }
              }
              rawSel.collapse(anchor.node, anchor.offset);
              if (main.bidiLevel != null && rawSel.caretBidiLevel !== void 0)
                rawSel.caretBidiLevel = main.bidiLevel;
            } else if (rawSel.extend) {
              rawSel.collapse(anchor.node, anchor.offset);
              try {
                rawSel.extend(head.node, head.offset);
              } catch (_) {
              }
            } else {
              let range = document.createRange();
              if (main.anchor > main.head)
                [anchor, head] = [head, anchor];
              range.setEnd(head.node, head.offset);
              range.setStart(anchor.node, anchor.offset);
              rawSel.removeAllRanges();
              rawSel.addRange(range);
            }
            if (selectionNotFocus && this.view.root.activeElement == this.dom) {
              this.dom.blur();
              if (activeElt)
                activeElt.focus();
            }
          });
          this.view.observer.setSelectionRange(anchor, head);
        }
        this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
        this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
      }
      // If a zero-length widget is inserted next to the cursor during
      // composition, avoid moving it across it and disrupting the
      // composition.
      suppressWidgetCursorChange(sel, cursor) {
        return this.hasComposition && cursor.empty && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) && this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head;
      }
      enforceCursorAssoc() {
        if (this.hasComposition)
          return;
        let { view } = this, cursor = view.state.selection.main;
        let sel = getSelection(view.root);
        let { anchorNode, anchorOffset } = view.observer.selectionRange;
        if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)
          return;
        let line2 = LineView.find(this, cursor.head);
        if (!line2)
          return;
        let lineStart = line2.posAtStart;
        if (cursor.head == lineStart || cursor.head == lineStart + line2.length)
          return;
        let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);
        if (!before || !after || before.bottom > after.top)
          return;
        let dom = this.domAtPos(cursor.head + cursor.assoc);
        sel.collapse(dom.node, dom.offset);
        sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
        view.observer.readSelectionRange();
        let newRange = view.observer.selectionRange;
        if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)
          sel.collapse(anchorNode, anchorOffset);
      }
      // If a position is in/near a block widget, move it to a nearby text
      // line, since we don't want the cursor inside a block widget.
      moveToLine(pos2) {
        let dom = this.dom, newPos;
        if (pos2.node != dom)
          return pos2;
        for (let i2 = pos2.offset; !newPos && i2 < dom.childNodes.length; i2++) {
          let view = ContentView.get(dom.childNodes[i2]);
          if (view instanceof LineView)
            newPos = view.domAtPos(0);
        }
        for (let i2 = pos2.offset - 1; !newPos && i2 >= 0; i2--) {
          let view = ContentView.get(dom.childNodes[i2]);
          if (view instanceof LineView)
            newPos = view.domAtPos(view.length);
        }
        return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos2;
      }
      nearest(dom) {
        for (let cur2 = dom; cur2; ) {
          let domView = ContentView.get(cur2);
          if (domView && domView.rootView == this)
            return domView;
          cur2 = cur2.parentNode;
        }
        return null;
      }
      posFromDOM(node2, offset) {
        let view = this.nearest(node2);
        if (!view)
          throw new RangeError("Trying to find position for a DOM position outside of the document");
        return view.localPosFromDOM(node2, offset) + view.posAtStart;
      }
      domAtPos(pos2) {
        let { i: i2, off } = this.childCursor().findPos(pos2, -1);
        for (; i2 < this.children.length - 1; ) {
          let child = this.children[i2];
          if (off < child.length || child instanceof LineView)
            break;
          i2++;
          off = 0;
        }
        return this.children[i2].domAtPos(off);
      }
      coordsAt(pos2, side) {
        let best = null, bestPos = 0;
        for (let off = this.length, i2 = this.children.length - 1; i2 >= 0; i2--) {
          let child = this.children[i2], end = off - child.breakAfter, start = end - child.length;
          if (end < pos2)
            break;
          if (start <= pos2 && (start < pos2 || child.covers(-1)) && (end > pos2 || child.covers(1)) && (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {
            best = child;
            bestPos = start;
          } else if (best && start == pos2 && end == pos2 && child instanceof BlockWidgetView && Math.abs(side) < 2) {
            if (child.deco.startSide < 0)
              break;
            else if (i2)
              best = null;
          }
          off = start;
        }
        return best ? best.coordsAt(pos2 - bestPos, side) : null;
      }
      coordsForChar(pos2) {
        let { i: i2, off } = this.childPos(pos2, 1), child = this.children[i2];
        if (!(child instanceof LineView))
          return null;
        while (child.children.length) {
          let { i: i3, off: childOff } = child.childPos(off, 1);
          for (; ; i3++) {
            if (i3 == child.children.length)
              return null;
            if ((child = child.children[i3]).length)
              break;
          }
          off = childOff;
        }
        if (!(child instanceof TextView))
          return null;
        let end = findClusterBreak(child.text, off);
        if (end == off)
          return null;
        let rects = textRange(child.dom, off, end).getClientRects();
        for (let i3 = 0; i3 < rects.length; i3++) {
          let rect = rects[i3];
          if (i3 == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)
            return rect;
        }
        return null;
      }
      measureVisibleLineHeights(viewport) {
        let result2 = [], { from, to: to2 } = viewport;
        let contentWidth = this.view.contentDOM.clientWidth;
        let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
        let widest = -1, ltr = this.view.textDirection == Direction.LTR;
        for (let pos2 = 0, i2 = 0; i2 < this.children.length; i2++) {
          let child = this.children[i2], end = pos2 + child.length;
          if (end > to2)
            break;
          if (pos2 >= from) {
            let childRect = child.dom.getBoundingClientRect();
            result2.push(childRect.height);
            if (isWider) {
              let last = child.dom.lastChild;
              let rects = last ? clientRectsFor(last) : [];
              if (rects.length) {
                let rect = rects[rects.length - 1];
                let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
                if (width > widest) {
                  widest = width;
                  this.minWidth = contentWidth;
                  this.minWidthFrom = pos2;
                  this.minWidthTo = end;
                }
              }
            }
          }
          pos2 = end + child.breakAfter;
        }
        return result2;
      }
      textDirectionAt(pos2) {
        let { i: i2 } = this.childPos(pos2, 1);
        return getComputedStyle(this.children[i2].dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
      }
      measureTextSize() {
        for (let child of this.children) {
          if (child instanceof LineView) {
            let measure = child.measureTextSize();
            if (measure)
              return measure;
          }
        }
        let dummy = document.createElement("div"), lineHeight, charWidth, textHeight;
        dummy.className = "cm-line";
        dummy.style.width = "99999px";
        dummy.style.position = "absolute";
        dummy.textContent = "abc def ghi jkl mno pqr stu";
        this.view.observer.ignore(() => {
          this.dom.appendChild(dummy);
          let rect = clientRectsFor(dummy.firstChild)[0];
          lineHeight = dummy.getBoundingClientRect().height;
          charWidth = rect ? rect.width / 27 : 7;
          textHeight = rect ? rect.height : lineHeight;
          dummy.remove();
        });
        return { lineHeight, charWidth, textHeight };
      }
      childCursor(pos2 = this.length) {
        let i2 = this.children.length;
        if (i2)
          pos2 -= this.children[--i2].length;
        return new ChildCursor(this.children, pos2, i2);
      }
      computeBlockGapDeco() {
        let deco = [], vs = this.view.viewState;
        for (let pos2 = 0, i2 = 0; ; i2++) {
          let next = i2 == vs.viewports.length ? null : vs.viewports[i2];
          let end = next ? next.from - 1 : this.length;
          if (end > pos2) {
            let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos2).top) / this.view.scaleY;
            deco.push(Decoration.replace({
              widget: new BlockGapWidget(height),
              block: true,
              inclusive: true,
              isBlockGap: true
            }).range(pos2, end));
          }
          if (!next)
            break;
          pos2 = next.to + 1;
        }
        return Decoration.set(deco);
      }
      updateDeco() {
        let i2 = 1;
        let allDeco = this.view.state.facet(decorations).map((d) => {
          let dynamic = this.dynamicDecorationMap[i2++] = typeof d == "function";
          return dynamic ? d(this.view) : d;
        });
        let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d, i3) => {
          let dynamic = typeof d == "function";
          if (dynamic)
            dynamicOuter = true;
          return dynamic ? d(this.view) : d;
        });
        if (outerDeco.length) {
          this.dynamicDecorationMap[i2++] = dynamicOuter;
          allDeco.push(RangeSet.join(outerDeco));
        }
        this.decorations = [
          this.editContextFormatting,
          ...allDeco,
          this.computeBlockGapDeco(),
          this.view.viewState.lineGapDeco
        ];
        while (i2 < this.decorations.length)
          this.dynamicDecorationMap[i2++] = false;
        return this.decorations;
      }
      scrollIntoView(target2) {
        if (target2.isSnapshot) {
          let ref = this.view.viewState.lineBlockAt(target2.range.head);
          this.view.scrollDOM.scrollTop = ref.top - target2.yMargin;
          this.view.scrollDOM.scrollLeft = target2.xMargin;
          return;
        }
        for (let handler of this.view.state.facet(scrollHandler)) {
          try {
            if (handler(this.view, target2.range, target2))
              return true;
          } catch (e) {
            logException(this.view.state, e, "scroll handler");
          }
        }
        let { range } = target2;
        let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;
        if (!rect)
          return;
        if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))
          rect = {
            left: Math.min(rect.left, other.left),
            top: Math.min(rect.top, other.top),
            right: Math.max(rect.right, other.right),
            bottom: Math.max(rect.bottom, other.bottom)
          };
        let margins = getScrollMargins(this.view);
        let targetRect = {
          left: rect.left - margins.left,
          top: rect.top - margins.top,
          right: rect.right + margins.right,
          bottom: rect.bottom + margins.bottom
        };
        let { offsetWidth, offsetHeight } = this.view.scrollDOM;
        scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target2.x, target2.y, Math.max(Math.min(target2.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target2.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
      }
    }
    function betweenUneditable(pos2) {
      return pos2.node.nodeType == 1 && pos2.node.firstChild && (pos2.offset == 0 || pos2.node.childNodes[pos2.offset - 1].contentEditable == "false") && (pos2.offset == pos2.node.childNodes.length || pos2.node.childNodes[pos2.offset].contentEditable == "false");
    }
    function findCompositionNode(view, headPos) {
      let sel = view.observer.selectionRange;
      if (!sel.focusNode)
        return null;
      let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);
      let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);
      let textNode = textBefore || textAfter;
      if (textAfter && textBefore && textAfter.node != textBefore.node) {
        let descAfter = ContentView.get(textAfter.node);
        if (!descAfter || descAfter instanceof TextView && descAfter.text != textAfter.node.nodeValue) {
          textNode = textAfter;
        } else if (view.docView.lastCompositionAfterCursor) {
          let descBefore = ContentView.get(textBefore.node);
          if (!(!descBefore || descBefore instanceof TextView && descBefore.text != textBefore.node.nodeValue))
            textNode = textAfter;
        }
      }
      view.docView.lastCompositionAfterCursor = textNode != textBefore;
      if (!textNode)
        return null;
      let from = headPos - textNode.offset;
      return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };
    }
    function findCompositionRange(view, changes, headPos) {
      let found = findCompositionNode(view, headPos);
      if (!found)
        return null;
      let { node: textNode, from, to: to2 } = found, text2 = textNode.nodeValue;
      if (/[\n\r]/.test(text2))
        return null;
      if (view.state.doc.sliceString(found.from, found.to) != text2)
        return null;
      let inv = changes.invertedDesc;
      let range = new ChangedRange(inv.mapPos(from), inv.mapPos(to2), from, to2);
      let marks = [];
      for (let parent = textNode.parentNode; ; parent = parent.parentNode) {
        let parentView = ContentView.get(parent);
        if (parentView instanceof MarkView)
          marks.push({ node: parent, deco: parentView.mark });
        else if (parentView instanceof LineView || parent.nodeName == "DIV" && parent.parentNode == view.contentDOM)
          return { range, text: textNode, marks, line: parent };
        else if (parent != view.contentDOM)
          marks.push({ node: parent, deco: new MarkDecoration({
            inclusive: true,
            attributes: getAttrs(parent),
            tagName: parent.tagName.toLowerCase()
          }) });
        else
          return null;
      }
    }
    function nextToUneditable(node2, offset) {
      if (node2.nodeType != 1)
        return 0;
      return (offset && node2.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node2.childNodes.length && node2.childNodes[offset].contentEditable == "false" ? 2 : 0);
    }
    let DecorationComparator$1 = class DecorationComparator {
      constructor() {
        this.changes = [];
      }
      compareRange(from, to2) {
        addRange(from, to2, this.changes);
      }
      comparePoint(from, to2) {
        addRange(from, to2, this.changes);
      }
      boundChange(pos2) {
        addRange(pos2, pos2, this.changes);
      }
    };
    function findChangedDeco(a, b, diff2) {
      let comp = new DecorationComparator$1();
      RangeSet.compare(a, b, diff2, comp);
      return comp.changes;
    }
    function inUneditable(node2, inside2) {
      for (let cur2 = node2; cur2 && cur2 != inside2; cur2 = cur2.assignedSlot || cur2.parentNode) {
        if (cur2.nodeType == 1 && cur2.contentEditable == "false") {
          return true;
        }
      }
      return false;
    }
    function touchesComposition(changes, composition) {
      let touched = false;
      if (composition)
        changes.iterChangedRanges((from, to2) => {
          if (from < composition.to && to2 > composition.from)
            touched = true;
        });
      return touched;
    }
    function groupAt(state, pos2, bias = 1) {
      let categorize = state.charCategorizer(pos2);
      let line2 = state.doc.lineAt(pos2), linePos = pos2 - line2.from;
      if (line2.length == 0)
        return EditorSelection.cursor(pos2);
      if (linePos == 0)
        bias = 1;
      else if (linePos == line2.length)
        bias = -1;
      let from = linePos, to2 = linePos;
      if (bias < 0)
        from = findClusterBreak(line2.text, linePos, false);
      else
        to2 = findClusterBreak(line2.text, linePos);
      let cat = categorize(line2.text.slice(from, to2));
      while (from > 0) {
        let prev = findClusterBreak(line2.text, from, false);
        if (categorize(line2.text.slice(prev, from)) != cat)
          break;
        from = prev;
      }
      while (to2 < line2.length) {
        let next = findClusterBreak(line2.text, to2);
        if (categorize(line2.text.slice(to2, next)) != cat)
          break;
        to2 = next;
      }
      return EditorSelection.range(from + line2.from, to2 + line2.from);
    }
    function getdx(x2, rect) {
      return rect.left > x2 ? rect.left - x2 : Math.max(0, x2 - rect.right);
    }
    function getdy(y, rect) {
      return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);
    }
    function yOverlap(a, b) {
      return a.top < b.bottom - 1 && a.bottom > b.top + 1;
    }
    function upTop(rect, top2) {
      return top2 < rect.top ? { top: top2, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;
    }
    function upBot(rect, bottom) {
      return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect;
    }
    function domPosAtCoords(parent, x2, y) {
      let closest, closestRect, closestX, closestY, closestOverlap = false;
      let above, below, aboveRect, belowRect;
      for (let child = parent.firstChild; child; child = child.nextSibling) {
        let rects = clientRectsFor(child);
        for (let i2 = 0; i2 < rects.length; i2++) {
          let rect = rects[i2];
          if (closestRect && yOverlap(closestRect, rect))
            rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);
          let dx = getdx(x2, rect), dy = getdy(y, rect);
          if (dx == 0 && dy == 0)
            return child.nodeType == 3 ? domPosInText(child, x2, y) : domPosAtCoords(child, x2, y);
          if (!closest || closestY > dy || closestY == dy && closestX > dx) {
            closest = child;
            closestRect = rect;
            closestX = dx;
            closestY = dy;
            let side = dy ? y < rect.top ? -1 : 1 : dx ? x2 < rect.left ? -1 : 1 : 0;
            closestOverlap = !side || (side > 0 ? i2 < rects.length - 1 : i2 > 0);
          }
          if (dx == 0) {
            if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
              above = child;
              aboveRect = rect;
            } else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {
              below = child;
              belowRect = rect;
            }
          } else if (aboveRect && yOverlap(aboveRect, rect)) {
            aboveRect = upBot(aboveRect, rect.bottom);
          } else if (belowRect && yOverlap(belowRect, rect)) {
            belowRect = upTop(belowRect, rect.top);
          }
        }
      }
      if (aboveRect && aboveRect.bottom >= y) {
        closest = above;
        closestRect = aboveRect;
      } else if (belowRect && belowRect.top <= y) {
        closest = below;
        closestRect = belowRect;
      }
      if (!closest)
        return { node: parent, offset: 0 };
      let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x2));
      if (closest.nodeType == 3)
        return domPosInText(closest, clipX, y);
      if (closestOverlap && closest.contentEditable != "false")
        return domPosAtCoords(closest, clipX, y);
      let offset = Array.prototype.indexOf.call(parent.childNodes, closest) + (x2 >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);
      return { node: parent, offset };
    }
    function domPosInText(node2, x2, y) {
      let len = node2.nodeValue.length;
      let closestOffset = -1, closestDY = 1e9, generalSide = 0;
      for (let i2 = 0; i2 < len; i2++) {
        let rects = textRange(node2, i2, i2 + 1).getClientRects();
        for (let j2 = 0; j2 < rects.length; j2++) {
          let rect = rects[j2];
          if (rect.top == rect.bottom)
            continue;
          if (!generalSide)
            generalSide = x2 - rect.left;
          let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;
          if (rect.left - 1 <= x2 && rect.right + 1 >= x2 && dy < closestDY) {
            let right = x2 >= (rect.left + rect.right) / 2, after = right;
            if (browser.chrome || browser.gecko) {
              let rectBefore = textRange(node2, i2).getBoundingClientRect();
              if (rectBefore.left == rect.right)
                after = !right;
            }
            if (dy <= 0)
              return { node: node2, offset: i2 + (after ? 1 : 0) };
            closestOffset = i2 + (after ? 1 : 0);
            closestDY = dy;
          }
        }
      }
      return { node: node2, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node2.nodeValue.length : 0 };
    }
    function posAtCoords(view, coords, precise, bias = -1) {
      var _a2, _b2;
      let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop;
      let block2, { docHeight } = view.viewState;
      let { x: x2, y } = coords, yOffset = y - docTop;
      if (yOffset < 0)
        return 0;
      if (yOffset > docHeight)
        return view.state.doc.length;
      for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false; ; ) {
        block2 = view.elementAtHeight(yOffset);
        if (block2.type == BlockType.Text)
          break;
        for (; ; ) {
          yOffset = bias > 0 ? block2.bottom + halfLine : block2.top - halfLine;
          if (yOffset >= 0 && yOffset <= docHeight)
            break;
          if (bounced)
            return precise ? null : 0;
          bounced = true;
          bias = -bias;
        }
      }
      y = docTop + yOffset;
      let lineStart = block2.from;
      if (lineStart < view.viewport.from)
        return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content2, block2, x2, y);
      if (lineStart > view.viewport.to)
        return view.viewport.to == view.state.doc.length ? view.state.doc.length : precise ? null : posAtCoordsImprecise(view, content2, block2, x2, y);
      let doc2 = view.dom.ownerDocument;
      let root2 = view.root.elementFromPoint ? view.root : doc2;
      let element = root2.elementFromPoint(x2, y);
      if (element && !view.contentDOM.contains(element))
        element = null;
      if (!element) {
        x2 = Math.max(content2.left + 1, Math.min(content2.right - 1, x2));
        element = root2.elementFromPoint(x2, y);
        if (element && !view.contentDOM.contains(element))
          element = null;
      }
      let node2, offset = -1;
      if (element && ((_a2 = view.docView.nearest(element)) === null || _a2 === void 0 ? void 0 : _a2.isEditable) != false) {
        if (doc2.caretPositionFromPoint) {
          let pos2 = doc2.caretPositionFromPoint(x2, y);
          if (pos2)
            ({ offsetNode: node2, offset } = pos2);
        } else if (doc2.caretRangeFromPoint) {
          let range = doc2.caretRangeFromPoint(x2, y);
          if (range) {
            ({ startContainer: node2, startOffset: offset } = range);
            if (!view.contentDOM.contains(node2) || browser.safari && isSuspiciousSafariCaretResult(node2, offset, x2) || browser.chrome && isSuspiciousChromeCaretResult(node2, offset, x2))
              node2 = void 0;
          }
        }
        if (node2)
          offset = Math.min(maxOffset(node2), offset);
      }
      if (!node2 || !view.docView.dom.contains(node2)) {
        let line2 = LineView.find(view.docView, lineStart);
        if (!line2)
          return yOffset > block2.top + block2.height / 2 ? block2.to : block2.from;
        ({ node: node2, offset } = domPosAtCoords(line2.dom, x2, y));
      }
      let nearest = view.docView.nearest(node2);
      if (!nearest)
        return null;
      if (nearest.isWidget && ((_b2 = nearest.dom) === null || _b2 === void 0 ? void 0 : _b2.nodeType) == 1) {
        let rect = nearest.dom.getBoundingClientRect();
        return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2 ? nearest.posAtStart : nearest.posAtEnd;
      } else {
        return nearest.localPosFromDOM(node2, offset) + nearest.posAtStart;
      }
    }
    function posAtCoordsImprecise(view, contentRect, block2, x2, y) {
      let into = Math.round((x2 - contentRect.left) * view.defaultCharacterWidth);
      if (view.lineWrapping && block2.height > view.defaultLineHeight * 1.5) {
        let textHeight = view.viewState.heightOracle.textHeight;
        let line2 = Math.floor((y - block2.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
        into += line2 * view.viewState.heightOracle.lineLength;
      }
      let content2 = view.state.sliceDoc(block2.from, block2.to);
      return block2.from + findColumn(content2, into, view.state.tabSize);
    }
    function isSuspiciousSafariCaretResult(node2, offset, x2) {
      let len;
      if (node2.nodeType != 3 || offset != (len = node2.nodeValue.length))
        return false;
      for (let next = node2.nextSibling; next; next = next.nextSibling)
        if (next.nodeType != 1 || next.nodeName != "BR")
          return false;
      return textRange(node2, len - 1, len).getBoundingClientRect().left > x2;
    }
    function isSuspiciousChromeCaretResult(node2, offset, x2) {
      if (offset != 0)
        return false;
      for (let cur2 = node2; ; ) {
        let parent = cur2.parentNode;
        if (!parent || parent.nodeType != 1 || parent.firstChild != cur2)
          return false;
        if (parent.classList.contains("cm-line"))
          break;
        cur2 = parent;
      }
      let rect = node2.nodeType == 1 ? node2.getBoundingClientRect() : textRange(node2, 0, Math.max(node2.nodeValue.length, 1)).getBoundingClientRect();
      return x2 - rect.left > 5;
    }
    function blockAt(view, pos2) {
      let line2 = view.lineBlockAt(pos2);
      if (Array.isArray(line2.type))
        for (let l of line2.type) {
          if (l.to > pos2 || l.to == pos2 && (l.to == line2.to || l.type == BlockType.Text))
            return l;
        }
      return line2;
    }
    function moveToLineBoundary(view, start, forward, includeWrap) {
      let line2 = blockAt(view, start.head);
      let coords = !includeWrap || line2.type != BlockType.Text || !(view.lineWrapping || line2.widgetLineBreaks) ? null : view.coordsAtPos(start.assoc < 0 && start.head > line2.from ? start.head - 1 : start.head);
      if (coords) {
        let editorRect = view.dom.getBoundingClientRect();
        let direction = view.textDirectionAt(line2.from);
        let pos2 = view.posAtCoords({
          x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
          y: (coords.top + coords.bottom) / 2
        });
        if (pos2 != null)
          return EditorSelection.cursor(pos2, forward ? -1 : 1);
      }
      return EditorSelection.cursor(forward ? line2.to : line2.from, forward ? -1 : 1);
    }
    function moveByChar(view, start, forward, by) {
      let line2 = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line2);
      let direction = view.textDirectionAt(line2.from);
      for (let cur2 = start, check = null; ; ) {
        let next = moveVisually(line2, spans, direction, cur2, forward), char = movedOver;
        if (!next) {
          if (line2.number == (forward ? view.state.doc.lines : 1))
            return cur2;
          char = "\n";
          line2 = view.state.doc.line(line2.number + (forward ? 1 : -1));
          spans = view.bidiSpans(line2);
          next = view.visualLineSide(line2, !forward);
        }
        if (!check) {
          if (!by)
            return next;
          check = by(char);
        } else if (!check(char)) {
          return cur2;
        }
        cur2 = next;
      }
    }
    function byGroup(view, pos2, start) {
      let categorize = view.state.charCategorizer(pos2);
      let cat = categorize(start);
      return (next) => {
        let nextCat = categorize(next);
        if (cat == CharCategory.Space)
          cat = nextCat;
        return cat == nextCat;
      };
    }
    function moveVertically(view, start, forward, distance) {
      let startPos = start.head, dir = forward ? 1 : -1;
      if (startPos == (forward ? view.state.doc.length : 0))
        return EditorSelection.cursor(startPos, start.assoc);
      let goal = start.goalColumn, startY;
      let rect = view.contentDOM.getBoundingClientRect();
      let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;
      if (startCoords) {
        if (goal == null)
          goal = startCoords.left - rect.left;
        startY = dir < 0 ? startCoords.top : startCoords.bottom;
      } else {
        let line2 = view.viewState.lineBlockAt(startPos);
        if (goal == null)
          goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line2.from));
        startY = (dir < 0 ? line2.top : line2.bottom) + docTop;
      }
      let resolvedGoal = rect.left + goal;
      let dist2 = distance !== null && distance !== void 0 ? distance : view.viewState.heightOracle.textHeight >> 1;
      for (let extra = 0; ; extra += 10) {
        let curY = startY + (dist2 + extra) * dir;
        let pos2 = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
        if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos2 < startPos : pos2 > startPos)) {
          let charRect = view.docView.coordsForChar(pos2);
          let assoc = !charRect || curY < charRect.top ? -1 : 1;
          return EditorSelection.cursor(pos2, assoc, void 0, goal);
        }
      }
    }
    function skipAtomicRanges(atoms, pos2, bias) {
      for (; ; ) {
        let moved = 0;
        for (let set of atoms) {
          set.between(pos2 - 1, pos2 + 1, (from, to2, value2) => {
            if (pos2 > from && pos2 < to2) {
              let side = moved || bias || (pos2 - from < to2 - pos2 ? -1 : 1);
              pos2 = side < 0 ? from : to2;
              moved = side;
            }
          });
        }
        if (!moved)
          return pos2;
      }
    }
    function skipAtoms(view, oldPos, pos2) {
      let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map((f) => f(view)), pos2.from, oldPos.head > pos2.from ? -1 : 1);
      return newPos == pos2.from ? pos2 : EditorSelection.cursor(newPos, newPos < pos2.from ? 1 : -1);
    }
    const LineBreakPlaceholder = "";
    class DOMReader {
      constructor(points, state) {
        this.points = points;
        this.text = "";
        this.lineSeparator = state.facet(EditorState.lineSeparator);
      }
      append(text2) {
        this.text += text2;
      }
      lineBreak() {
        this.text += LineBreakPlaceholder;
      }
      readRange(start, end) {
        if (!start)
          return this;
        let parent = start.parentNode;
        for (let cur2 = start; ; ) {
          this.findPointBefore(parent, cur2);
          let oldLen = this.text.length;
          this.readNode(cur2);
          let next = cur2.nextSibling;
          if (next == end)
            break;
          let view = ContentView.get(cur2), nextView = ContentView.get(next);
          if (view && nextView ? view.breakAfter : (view ? view.breakAfter : isBlockElement(cur2)) || isBlockElement(next) && (cur2.nodeName != "BR" || cur2.cmIgnore) && this.text.length > oldLen)
            this.lineBreak();
          cur2 = next;
        }
        this.findPointBefore(parent, end);
        return this;
      }
      readTextNode(node2) {
        let text2 = node2.nodeValue;
        for (let point of this.points)
          if (point.node == node2)
            point.pos = this.text.length + Math.min(point.offset, text2.length);
        for (let off = 0, re2 = this.lineSeparator ? null : /\r\n?|\n/g; ; ) {
          let nextBreak = -1, breakSize = 1, m;
          if (this.lineSeparator) {
            nextBreak = text2.indexOf(this.lineSeparator, off);
            breakSize = this.lineSeparator.length;
          } else if (m = re2.exec(text2)) {
            nextBreak = m.index;
            breakSize = m[0].length;
          }
          this.append(text2.slice(off, nextBreak < 0 ? text2.length : nextBreak));
          if (nextBreak < 0)
            break;
          this.lineBreak();
          if (breakSize > 1) {
            for (let point of this.points)
              if (point.node == node2 && point.pos > this.text.length)
                point.pos -= breakSize - 1;
          }
          off = nextBreak + breakSize;
        }
      }
      readNode(node2) {
        if (node2.cmIgnore)
          return;
        let view = ContentView.get(node2);
        let fromView = view && view.overrideDOMText;
        if (fromView != null) {
          this.findPointInside(node2, fromView.length);
          for (let i2 = fromView.iter(); !i2.next().done; ) {
            if (i2.lineBreak)
              this.lineBreak();
            else
              this.append(i2.value);
          }
        } else if (node2.nodeType == 3) {
          this.readTextNode(node2);
        } else if (node2.nodeName == "BR") {
          if (node2.nextSibling)
            this.lineBreak();
        } else if (node2.nodeType == 1) {
          this.readRange(node2.firstChild, null);
        }
      }
      findPointBefore(node2, next) {
        for (let point of this.points)
          if (point.node == node2 && node2.childNodes[point.offset] == next)
            point.pos = this.text.length;
      }
      findPointInside(node2, length) {
        for (let point of this.points)
          if (node2.nodeType == 3 ? point.node == node2 : node2.contains(point.node))
            point.pos = this.text.length + (isAtEnd(node2, point.node, point.offset) ? length : 0);
      }
    }
    function isAtEnd(parent, node2, offset) {
      for (; ; ) {
        if (!node2 || offset < maxOffset(node2))
          return false;
        if (node2 == parent)
          return true;
        offset = domIndex(node2) + 1;
        node2 = node2.parentNode;
      }
    }
    class DOMPoint {
      constructor(node2, offset) {
        this.node = node2;
        this.offset = offset;
        this.pos = -1;
      }
    }
    class DOMChange {
      constructor(view, start, end, typeOver) {
        this.typeOver = typeOver;
        this.bounds = null;
        this.text = "";
        this.domChanged = start > -1;
        let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
        if (view.state.readOnly && start > -1) {
          this.newSel = null;
        } else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {
          let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
          let reader = new DOMReader(selPoints, view.state);
          reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
          this.text = reader.text;
          this.newSel = selectionFromPoints(selPoints, this.bounds.from);
        } else {
          let domSel = view.observer.selectionRange;
          let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? view.state.selection.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
          let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? view.state.selection.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
          let vp = view.viewport;
          if ((browser.ios || browser.chrome) && view.state.selection.main.empty && head != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) {
            let from = Math.min(head, anchor), to2 = Math.max(head, anchor);
            let offFrom = vp.from - from, offTo = vp.to - to2;
            if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to2 == view.state.doc.length)) {
              head = 0;
              anchor = view.state.doc.length;
            }
          }
          this.newSel = EditorSelection.single(anchor, head);
        }
      }
    }
    function applyDOMChange(view, domChange) {
      let change;
      let { newSel } = domChange, sel = view.state.selection.main;
      let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
      if (domChange.bounds) {
        let { from, to: to2 } = domChange.bounds;
        let preferredPos = sel.from, preferredSide = null;
        if (lastKey === 8 || browser.android && domChange.text.length < to2 - from) {
          preferredPos = sel.to;
          preferredSide = "end";
        }
        let diff2 = findDiff(view.state.doc.sliceString(from, to2, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
        if (diff2) {
          if (browser.chrome && lastKey == 13 && diff2.toB == diff2.from + 2 && domChange.text.slice(diff2.from, diff2.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
            diff2.toB--;
          change = {
            from: from + diff2.from,
            to: from + diff2.toA,
            insert: Text.of(domChange.text.slice(diff2.from, diff2.toB).split(LineBreakPlaceholder))
          };
        }
      } else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {
        newSel = null;
      }
      if (!change && !newSel)
        return false;
      if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
        change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
      } else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
        if (newSel && change.insert.length == 2)
          newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
        change = { from: change.from, to: change.to, insert: Text.of([change.insert.toString().replace(".", " ")]) };
      } else if (change && change.from >= sel.from && change.to <= sel.to && (change.from != sel.from || change.to != sel.to) && sel.to - sel.from - (change.to - change.from) <= 4) {
        change = {
          from: sel.from,
          to: sel.to,
          insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
        };
      } else if (browser.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == "\n " && view.lineWrapping) {
        if (newSel)
          newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
        change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
      }
      if (change) {
        return applyDOMChangeInner(view, change, newSel, lastKey);
      } else if (newSel && !newSel.main.eq(sel)) {
        let scrollIntoView2 = false, userEvent = "select";
        if (view.inputState.lastSelectionTime > Date.now() - 50) {
          if (view.inputState.lastSelectionOrigin == "select")
            scrollIntoView2 = true;
          userEvent = view.inputState.lastSelectionOrigin;
        }
        view.dispatch({ selection: newSel, scrollIntoView: scrollIntoView2, userEvent });
        return true;
      } else {
        return false;
      }
    }
    function applyDOMChangeInner(view, change, newSel, lastKey = -1) {
      if (browser.ios && view.inputState.flushIOSKey(change))
        return true;
      let sel = view.state.selection.main;
      if (browser.android && (change.to == sel.to && // GBoard will sometimes remove a space it just inserted
      // after a completion when you press enter
      (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") && change.insert.length == 1 && change.insert.lines == 2 && dispatchKey(view.contentDOM, "Enter", 13) || (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 || lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) && dispatchKey(view.contentDOM, "Backspace", 8) || change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && dispatchKey(view.contentDOM, "Delete", 46)))
        return true;
      let text2 = change.insert.toString();
      if (view.inputState.composing >= 0)
        view.inputState.composing++;
      let defaultTr;
      let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
      if (!view.state.facet(inputHandler).some((h) => h(view, change.from, change.to, text2, defaultInsert)))
        view.dispatch(defaultInsert());
      return true;
    }
    function applyDefaultInsert(view, change, newSel) {
      let tr2, startState = view.state, sel = startState.selection.main;
      if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && view.inputState.composing < 0) {
        let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
        let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
        tr2 = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, void 0, view.state.lineBreak) + after));
      } else {
        let changes = startState.changes(change);
        let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : void 0;
        if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && change.to <= sel.to && change.to >= sel.to - 10) {
          let replaced = view.state.sliceDoc(change.from, change.to);
          let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);
          if (composition) {
            let dLen = change.insert.length - (change.to - change.from);
            compositionRange = { from: composition.from, to: composition.to - dLen };
          } else {
            compositionRange = view.state.doc.lineAt(sel.head);
          }
          let offset = sel.to - change.to, size = sel.to - sel.from;
          tr2 = startState.changeByRange((range) => {
            if (range.from == sel.from && range.to == sel.to)
              return { changes, range: mainSel || range.map(changes) };
            let to2 = range.to - offset, from = to2 - replaced.length;
            if (range.to - range.from != size || view.state.sliceDoc(from, to2) != replaced || // Unfortunately, there's no way to make multiple
            // changes in the same node work without aborting
            // composition, so cursors in the composition range are
            // ignored.
            range.to >= compositionRange.from && range.from <= compositionRange.to)
              return { range };
            let rangeChanges = startState.changes({ from, to: to2, insert: change.insert }), selOff = range.to - sel.to;
            return {
              changes: rangeChanges,
              range: !mainSel ? range.map(rangeChanges) : EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
            };
          });
        } else {
          tr2 = {
            changes,
            selection: mainSel && startState.selection.replaceRange(mainSel)
          };
        }
      }
      let userEvent = "input.type";
      if (view.composing || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
        view.inputState.compositionPendingChange = false;
        userEvent += ".compose";
        if (view.inputState.compositionFirstChange) {
          userEvent += ".start";
          view.inputState.compositionFirstChange = false;
        }
      }
      return startState.update(tr2, { userEvent, scrollIntoView: true });
    }
    function findDiff(a, b, preferredPos, preferredSide) {
      let minLen = Math.min(a.length, b.length);
      let from = 0;
      while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))
        from++;
      if (from == minLen && a.length == b.length)
        return null;
      let toA = a.length, toB = b.length;
      while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
        toA--;
        toB--;
      }
      if (preferredSide == "end") {
        let adjust = Math.max(0, from - Math.min(toA, toB));
        preferredPos -= toA + adjust - from;
      }
      if (toA < from && a.length < b.length) {
        let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
        from -= move;
        toB = from + (toB - toA);
        toA = from;
      } else if (toB < from) {
        let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
        from -= move;
        toA = from + (toA - toB);
        toB = from;
      }
      return { from, toA, toB };
    }
    function selectionPoints(view) {
      let result2 = [];
      if (view.root.activeElement != view.contentDOM)
        return result2;
      let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
      if (anchorNode) {
        result2.push(new DOMPoint(anchorNode, anchorOffset));
        if (focusNode != anchorNode || focusOffset != anchorOffset)
          result2.push(new DOMPoint(focusNode, focusOffset));
      }
      return result2;
    }
    function selectionFromPoints(points, base2) {
      if (points.length == 0)
        return null;
      let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;
      return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base2, head + base2) : null;
    }
    class InputState {
      setSelectionOrigin(origin) {
        this.lastSelectionOrigin = origin;
        this.lastSelectionTime = Date.now();
      }
      constructor(view) {
        this.view = view;
        this.lastKeyCode = 0;
        this.lastKeyTime = 0;
        this.lastTouchTime = 0;
        this.lastFocusTime = 0;
        this.lastScrollTop = 0;
        this.lastScrollLeft = 0;
        this.pendingIOSKey = void 0;
        this.tabFocusMode = -1;
        this.lastSelectionOrigin = null;
        this.lastSelectionTime = 0;
        this.lastContextMenu = 0;
        this.scrollHandlers = [];
        this.handlers = /* @__PURE__ */ Object.create(null);
        this.composing = -1;
        this.compositionFirstChange = null;
        this.compositionEndedAt = 0;
        this.compositionPendingKey = false;
        this.compositionPendingChange = false;
        this.mouseSelection = null;
        this.draggedContent = null;
        this.handleEvent = this.handleEvent.bind(this);
        this.notifiedFocused = view.hasFocus;
        if (browser.safari)
          view.contentDOM.addEventListener("input", () => null);
        if (browser.gecko)
          firefoxCopyCutHack(view.contentDOM.ownerDocument);
      }
      handleEvent(event) {
        if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))
          return;
        if (event.type == "keydown" && this.keydown(event))
          return;
        if (this.view.updateState != 0)
          Promise.resolve().then(() => this.runHandlers(event.type, event));
        else
          this.runHandlers(event.type, event);
      }
      runHandlers(type, event) {
        let handlers2 = this.handlers[type];
        if (handlers2) {
          for (let observer of handlers2.observers)
            observer(this.view, event);
          for (let handler of handlers2.handlers) {
            if (event.defaultPrevented)
              break;
            if (handler(this.view, event)) {
              event.preventDefault();
              break;
            }
          }
        }
      }
      ensureHandlers(plugins) {
        let handlers2 = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
        for (let type in handlers2)
          if (type != "scroll") {
            let passive = !handlers2[type].handlers.length;
            let exists = prev[type];
            if (exists && passive != !exists.handlers.length) {
              dom.removeEventListener(type, this.handleEvent);
              exists = null;
            }
            if (!exists)
              dom.addEventListener(type, this.handleEvent, { passive });
          }
        for (let type in prev)
          if (type != "scroll" && !handlers2[type])
            dom.removeEventListener(type, this.handleEvent);
        this.handlers = handlers2;
      }
      keydown(event) {
        this.lastKeyCode = event.keyCode;
        this.lastKeyTime = Date.now();
        if (event.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode))
          return true;
        if (this.tabFocusMode > 0 && event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)
          this.tabFocusMode = -1;
        if (browser.android && browser.chrome && !event.synthetic && (event.keyCode == 13 || event.keyCode == 8)) {
          this.view.observer.delayAndroidKey(event.key, event.keyCode);
          return true;
        }
        let pending;
        if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && ((pending = PendingKeys.find((key2) => key2.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
          this.pendingIOSKey = pending || event;
          setTimeout(() => this.flushIOSKey(), 250);
          return true;
        }
        if (event.keyCode != 229)
          this.view.observer.forceFlush();
        return false;
      }
      flushIOSKey(change) {
        let key2 = this.pendingIOSKey;
        if (!key2)
          return false;
        if (key2.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString()))
          return false;
        this.pendingIOSKey = void 0;
        return dispatchKey(this.view.contentDOM, key2.key, key2.keyCode, key2 instanceof KeyboardEvent ? key2 : void 0);
      }
      ignoreDuringComposition(event) {
        if (!/^key/.test(event.type))
          return false;
        if (this.composing > 0)
          return true;
        if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
          this.compositionPendingKey = false;
          return true;
        }
        return false;
      }
      startMouseSelection(mouseSelection) {
        if (this.mouseSelection)
          this.mouseSelection.destroy();
        this.mouseSelection = mouseSelection;
      }
      update(update) {
        this.view.observer.update(update);
        if (this.mouseSelection)
          this.mouseSelection.update(update);
        if (this.draggedContent && update.docChanged)
          this.draggedContent = this.draggedContent.map(update.changes);
        if (update.transactions.length)
          this.lastKeyCode = this.lastSelectionTime = 0;
      }
      destroy() {
        if (this.mouseSelection)
          this.mouseSelection.destroy();
      }
    }
    function bindHandler(plugin, handler) {
      return (view, event) => {
        try {
          return handler.call(plugin, event, view);
        } catch (e) {
          logException(view.state, e);
        }
      };
    }
    function computeHandlers(plugins) {
      let result2 = /* @__PURE__ */ Object.create(null);
      function record(type) {
        return result2[type] || (result2[type] = { observers: [], handlers: [] });
      }
      for (let plugin of plugins) {
        let spec = plugin.spec;
        if (spec && spec.domEventHandlers)
          for (let type in spec.domEventHandlers) {
            let f = spec.domEventHandlers[type];
            if (f)
              record(type).handlers.push(bindHandler(plugin.value, f));
          }
        if (spec && spec.domEventObservers)
          for (let type in spec.domEventObservers) {
            let f = spec.domEventObservers[type];
            if (f)
              record(type).observers.push(bindHandler(plugin.value, f));
          }
      }
      for (let type in handlers)
        record(type).handlers.push(handlers[type]);
      for (let type in observers)
        record(type).observers.push(observers[type]);
      return result2;
    }
    const PendingKeys = [
      { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
      { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
      { key: "Enter", keyCode: 13, inputType: "insertLineBreak" },
      { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
    ];
    const EmacsyPendingKeys = "dthko";
    const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
    const dragScrollMargin = 6;
    function dragScrollSpeed(dist2) {
      return Math.max(0, dist2) * 0.7 + 8;
    }
    function dist(a, b) {
      return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
    }
    class MouseSelection {
      constructor(view, startEvent, style2, mustSelect) {
        this.view = view;
        this.startEvent = startEvent;
        this.style = style2;
        this.mustSelect = mustSelect;
        this.scrollSpeed = { x: 0, y: 0 };
        this.scrolling = -1;
        this.lastEvent = startEvent;
        this.scrollParents = scrollableParents(view.contentDOM);
        this.atoms = view.state.facet(atomicRanges).map((f) => f(view));
        let doc2 = view.contentDOM.ownerDocument;
        doc2.addEventListener("mousemove", this.move = this.move.bind(this));
        doc2.addEventListener("mouseup", this.up = this.up.bind(this));
        this.extend = startEvent.shiftKey;
        this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
        this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
      }
      start(event) {
        if (this.dragging === false)
          this.select(event);
      }
      move(event) {
        if (event.buttons == 0)
          return this.destroy();
        if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)
          return;
        this.select(this.lastEvent = event);
        let sx = 0, sy = 0;
        let left = 0, top2 = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight;
        if (this.scrollParents.x)
          ({ left, right } = this.scrollParents.x.getBoundingClientRect());
        if (this.scrollParents.y)
          ({ top: top2, bottom } = this.scrollParents.y.getBoundingClientRect());
        let margins = getScrollMargins(this.view);
        if (event.clientX - margins.left <= left + dragScrollMargin)
          sx = -dragScrollSpeed(left - event.clientX);
        else if (event.clientX + margins.right >= right - dragScrollMargin)
          sx = dragScrollSpeed(event.clientX - right);
        if (event.clientY - margins.top <= top2 + dragScrollMargin)
          sy = -dragScrollSpeed(top2 - event.clientY);
        else if (event.clientY + margins.bottom >= bottom - dragScrollMargin)
          sy = dragScrollSpeed(event.clientY - bottom);
        this.setScrollSpeed(sx, sy);
      }
      up(event) {
        if (this.dragging == null)
          this.select(this.lastEvent);
        if (!this.dragging)
          event.preventDefault();
        this.destroy();
      }
      destroy() {
        this.setScrollSpeed(0, 0);
        let doc2 = this.view.contentDOM.ownerDocument;
        doc2.removeEventListener("mousemove", this.move);
        doc2.removeEventListener("mouseup", this.up);
        this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
      }
      setScrollSpeed(sx, sy) {
        this.scrollSpeed = { x: sx, y: sy };
        if (sx || sy) {
          if (this.scrolling < 0)
            this.scrolling = setInterval(() => this.scroll(), 50);
        } else if (this.scrolling > -1) {
          clearInterval(this.scrolling);
          this.scrolling = -1;
        }
      }
      scroll() {
        let { x: x2, y } = this.scrollSpeed;
        if (x2 && this.scrollParents.x) {
          this.scrollParents.x.scrollLeft += x2;
          x2 = 0;
        }
        if (y && this.scrollParents.y) {
          this.scrollParents.y.scrollTop += y;
          y = 0;
        }
        if (x2 || y)
          this.view.win.scrollBy(x2, y);
        if (this.dragging === false)
          this.select(this.lastEvent);
      }
      skipAtoms(sel) {
        let ranges = null;
        for (let i2 = 0; i2 < sel.ranges.length; i2++) {
          let range = sel.ranges[i2], updated = null;
          if (range.empty) {
            let pos2 = skipAtomicRanges(this.atoms, range.from, 0);
            if (pos2 != range.from)
              updated = EditorSelection.cursor(pos2, -1);
          } else {
            let from = skipAtomicRanges(this.atoms, range.from, -1);
            let to2 = skipAtomicRanges(this.atoms, range.to, 1);
            if (from != range.from || to2 != range.to)
              updated = EditorSelection.range(range.from == range.anchor ? from : to2, range.from == range.head ? from : to2);
          }
          if (updated) {
            if (!ranges)
              ranges = sel.ranges.slice();
            ranges[i2] = updated;
          }
        }
        return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
      }
      select(event) {
        let { view } = this, selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));
        if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false))
          this.view.dispatch({
            selection,
            userEvent: "select.pointer"
          });
        this.mustSelect = false;
      }
      update(update) {
        if (update.transactions.some((tr2) => tr2.isUserEvent("input.type")))
          this.destroy();
        else if (this.style.update(update))
          setTimeout(() => this.select(this.lastEvent), 20);
      }
    }
    function addsSelectionRange(view, event) {
      let facet = view.state.facet(clickAddsSelectionRange);
      return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
    }
    function dragMovesSelection(view, event) {
      let facet = view.state.facet(dragMovesSelection$1);
      return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
    }
    function isInPrimarySelection(view, event) {
      let { main } = view.state.selection;
      if (main.empty)
        return false;
      let sel = getSelection(view.root);
      if (!sel || sel.rangeCount == 0)
        return true;
      let rects = sel.getRangeAt(0).getClientRects();
      for (let i2 = 0; i2 < rects.length; i2++) {
        let rect = rects[i2];
        if (rect.left <= event.clientX && rect.right >= event.clientX && rect.top <= event.clientY && rect.bottom >= event.clientY)
          return true;
      }
      return false;
    }
    function eventBelongsToEditor(view, event) {
      if (!event.bubbles)
        return true;
      if (event.defaultPrevented)
        return false;
      for (let node2 = event.target, cView; node2 != view.contentDOM; node2 = node2.parentNode)
        if (!node2 || node2.nodeType == 11 || (cView = ContentView.get(node2)) && cView.ignoreEvent(event))
          return false;
      return true;
    }
    const handlers = /* @__PURE__ */ Object.create(null);
    const observers = /* @__PURE__ */ Object.create(null);
    const brokenClipboardAPI = browser.ie && browser.ie_version < 15 || browser.ios && browser.webkit_version < 604;
    function capturePaste(view) {
      let parent = view.dom.parentNode;
      if (!parent)
        return;
      let target2 = parent.appendChild(document.createElement("textarea"));
      target2.style.cssText = "position: fixed; left: -10000px; top: 10px";
      target2.focus();
      setTimeout(() => {
        view.focus();
        target2.remove();
        doPaste(view, target2.value);
      }, 50);
    }
    function textFilter(state, facet, text2) {
      for (let filter of state.facet(facet))
        text2 = filter(text2, state);
      return text2;
    }
    function doPaste(view, input2) {
      input2 = textFilter(view.state, clipboardInputFilter, input2);
      let { state } = view, changes, i2 = 1, text2 = state.toText(input2);
      let byLine = text2.lines == state.selection.ranges.length;
      let linewise = lastLinewiseCopy != null && state.selection.ranges.every((r2) => r2.empty) && lastLinewiseCopy == text2.toString();
      if (linewise) {
        let lastLine = -1;
        changes = state.changeByRange((range) => {
          let line2 = state.doc.lineAt(range.from);
          if (line2.from == lastLine)
            return { range };
          lastLine = line2.from;
          let insert2 = state.toText((byLine ? text2.line(i2++).text : input2) + state.lineBreak);
          return {
            changes: { from: line2.from, insert: insert2 },
            range: EditorSelection.cursor(range.from + insert2.length)
          };
        });
      } else if (byLine) {
        changes = state.changeByRange((range) => {
          let line2 = text2.line(i2++);
          return {
            changes: { from: range.from, to: range.to, insert: line2.text },
            range: EditorSelection.cursor(range.from + line2.length)
          };
        });
      } else {
        changes = state.replaceSelection(text2);
      }
      view.dispatch(changes, {
        userEvent: "input.paste",
        scrollIntoView: true
      });
    }
    observers.scroll = (view) => {
      view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
      view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
    };
    handlers.keydown = (view, event) => {
      view.inputState.setSelectionOrigin("select");
      if (event.keyCode == 27 && view.inputState.tabFocusMode != 0)
        view.inputState.tabFocusMode = Date.now() + 2e3;
      return false;
    };
    observers.touchstart = (view, e) => {
      view.inputState.lastTouchTime = Date.now();
      view.inputState.setSelectionOrigin("select.pointer");
    };
    observers.touchmove = (view) => {
      view.inputState.setSelectionOrigin("select.pointer");
    };
    handlers.mousedown = (view, event) => {
      view.observer.flush();
      if (view.inputState.lastTouchTime > Date.now() - 2e3)
        return false;
      let style2 = null;
      for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
        style2 = makeStyle(view, event);
        if (style2)
          break;
      }
      if (!style2 && event.button == 0)
        style2 = basicMouseSelection(view, event);
      if (style2) {
        let mustFocus = !view.hasFocus;
        view.inputState.startMouseSelection(new MouseSelection(view, event, style2, mustFocus));
        if (mustFocus)
          view.observer.ignore(() => {
            focusPreventScroll(view.contentDOM);
            let active2 = view.root.activeElement;
            if (active2 && !active2.contains(view.contentDOM))
              active2.blur();
          });
        let mouseSel = view.inputState.mouseSelection;
        if (mouseSel) {
          mouseSel.start(event);
          return mouseSel.dragging === false;
        }
      }
      return false;
    };
    function rangeForClick(view, pos2, bias, type) {
      if (type == 1) {
        return EditorSelection.cursor(pos2, bias);
      } else if (type == 2) {
        return groupAt(view.state, pos2, bias);
      } else {
        let visual = LineView.find(view.docView, pos2), line2 = view.state.doc.lineAt(visual ? visual.posAtEnd : pos2);
        let from = visual ? visual.posAtStart : line2.from, to2 = visual ? visual.posAtEnd : line2.to;
        if (to2 < view.state.doc.length && to2 == line2.to)
          to2++;
        return EditorSelection.range(from, to2);
      }
    }
    let inside = (x2, y, rect) => y >= rect.top && y <= rect.bottom && x2 >= rect.left && x2 <= rect.right;
    function findPositionSide(view, pos2, x2, y) {
      let line2 = LineView.find(view.docView, pos2);
      if (!line2)
        return 1;
      let off = pos2 - line2.posAtStart;
      if (off == 0)
        return 1;
      if (off == line2.length)
        return -1;
      let before = line2.coordsAt(off, -1);
      if (before && inside(x2, y, before))
        return -1;
      let after = line2.coordsAt(off, 1);
      if (after && inside(x2, y, after))
        return 1;
      return before && before.bottom >= y ? -1 : 1;
    }
    function queryPos(view, event) {
      let pos2 = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
      return { pos: pos2, bias: findPositionSide(view, pos2, event.clientX, event.clientY) };
    }
    const BadMouseDetail = browser.ie && browser.ie_version <= 11;
    let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
    function getClickType(event) {
      if (!BadMouseDetail)
        return event.detail;
      let last = lastMouseDown, lastTime = lastMouseDownTime;
      lastMouseDown = event;
      lastMouseDownTime = Date.now();
      return lastMouseDownCount = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && Math.abs(last.clientY - event.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1;
    }
    function basicMouseSelection(view, event) {
      let start = queryPos(view, event), type = getClickType(event);
      let startSel = view.state.selection;
      return {
        update(update) {
          if (update.docChanged) {
            start.pos = update.changes.mapPos(start.pos);
            startSel = startSel.map(update.changes);
          }
        },
        get(event2, extend, multiple) {
          let cur2 = queryPos(view, event2), removed;
          let range = rangeForClick(view, cur2.pos, cur2.bias, type);
          if (start.pos != cur2.pos && !extend) {
            let startRange = rangeForClick(view, start.pos, start.bias, type);
            let from = Math.min(startRange.from, range.from), to2 = Math.max(startRange.to, range.to);
            range = from < range.from ? EditorSelection.range(from, to2) : EditorSelection.range(to2, from);
          }
          if (extend)
            return startSel.replaceRange(startSel.main.extend(range.from, range.to));
          else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur2.pos)))
            return removed;
          else if (multiple)
            return startSel.addRange(range);
          else
            return EditorSelection.create([range]);
        }
      };
    }
    function removeRangeAround(sel, pos2) {
      for (let i2 = 0; i2 < sel.ranges.length; i2++) {
        let { from, to: to2 } = sel.ranges[i2];
        if (from <= pos2 && to2 >= pos2)
          return EditorSelection.create(sel.ranges.slice(0, i2).concat(sel.ranges.slice(i2 + 1)), sel.mainIndex == i2 ? 0 : sel.mainIndex - (sel.mainIndex > i2 ? 1 : 0));
      }
      return null;
    }
    handlers.dragstart = (view, event) => {
      let { selection: { main: range } } = view.state;
      if (event.target.draggable) {
        let cView = view.docView.nearest(event.target);
        if (cView && cView.isWidget) {
          let from = cView.posAtStart, to2 = from + cView.length;
          if (from >= range.to || to2 <= range.from)
            range = EditorSelection.range(from, to2);
        }
      }
      let { inputState } = view;
      if (inputState.mouseSelection)
        inputState.mouseSelection.dragging = true;
      inputState.draggedContent = range;
      if (event.dataTransfer) {
        event.dataTransfer.setData("Text", textFilter(view.state, clipboardOutputFilter, view.state.sliceDoc(range.from, range.to)));
        event.dataTransfer.effectAllowed = "copyMove";
      }
      return false;
    };
    handlers.dragend = (view) => {
      view.inputState.draggedContent = null;
      return false;
    };
    function dropText(view, event, text2, direct) {
      text2 = textFilter(view.state, clipboardInputFilter, text2);
      if (!text2)
        return;
      let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
      let { draggedContent } = view.inputState;
      let del = direct && draggedContent && dragMovesSelection(view, event) ? { from: draggedContent.from, to: draggedContent.to } : null;
      let ins = { from: dropPos, insert: text2 };
      let changes = view.state.changes(del ? [del, ins] : ins);
      view.focus();
      view.dispatch({
        changes,
        selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
        userEvent: del ? "move.drop" : "input.drop"
      });
      view.inputState.draggedContent = null;
    }
    handlers.drop = (view, event) => {
      if (!event.dataTransfer)
        return false;
      if (view.state.readOnly)
        return true;
      let files = event.dataTransfer.files;
      if (files && files.length) {
        let text2 = Array(files.length), read2 = 0;
        let finishFile = () => {
          if (++read2 == files.length)
            dropText(view, event, text2.filter((s) => s != null).join(view.state.lineBreak), false);
        };
        for (let i2 = 0; i2 < files.length; i2++) {
          let reader = new FileReader();
          reader.onerror = finishFile;
          reader.onload = () => {
            if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
              text2[i2] = reader.result;
            finishFile();
          };
          reader.readAsText(files[i2]);
        }
        return true;
      } else {
        let text2 = event.dataTransfer.getData("Text");
        if (text2) {
          dropText(view, event, text2, true);
          return true;
        }
      }
      return false;
    };
    handlers.paste = (view, event) => {
      if (view.state.readOnly)
        return true;
      view.observer.flush();
      let data = brokenClipboardAPI ? null : event.clipboardData;
      if (data) {
        doPaste(view, data.getData("text/plain") || data.getData("text/uri-list"));
        return true;
      } else {
        capturePaste(view);
        return false;
      }
    };
    function captureCopy(view, text2) {
      let parent = view.dom.parentNode;
      if (!parent)
        return;
      let target2 = parent.appendChild(document.createElement("textarea"));
      target2.style.cssText = "position: fixed; left: -10000px; top: 10px";
      target2.value = text2;
      target2.focus();
      target2.selectionEnd = text2.length;
      target2.selectionStart = 0;
      setTimeout(() => {
        target2.remove();
        view.focus();
      }, 50);
    }
    function copiedRange(state) {
      let content2 = [], ranges = [], linewise = false;
      for (let range of state.selection.ranges)
        if (!range.empty) {
          content2.push(state.sliceDoc(range.from, range.to));
          ranges.push(range);
        }
      if (!content2.length) {
        let upto = -1;
        for (let { from } of state.selection.ranges) {
          let line2 = state.doc.lineAt(from);
          if (line2.number > upto) {
            content2.push(line2.text);
            ranges.push({ from: line2.from, to: Math.min(state.doc.length, line2.to + 1) });
          }
          upto = line2.number;
        }
        linewise = true;
      }
      return { text: textFilter(state, clipboardOutputFilter, content2.join(state.lineBreak)), ranges, linewise };
    }
    let lastLinewiseCopy = null;
    handlers.copy = handlers.cut = (view, event) => {
      let { text: text2, ranges, linewise } = copiedRange(view.state);
      if (!text2 && !linewise)
        return false;
      lastLinewiseCopy = linewise ? text2 : null;
      if (event.type == "cut" && !view.state.readOnly)
        view.dispatch({
          changes: ranges,
          scrollIntoView: true,
          userEvent: "delete.cut"
        });
      let data = brokenClipboardAPI ? null : event.clipboardData;
      if (data) {
        data.clearData();
        data.setData("text/plain", text2);
        return true;
      } else {
        captureCopy(view, text2);
        return false;
      }
    };
    const isFocusChange = /* @__PURE__ */ Annotation.define();
    function focusChangeTransaction(state, focus) {
      let effects = [];
      for (let getEffect of state.facet(focusChangeEffect)) {
        let effect = getEffect(state, focus);
        if (effect)
          effects.push(effect);
      }
      return effects ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;
    }
    function updateForFocusChange(view) {
      setTimeout(() => {
        let focus = view.hasFocus;
        if (focus != view.inputState.notifiedFocused) {
          let tr2 = focusChangeTransaction(view.state, focus);
          if (tr2)
            view.dispatch(tr2);
          else
            view.update([]);
        }
      }, 10);
    }
    observers.focus = (view) => {
      view.inputState.lastFocusTime = Date.now();
      if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
        view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
        view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
      }
      updateForFocusChange(view);
    };
    observers.blur = (view) => {
      view.observer.clearSelectionRange();
      updateForFocusChange(view);
    };
    observers.compositionstart = observers.compositionupdate = (view) => {
      if (view.observer.editContext)
        return;
      if (view.inputState.compositionFirstChange == null)
        view.inputState.compositionFirstChange = true;
      if (view.inputState.composing < 0) {
        view.inputState.composing = 0;
      }
    };
    observers.compositionend = (view) => {
      if (view.observer.editContext)
        return;
      view.inputState.composing = -1;
      view.inputState.compositionEndedAt = Date.now();
      view.inputState.compositionPendingKey = true;
      view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
      view.inputState.compositionFirstChange = null;
      if (browser.chrome && browser.android) {
        view.observer.flushSoon();
      } else if (view.inputState.compositionPendingChange) {
        Promise.resolve().then(() => view.observer.flush());
      } else {
        setTimeout(() => {
          if (view.inputState.composing < 0 && view.docView.hasComposition)
            view.update([]);
        }, 50);
      }
    };
    observers.contextmenu = (view) => {
      view.inputState.lastContextMenu = Date.now();
    };
    handlers.beforeinput = (view, event) => {
      var _a2, _b2;
      if (event.inputType == "insertReplacementText" && view.observer.editContext) {
        let text2 = (_a2 = event.dataTransfer) === null || _a2 === void 0 ? void 0 : _a2.getData("text/plain"), ranges = event.getTargetRanges();
        if (text2 && ranges.length) {
          let r2 = ranges[0];
          let from = view.posAtDOM(r2.startContainer, r2.startOffset), to2 = view.posAtDOM(r2.endContainer, r2.endOffset);
          applyDOMChangeInner(view, { from, to: to2, insert: view.state.toText(text2) }, null);
          return true;
        }
      }
      let pending;
      if (browser.chrome && browser.android && (pending = PendingKeys.find((key2) => key2.inputType == event.inputType))) {
        view.observer.delayAndroidKey(pending.key, pending.keyCode);
        if (pending.key == "Backspace" || pending.key == "Delete") {
          let startViewHeight = ((_b2 = window.visualViewport) === null || _b2 === void 0 ? void 0 : _b2.height) || 0;
          setTimeout(() => {
            var _a3;
            if ((((_a3 = window.visualViewport) === null || _a3 === void 0 ? void 0 : _a3.height) || 0) > startViewHeight + 10 && view.hasFocus) {
              view.contentDOM.blur();
              view.focus();
            }
          }, 100);
        }
      }
      if (browser.ios && event.inputType == "deleteContentForward") {
        view.observer.flushSoon();
      }
      if (browser.safari && event.inputType == "insertText" && view.inputState.composing >= 0) {
        setTimeout(() => observers.compositionend(view, event), 20);
      }
      return false;
    };
    const appliedFirefoxHack = /* @__PURE__ */ new Set();
    function firefoxCopyCutHack(doc2) {
      if (!appliedFirefoxHack.has(doc2)) {
        appliedFirefoxHack.add(doc2);
        doc2.addEventListener("copy", () => {
        });
        doc2.addEventListener("cut", () => {
        });
      }
    }
    const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
    let heightChangeFlag = false;
    function clearHeightChangeFlag() {
      heightChangeFlag = false;
    }
    class HeightOracle {
      constructor(lineWrapping) {
        this.lineWrapping = lineWrapping;
        this.doc = Text.empty;
        this.heightSamples = {};
        this.lineHeight = 14;
        this.charWidth = 7;
        this.textHeight = 14;
        this.lineLength = 30;
      }
      heightForGap(from, to2) {
        let lines = this.doc.lineAt(to2).number - this.doc.lineAt(from).number + 1;
        if (this.lineWrapping)
          lines += Math.max(0, Math.ceil((to2 - from - lines * this.lineLength * 0.5) / this.lineLength));
        return this.lineHeight * lines;
      }
      heightForLine(length) {
        if (!this.lineWrapping)
          return this.lineHeight;
        let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));
        return lines * this.lineHeight;
      }
      setDoc(doc2) {
        this.doc = doc2;
        return this;
      }
      mustRefreshForWrapping(whiteSpace) {
        return wrappingWhiteSpace.indexOf(whiteSpace) > -1 != this.lineWrapping;
      }
      mustRefreshForHeights(lineHeights) {
        let newHeight = false;
        for (let i2 = 0; i2 < lineHeights.length; i2++) {
          let h = lineHeights[i2];
          if (h < 0) {
            i2++;
          } else if (!this.heightSamples[Math.floor(h * 10)]) {
            newHeight = true;
            this.heightSamples[Math.floor(h * 10)] = true;
          }
        }
        return newHeight;
      }
      refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
        let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
        let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
        this.lineWrapping = lineWrapping;
        this.lineHeight = lineHeight;
        this.charWidth = charWidth;
        this.textHeight = textHeight;
        this.lineLength = lineLength;
        if (changed) {
          this.heightSamples = {};
          for (let i2 = 0; i2 < knownHeights.length; i2++) {
            let h = knownHeights[i2];
            if (h < 0)
              i2++;
            else
              this.heightSamples[Math.floor(h * 10)] = true;
          }
        }
        return changed;
      }
    }
    class MeasuredHeights {
      constructor(from, heights) {
        this.from = from;
        this.heights = heights;
        this.index = 0;
      }
      get more() {
        return this.index < this.heights.length;
      }
    }
    class BlockInfo {
      /**
      @internal
      */
      constructor(from, length, top2, height, _content) {
        this.from = from;
        this.length = length;
        this.top = top2;
        this.height = height;
        this._content = _content;
      }
      /**
      The type of element this is. When querying lines, this may be
      an array of all the blocks that make up the line.
      */
      get type() {
        return typeof this._content == "number" ? BlockType.Text : Array.isArray(this._content) ? this._content : this._content.type;
      }
      /**
      The end of the element as a document position.
      */
      get to() {
        return this.from + this.length;
      }
      /**
      The bottom position of the element.
      */
      get bottom() {
        return this.top + this.height;
      }
      /**
      If this is a widget block, this will return the widget
      associated with it.
      */
      get widget() {
        return this._content instanceof PointDecoration ? this._content.widget : null;
      }
      /**
      If this is a textblock, this holds the number of line breaks
      that appear in widgets inside the block.
      */
      get widgetLineBreaks() {
        return typeof this._content == "number" ? this._content : 0;
      }
      /**
      @internal
      */
      join(other) {
        let content2 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]);
        return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content2);
      }
    }
    var QueryType = /* @__PURE__ */ function(QueryType2) {
      QueryType2[QueryType2["ByPos"] = 0] = "ByPos";
      QueryType2[QueryType2["ByHeight"] = 1] = "ByHeight";
      QueryType2[QueryType2["ByPosNoHeight"] = 2] = "ByPosNoHeight";
      return QueryType2;
    }(QueryType || (QueryType = {}));
    const Epsilon = 1e-3;
    class HeightMap {
      constructor(length, height, flags = 2) {
        this.length = length;
        this.height = height;
        this.flags = flags;
      }
      get outdated() {
        return (this.flags & 2) > 0;
      }
      set outdated(value2) {
        this.flags = (value2 ? 2 : 0) | this.flags & -3;
      }
      setHeight(height) {
        if (this.height != height) {
          if (Math.abs(this.height - height) > Epsilon)
            heightChangeFlag = true;
          this.height = height;
        }
      }
      // Base case is to replace a leaf node, which simply builds a tree
      // from the new nodes and returns that (HeightMapBranch and
      // HeightMapGap override this to actually use from/to)
      replace(_from, _to, nodes) {
        return HeightMap.of(nodes);
      }
      // Again, these are base cases, and are overridden for branch and gap nodes.
      decomposeLeft(_to, result2) {
        result2.push(this);
      }
      decomposeRight(_from, result2) {
        result2.push(this);
      }
      applyChanges(decorations2, oldDoc, oracle, changes) {
        let me = this, doc2 = oracle.doc;
        for (let i2 = changes.length - 1; i2 >= 0; i2--) {
          let { fromA, toA, fromB, toB } = changes[i2];
          let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
          let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);
          toB += end.to - toA;
          toA = end.to;
          while (i2 > 0 && start.from <= changes[i2 - 1].toA) {
            fromA = changes[i2 - 1].fromA;
            fromB = changes[i2 - 1].fromB;
            i2--;
            if (fromA < start.from)
              start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);
          }
          fromB += start.from - fromA;
          fromA = start.from;
          let nodes = NodeBuilder.build(oracle.setDoc(doc2), decorations2, fromB, toB);
          me = replace(me, me.replace(fromA, toA, nodes));
        }
        return me.updateHeight(oracle, 0);
      }
      static empty() {
        return new HeightMapText(0, 0);
      }
      // nodes uses null values to indicate the position of line breaks.
      // There are never line breaks at the start or end of the array, or
      // two line breaks next to each other, and the array isn't allowed
      // to be empty (same restrictions as return value from the builder).
      static of(nodes) {
        if (nodes.length == 1)
          return nodes[0];
        let i2 = 0, j2 = nodes.length, before = 0, after = 0;
        for (; ; ) {
          if (i2 == j2) {
            if (before > after * 2) {
              let split = nodes[i2 - 1];
              if (split.break)
                nodes.splice(--i2, 1, split.left, null, split.right);
              else
                nodes.splice(--i2, 1, split.left, split.right);
              j2 += 1 + split.break;
              before -= split.size;
            } else if (after > before * 2) {
              let split = nodes[j2];
              if (split.break)
                nodes.splice(j2, 1, split.left, null, split.right);
              else
                nodes.splice(j2, 1, split.left, split.right);
              j2 += 2 + split.break;
              after -= split.size;
            } else {
              break;
            }
          } else if (before < after) {
            let next = nodes[i2++];
            if (next)
              before += next.size;
          } else {
            let next = nodes[--j2];
            if (next)
              after += next.size;
          }
        }
        let brk = 0;
        if (nodes[i2 - 1] == null) {
          brk = 1;
          i2--;
        } else if (nodes[i2] == null) {
          brk = 1;
          j2++;
        }
        return new HeightMapBranch(HeightMap.of(nodes.slice(0, i2)), brk, HeightMap.of(nodes.slice(j2)));
      }
    }
    function replace(old, val) {
      if (old == val)
        return old;
      if (old.constructor != val.constructor)
        heightChangeFlag = true;
      return val;
    }
    HeightMap.prototype.size = 1;
    class HeightMapBlock extends HeightMap {
      constructor(length, height, deco) {
        super(length, height);
        this.deco = deco;
      }
      blockAt(_height, _oracle, top2, offset) {
        return new BlockInfo(offset, this.length, top2, this.height, this.deco || 0);
      }
      lineAt(_value, _type, oracle, top2, offset) {
        return this.blockAt(0, oracle, top2, offset);
      }
      forEachLine(from, to2, oracle, top2, offset, f) {
        if (from <= offset + this.length && to2 >= offset)
          f(this.blockAt(0, oracle, top2, offset));
      }
      updateHeight(oracle, offset = 0, _force = false, measured) {
        if (measured && measured.from <= offset && measured.more)
          this.setHeight(measured.heights[measured.index++]);
        this.outdated = false;
        return this;
      }
      toString() {
        return `block(${this.length})`;
      }
    }
    class HeightMapText extends HeightMapBlock {
      constructor(length, height) {
        super(length, height, null);
        this.collapsed = 0;
        this.widgetHeight = 0;
        this.breaks = 0;
      }
      blockAt(_height, _oracle, top2, offset) {
        return new BlockInfo(offset, this.length, top2, this.height, this.breaks);
      }
      replace(_from, _to, nodes) {
        let node2 = nodes[0];
        if (nodes.length == 1 && (node2 instanceof HeightMapText || node2 instanceof HeightMapGap && node2.flags & 4) && Math.abs(this.length - node2.length) < 10) {
          if (node2 instanceof HeightMapGap)
            node2 = new HeightMapText(node2.length, this.height);
          else
            node2.height = this.height;
          if (!this.outdated)
            node2.outdated = false;
          return node2;
        } else {
          return HeightMap.of(nodes);
        }
      }
      updateHeight(oracle, offset = 0, force = false, measured) {
        if (measured && measured.from <= offset && measured.more)
          this.setHeight(measured.heights[measured.index++]);
        else if (force || this.outdated)
          this.setHeight(Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) + this.breaks * oracle.lineHeight);
        this.outdated = false;
        return this;
      }
      toString() {
        return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
      }
    }
    class HeightMapGap extends HeightMap {
      constructor(length) {
        super(length, 0);
      }
      heightMetrics(oracle, offset) {
        let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;
        let lines = lastLine - firstLine + 1;
        let perLine, perChar = 0;
        if (oracle.lineWrapping) {
          let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
          perLine = totalPerLine / lines;
          if (this.length > lines + 1)
            perChar = (this.height - totalPerLine) / (this.length - lines - 1);
        } else {
          perLine = this.height / lines;
        }
        return { firstLine, lastLine, perLine, perChar };
      }
      blockAt(height, oracle, top2, offset) {
        let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
        if (oracle.lineWrapping) {
          let guess = offset + (height < oracle.lineHeight ? 0 : Math.round(Math.max(0, Math.min(1, (height - top2) / this.height)) * this.length));
          let line2 = oracle.doc.lineAt(guess), lineHeight = perLine + line2.length * perChar;
          let lineTop = Math.max(top2, height - lineHeight / 2);
          return new BlockInfo(line2.from, line2.length, lineTop, lineHeight, 0);
        } else {
          let line2 = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top2) / perLine)));
          let { from, length } = oracle.doc.line(firstLine + line2);
          return new BlockInfo(from, length, top2 + perLine * line2, perLine, 0);
        }
      }
      lineAt(value2, type, oracle, top2, offset) {
        if (type == QueryType.ByHeight)
          return this.blockAt(value2, oracle, top2, offset);
        if (type == QueryType.ByPosNoHeight) {
          let { from, to: to2 } = oracle.doc.lineAt(value2);
          return new BlockInfo(from, to2 - from, 0, 0, 0);
        }
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
        let line2 = oracle.doc.lineAt(value2), lineHeight = perLine + line2.length * perChar;
        let linesAbove = line2.number - firstLine;
        let lineTop = top2 + perLine * linesAbove + perChar * (line2.from - offset - linesAbove);
        return new BlockInfo(line2.from, line2.length, Math.max(top2, Math.min(lineTop, top2 + this.height - lineHeight)), lineHeight, 0);
      }
      forEachLine(from, to2, oracle, top2, offset, f) {
        from = Math.max(from, offset);
        to2 = Math.min(to2, offset + this.length);
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
        for (let pos2 = from, lineTop = top2; pos2 <= to2; ) {
          let line2 = oracle.doc.lineAt(pos2);
          if (pos2 == from) {
            let linesAbove = line2.number - firstLine;
            lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
          }
          let lineHeight = perLine + perChar * line2.length;
          f(new BlockInfo(line2.from, line2.length, lineTop, lineHeight, 0));
          lineTop += lineHeight;
          pos2 = line2.to + 1;
        }
      }
      replace(from, to2, nodes) {
        let after = this.length - to2;
        if (after > 0) {
          let last = nodes[nodes.length - 1];
          if (last instanceof HeightMapGap)
            nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
          else
            nodes.push(null, new HeightMapGap(after - 1));
        }
        if (from > 0) {
          let first2 = nodes[0];
          if (first2 instanceof HeightMapGap)
            nodes[0] = new HeightMapGap(from + first2.length);
          else
            nodes.unshift(new HeightMapGap(from - 1), null);
        }
        return HeightMap.of(nodes);
      }
      decomposeLeft(to2, result2) {
        result2.push(new HeightMapGap(to2 - 1), null);
      }
      decomposeRight(from, result2) {
        result2.push(null, new HeightMapGap(this.length - from - 1));
      }
      updateHeight(oracle, offset = 0, force = false, measured) {
        let end = offset + this.length;
        if (measured && measured.from <= offset + this.length && measured.more) {
          let nodes = [], pos2 = Math.max(offset, measured.from), singleHeight = -1;
          if (measured.from > offset)
            nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
          while (pos2 <= end && measured.more) {
            let len = oracle.doc.lineAt(pos2).length;
            if (nodes.length)
              nodes.push(null);
            let height = measured.heights[measured.index++];
            if (singleHeight == -1)
              singleHeight = height;
            else if (Math.abs(height - singleHeight) >= Epsilon)
              singleHeight = -2;
            let line2 = new HeightMapText(len, height);
            line2.outdated = false;
            nodes.push(line2);
            pos2 += len + 1;
          }
          if (pos2 <= end)
            nodes.push(null, new HeightMapGap(end - pos2).updateHeight(oracle, pos2));
          let result2 = HeightMap.of(nodes);
          if (singleHeight < 0 || Math.abs(result2.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
            heightChangeFlag = true;
          return replace(this, result2);
        } else if (force || this.outdated) {
          this.setHeight(oracle.heightForGap(offset, offset + this.length));
          this.outdated = false;
        }
        return this;
      }
      toString() {
        return `gap(${this.length})`;
      }
    }
    class HeightMapBranch extends HeightMap {
      constructor(left, brk, right) {
        super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 : 0));
        this.left = left;
        this.right = right;
        this.size = left.size + right.size;
      }
      get break() {
        return this.flags & 1;
      }
      blockAt(height, oracle, top2, offset) {
        let mid = top2 + this.left.height;
        return height < mid ? this.left.blockAt(height, oracle, top2, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
      }
      lineAt(value2, type, oracle, top2, offset) {
        let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break;
        let left = type == QueryType.ByHeight ? value2 < rightTop : value2 < rightOffset;
        let base2 = left ? this.left.lineAt(value2, type, oracle, top2, offset) : this.right.lineAt(value2, type, oracle, rightTop, rightOffset);
        if (this.break || (left ? base2.to < rightOffset : base2.from > rightOffset))
          return base2;
        let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;
        if (left)
          return base2.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
        else
          return this.left.lineAt(rightOffset, subQuery, oracle, top2, offset).join(base2);
      }
      forEachLine(from, to2, oracle, top2, offset, f) {
        let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break;
        if (this.break) {
          if (from < rightOffset)
            this.left.forEachLine(from, to2, oracle, top2, offset, f);
          if (to2 >= rightOffset)
            this.right.forEachLine(from, to2, oracle, rightTop, rightOffset, f);
        } else {
          let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top2, offset);
          if (from < mid.from)
            this.left.forEachLine(from, mid.from - 1, oracle, top2, offset, f);
          if (mid.to >= from && mid.from <= to2)
            f(mid);
          if (to2 > mid.to)
            this.right.forEachLine(mid.to + 1, to2, oracle, rightTop, rightOffset, f);
        }
      }
      replace(from, to2, nodes) {
        let rightStart = this.left.length + this.break;
        if (to2 < rightStart)
          return this.balanced(this.left.replace(from, to2, nodes), this.right);
        if (from > this.left.length)
          return this.balanced(this.left, this.right.replace(from - rightStart, to2 - rightStart, nodes));
        let result2 = [];
        if (from > 0)
          this.decomposeLeft(from, result2);
        let left = result2.length;
        for (let node2 of nodes)
          result2.push(node2);
        if (from > 0)
          mergeGaps(result2, left - 1);
        if (to2 < this.length) {
          let right = result2.length;
          this.decomposeRight(to2, result2);
          mergeGaps(result2, right);
        }
        return HeightMap.of(result2);
      }
      decomposeLeft(to2, result2) {
        let left = this.left.length;
        if (to2 <= left)
          return this.left.decomposeLeft(to2, result2);
        result2.push(this.left);
        if (this.break) {
          left++;
          if (to2 >= left)
            result2.push(null);
        }
        if (to2 > left)
          this.right.decomposeLeft(to2 - left, result2);
      }
      decomposeRight(from, result2) {
        let left = this.left.length, right = left + this.break;
        if (from >= right)
          return this.right.decomposeRight(from - right, result2);
        if (from < left)
          this.left.decomposeRight(from, result2);
        if (this.break && from < right)
          result2.push(null);
        result2.push(this.right);
      }
      balanced(left, right) {
        if (left.size > 2 * right.size || right.size > 2 * left.size)
          return HeightMap.of(this.break ? [left, null, right] : [left, right]);
        this.left = replace(this.left, left);
        this.right = replace(this.right, right);
        this.setHeight(left.height + right.height);
        this.outdated = left.outdated || right.outdated;
        this.size = left.size + right.size;
        this.length = left.length + this.break + right.length;
        return this;
      }
      updateHeight(oracle, offset = 0, force = false, measured) {
        let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
        if (measured && measured.from <= offset + left.length && measured.more)
          rebalance = left = left.updateHeight(oracle, offset, force, measured);
        else
          left.updateHeight(oracle, offset, force);
        if (measured && measured.from <= rightStart + right.length && measured.more)
          rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
        else
          right.updateHeight(oracle, rightStart, force);
        if (rebalance)
          return this.balanced(left, right);
        this.height = this.left.height + this.right.height;
        this.outdated = false;
        return this;
      }
      toString() {
        return this.left + (this.break ? " " : "-") + this.right;
      }
    }
    function mergeGaps(nodes, around) {
      let before, after;
      if (nodes[around] == null && (before = nodes[around - 1]) instanceof HeightMapGap && (after = nodes[around + 1]) instanceof HeightMapGap)
        nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
    }
    const relevantWidgetHeight = 5;
    class NodeBuilder {
      constructor(pos2, oracle) {
        this.pos = pos2;
        this.oracle = oracle;
        this.nodes = [];
        this.lineStart = -1;
        this.lineEnd = -1;
        this.covering = null;
        this.writtenTo = pos2;
      }
      get isCovered() {
        return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
      }
      span(_from, to2) {
        if (this.lineStart > -1) {
          let end = Math.min(to2, this.lineEnd), last = this.nodes[this.nodes.length - 1];
          if (last instanceof HeightMapText)
            last.length += end - this.pos;
          else if (end > this.pos || !this.isCovered)
            this.nodes.push(new HeightMapText(end - this.pos, -1));
          this.writtenTo = end;
          if (to2 > end) {
            this.nodes.push(null);
            this.writtenTo++;
            this.lineStart = -1;
          }
        }
        this.pos = to2;
      }
      point(from, to2, deco) {
        if (from < to2 || deco.heightRelevant) {
          let height = deco.widget ? deco.widget.estimatedHeight : 0;
          let breaks = deco.widget ? deco.widget.lineBreaks : 0;
          if (height < 0)
            height = this.oracle.lineHeight;
          let len = to2 - from;
          if (deco.block) {
            this.addBlock(new HeightMapBlock(len, height, deco));
          } else if (len || breaks || height >= relevantWidgetHeight) {
            this.addLineDeco(height, breaks, len);
          }
        } else if (to2 > from) {
          this.span(from, to2);
        }
        if (this.lineEnd > -1 && this.lineEnd < this.pos)
          this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
      }
      enterLine() {
        if (this.lineStart > -1)
          return;
        let { from, to: to2 } = this.oracle.doc.lineAt(this.pos);
        this.lineStart = from;
        this.lineEnd = to2;
        if (this.writtenTo < from) {
          if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
            this.nodes.push(this.blankContent(this.writtenTo, from - 1));
          this.nodes.push(null);
        }
        if (this.pos > from)
          this.nodes.push(new HeightMapText(this.pos - from, -1));
        this.writtenTo = this.pos;
      }
      blankContent(from, to2) {
        let gap = new HeightMapGap(to2 - from);
        if (this.oracle.doc.lineAt(from).to == to2)
          gap.flags |= 4;
        return gap;
      }
      ensureLine() {
        this.enterLine();
        let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
        if (last instanceof HeightMapText)
          return last;
        let line2 = new HeightMapText(0, -1);
        this.nodes.push(line2);
        return line2;
      }
      addBlock(block2) {
        this.enterLine();
        let deco = block2.deco;
        if (deco && deco.startSide > 0 && !this.isCovered)
          this.ensureLine();
        this.nodes.push(block2);
        this.writtenTo = this.pos = this.pos + block2.length;
        if (deco && deco.endSide > 0)
          this.covering = block2;
      }
      addLineDeco(height, breaks, length) {
        let line2 = this.ensureLine();
        line2.length += length;
        line2.collapsed += length;
        line2.widgetHeight = Math.max(line2.widgetHeight, height);
        line2.breaks += breaks;
        this.writtenTo = this.pos = this.pos + length;
      }
      finish(from) {
        let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
        if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
          this.nodes.push(new HeightMapText(0, -1));
        else if (this.writtenTo < this.pos || last == null)
          this.nodes.push(this.blankContent(this.writtenTo, this.pos));
        let pos2 = from;
        for (let node2 of this.nodes) {
          if (node2 instanceof HeightMapText)
            node2.updateHeight(this.oracle, pos2);
          pos2 += node2 ? node2.length : 1;
        }
        return this.nodes;
      }
      // Always called with a region that on both sides either stretches
      // to a line break or the end of the document.
      // The returned array uses null to indicate line breaks, but never
      // starts or ends in a line break, or has multiple line breaks next
      // to each other.
      static build(oracle, decorations2, from, to2) {
        let builder = new NodeBuilder(from, oracle);
        RangeSet.spans(decorations2, from, to2, builder, 0);
        return builder.finish(from);
      }
    }
    function heightRelevantDecoChanges(a, b, diff2) {
      let comp = new DecorationComparator();
      RangeSet.compare(a, b, diff2, comp, 0);
      return comp.changes;
    }
    class DecorationComparator {
      constructor() {
        this.changes = [];
      }
      compareRange() {
      }
      comparePoint(from, to2, a, b) {
        if (from < to2 || a && a.heightRelevant || b && b.heightRelevant)
          addRange(from, to2, this.changes, 5);
      }
    }
    function visiblePixelRange(dom, paddingTop) {
      let rect = dom.getBoundingClientRect();
      let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
      let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);
      let top2 = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);
      for (let parent = dom.parentNode; parent && parent != doc2.body; ) {
        if (parent.nodeType == 1) {
          let elt = parent;
          let style2 = window.getComputedStyle(elt);
          if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style2.overflow != "visible") {
            let parentRect = elt.getBoundingClientRect();
            left = Math.max(left, parentRect.left);
            right = Math.min(right, parentRect.right);
            top2 = Math.max(top2, parentRect.top);
            bottom = Math.min(parent == dom.parentNode ? win.innerHeight : bottom, parentRect.bottom);
          }
          parent = style2.position == "absolute" || style2.position == "fixed" ? elt.offsetParent : elt.parentNode;
        } else if (parent.nodeType == 11) {
          parent = parent.host;
        } else {
          break;
        }
      }
      return {
        left: left - rect.left,
        right: Math.max(left, right) - rect.left,
        top: top2 - (rect.top + paddingTop),
        bottom: Math.max(top2, bottom) - (rect.top + paddingTop)
      };
    }
    function inWindow(elt) {
      let rect = elt.getBoundingClientRect(), win = elt.ownerDocument.defaultView || window;
      return rect.left < win.innerWidth && rect.right > 0 && rect.top < win.innerHeight && rect.bottom > 0;
    }
    function fullPixelRange(dom, paddingTop) {
      let rect = dom.getBoundingClientRect();
      return {
        left: 0,
        right: rect.right - rect.left,
        top: paddingTop,
        bottom: rect.bottom - (rect.top + paddingTop)
      };
    }
    class LineGap {
      constructor(from, to2, size, displaySize) {
        this.from = from;
        this.to = to2;
        this.size = size;
        this.displaySize = displaySize;
      }
      static same(a, b) {
        if (a.length != b.length)
          return false;
        for (let i2 = 0; i2 < a.length; i2++) {
          let gA = a[i2], gB = b[i2];
          if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
            return false;
        }
        return true;
      }
      draw(viewState, wrapping) {
        return Decoration.replace({
          widget: new LineGapWidget(this.displaySize * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
        }).range(this.from, this.to);
      }
    }
    class LineGapWidget extends WidgetType {
      constructor(size, vertical) {
        super();
        this.size = size;
        this.vertical = vertical;
      }
      eq(other) {
        return other.size == this.size && other.vertical == this.vertical;
      }
      toDOM() {
        let elt = document.createElement("div");
        if (this.vertical) {
          elt.style.height = this.size + "px";
        } else {
          elt.style.width = this.size + "px";
          elt.style.height = "2px";
          elt.style.display = "inline-block";
        }
        return elt;
      }
      get estimatedHeight() {
        return this.vertical ? this.size : -1;
      }
    }
    class ViewState {
      constructor(state) {
        this.state = state;
        this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
        this.inView = true;
        this.paddingTop = 0;
        this.paddingBottom = 0;
        this.contentDOMWidth = 0;
        this.contentDOMHeight = 0;
        this.editorHeight = 0;
        this.editorWidth = 0;
        this.scrollTop = 0;
        this.scrolledToBottom = false;
        this.scaleX = 1;
        this.scaleY = 1;
        this.scrollAnchorPos = 0;
        this.scrollAnchorHeight = -1;
        this.scaler = IdScaler;
        this.scrollTarget = null;
        this.printing = false;
        this.mustMeasureContent = true;
        this.defaultTextDirection = Direction.LTR;
        this.visibleRanges = [];
        this.mustEnforceCursorAssoc = false;
        let guessWrapping = state.facet(contentAttributes).some((v) => typeof v != "function" && v.class == "cm-lineWrapping");
        this.heightOracle = new HeightOracle(guessWrapping);
        this.stateDeco = state.facet(decorations).filter((d) => typeof d != "function");
        this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
        for (let i2 = 0; i2 < 2; i2++) {
          this.viewport = this.getViewport(0, null);
          if (!this.updateForViewport())
            break;
        }
        this.updateViewportLines();
        this.lineGaps = this.ensureLineGaps([]);
        this.lineGapDeco = Decoration.set(this.lineGaps.map((gap) => gap.draw(this, false)));
        this.computeVisibleRanges();
      }
      updateForViewport() {
        let viewports = [this.viewport], { main } = this.state.selection;
        for (let i2 = 0; i2 <= 1; i2++) {
          let pos2 = i2 ? main.head : main.anchor;
          if (!viewports.some(({ from, to: to2 }) => pos2 >= from && pos2 <= to2)) {
            let { from, to: to2 } = this.lineBlockAt(pos2);
            viewports.push(new Viewport(from, to2));
          }
        }
        this.viewports = viewports.sort((a, b) => a.from - b.from);
        return this.updateScaler();
      }
      updateScaler() {
        let scaler = this.scaler;
        this.scaler = this.heightMap.height <= 7e6 ? IdScaler : new BigScaler(this.heightOracle, this.heightMap, this.viewports);
        return scaler.eq(this.scaler) ? 0 : 2;
      }
      updateViewportLines() {
        this.viewportLines = [];
        this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, (block2) => {
          this.viewportLines.push(scaleBlock(block2, this.scaler));
        });
      }
      update(update, scrollTarget = null) {
        this.state = update.state;
        let prevDeco = this.stateDeco;
        this.stateDeco = this.state.facet(decorations).filter((d) => typeof d != "function");
        let contentChanges = update.changedRanges;
        let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
        let prevHeight = this.heightMap.height;
        let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
        clearHeightChangeFlag();
        this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
        if (this.heightMap.height != prevHeight || heightChangeFlag)
          update.flags |= 2;
        if (scrollAnchor) {
          this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);
          this.scrollAnchorHeight = scrollAnchor.top;
        } else {
          this.scrollAnchorPos = -1;
          this.scrollAnchorHeight = this.heightMap.height;
        }
        let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
        if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || !this.viewportIsAppropriate(viewport))
          viewport = this.getViewport(0, scrollTarget);
        let viewportChange = viewport.from != this.viewport.from || viewport.to != this.viewport.to;
        this.viewport = viewport;
        update.flags |= this.updateForViewport();
        if (viewportChange || !update.changes.empty || update.flags & 2)
          this.updateViewportLines();
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
          this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
        update.flags |= this.computeVisibleRanges(update.changes);
        if (scrollTarget)
          this.scrollTarget = scrollTarget;
        if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && update.state.selection.main.empty && update.state.selection.main.assoc && !update.state.facet(nativeSelectionHidden))
          this.mustEnforceCursorAssoc = true;
      }
      measure(view) {
        let dom = view.contentDOM, style2 = window.getComputedStyle(dom);
        let oracle = this.heightOracle;
        let whiteSpace = style2.whiteSpace;
        this.defaultTextDirection = style2.direction == "rtl" ? Direction.RTL : Direction.LTR;
        let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
        let domRect = dom.getBoundingClientRect();
        let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
        this.contentDOMHeight = domRect.height;
        this.mustMeasureContent = false;
        let result2 = 0, bias = 0;
        if (domRect.width && domRect.height) {
          let { scaleX, scaleY } = getScale(dom, domRect);
          if (scaleX > 5e-3 && Math.abs(this.scaleX - scaleX) > 5e-3 || scaleY > 5e-3 && Math.abs(this.scaleY - scaleY) > 5e-3) {
            this.scaleX = scaleX;
            this.scaleY = scaleY;
            result2 |= 16;
            refresh = measureContent = true;
          }
        }
        let paddingTop = (parseInt(style2.paddingTop) || 0) * this.scaleY;
        let paddingBottom = (parseInt(style2.paddingBottom) || 0) * this.scaleY;
        if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
          this.paddingTop = paddingTop;
          this.paddingBottom = paddingBottom;
          result2 |= 16 | 2;
        }
        if (this.editorWidth != view.scrollDOM.clientWidth) {
          if (oracle.lineWrapping)
            measureContent = true;
          this.editorWidth = view.scrollDOM.clientWidth;
          result2 |= 16;
        }
        let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
        if (this.scrollTop != scrollTop) {
          this.scrollAnchorHeight = -1;
          this.scrollTop = scrollTop;
        }
        this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
        let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
        let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
        this.pixelViewport = pixelViewport;
        let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
        if (inView != this.inView) {
          this.inView = inView;
          if (inView)
            measureContent = true;
        }
        if (!this.inView && !this.scrollTarget && !inWindow(view.dom))
          return 0;
        let contentWidth = domRect.width;
        if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
          this.contentDOMWidth = domRect.width;
          this.editorHeight = view.scrollDOM.clientHeight;
          result2 |= 16;
        }
        if (measureContent) {
          let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
          if (oracle.mustRefreshForHeights(lineHeights))
            refresh = true;
          if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
            let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();
            refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);
            if (refresh) {
              view.docView.minWidth = 0;
              result2 |= 16;
            }
          }
          if (dTop > 0 && dBottom > 0)
            bias = Math.max(dTop, dBottom);
          else if (dTop < 0 && dBottom < 0)
            bias = Math.min(dTop, dBottom);
          clearHeightChangeFlag();
          for (let vp of this.viewports) {
            let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
            this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));
          }
          if (heightChangeFlag)
            result2 |= 2;
        }
        let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to);
        if (viewportChange) {
          if (result2 & 2)
            result2 |= this.updateScaler();
          this.viewport = this.getViewport(bias, this.scrollTarget);
          result2 |= this.updateForViewport();
        }
        if (result2 & 2 || viewportChange)
          this.updateViewportLines();
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
          this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
        result2 |= this.computeVisibleRanges();
        if (this.mustEnforceCursorAssoc) {
          this.mustEnforceCursorAssoc = false;
          view.docView.enforceCursorAssoc();
        }
        return result2;
      }
      get visibleTop() {
        return this.scaler.fromDOM(this.pixelViewport.top);
      }
      get visibleBottom() {
        return this.scaler.fromDOM(this.pixelViewport.bottom);
      }
      getViewport(bias, scrollTarget) {
        let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1e3 / 2));
        let map2 = this.heightMap, oracle = this.heightOracle;
        let { visibleTop, visibleBottom } = this;
        let viewport = new Viewport(map2.lineAt(visibleTop - marginTop * 1e3, QueryType.ByHeight, oracle, 0, 0).from, map2.lineAt(visibleBottom + (1 - marginTop) * 1e3, QueryType.ByHeight, oracle, 0, 0).to);
        if (scrollTarget) {
          let { head } = scrollTarget.range;
          if (head < viewport.from || head > viewport.to) {
            let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
            let block2 = map2.lineAt(head, QueryType.ByPos, oracle, 0, 0), topPos;
            if (scrollTarget.y == "center")
              topPos = (block2.top + block2.bottom) / 2 - viewHeight / 2;
            else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from)
              topPos = block2.top;
            else
              topPos = block2.bottom - viewHeight;
            viewport = new Viewport(map2.lineAt(topPos - 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).from, map2.lineAt(topPos + viewHeight + 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).to);
          }
        }
        return viewport;
      }
      mapViewport(viewport, changes) {
        let from = changes.mapPos(viewport.from, -1), to2 = changes.mapPos(viewport.to, 1);
        return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to2, QueryType.ByPos, this.heightOracle, 0, 0).to);
      }
      // Checks if a given viewport covers the visible part of the
      // document and not too much beyond that.
      viewportIsAppropriate({ from, to: to2 }, bias = 0) {
        if (!this.inView)
          return true;
        let { top: top2 } = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);
        let { bottom } = this.heightMap.lineAt(to2, QueryType.ByPos, this.heightOracle, 0, 0);
        let { visibleTop, visibleBottom } = this;
        return (from == 0 || top2 <= visibleTop - Math.max(10, Math.min(
          -bias,
          250
          /* VP.MaxCoverMargin */
        ))) && (to2 == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(
          bias,
          250
          /* VP.MaxCoverMargin */
        ))) && (top2 > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3);
      }
      mapLineGaps(gaps, changes) {
        if (!gaps.length || changes.empty)
          return gaps;
        let mapped = [];
        for (let gap of gaps)
          if (!changes.touchesRange(gap.from, gap.to))
            mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size, gap.displaySize));
        return mapped;
      }
      // Computes positions in the viewport where the start or end of a
      // line should be hidden, trying to reuse existing line gaps when
      // appropriate to avoid unneccesary redraws.
      // Uses crude character-counting for the positioning and sizing,
      // since actual DOM coordinates aren't always available and
      // predictable. Relies on generous margins (see LG.Margin) to hide
      // the artifacts this might produce from the user.
      ensureLineGaps(current, mayMeasure) {
        let wrapping = this.heightOracle.lineWrapping;
        let margin = wrapping ? 1e4 : 2e3, halfMargin = margin >> 1, doubleMargin = margin << 1;
        if (this.defaultTextDirection != Direction.LTR && !wrapping)
          return [];
        let gaps = [];
        let addGap = (from, to2, line2, structure) => {
          if (to2 - from < halfMargin)
            return;
          let sel = this.state.selection.main, avoid = [sel.from];
          if (!sel.empty)
            avoid.push(sel.to);
          for (let pos2 of avoid) {
            if (pos2 > from && pos2 < to2) {
              addGap(from, pos2 - 10, line2, structure);
              addGap(pos2 + 10, to2, line2, structure);
              return;
            }
          }
          let gap = find(current, (gap2) => gap2.from >= line2.from && gap2.to <= line2.to && Math.abs(gap2.from - from) < halfMargin && Math.abs(gap2.to - to2) < halfMargin && !avoid.some((pos2) => gap2.from < pos2 && gap2.to > pos2));
          if (!gap) {
            if (to2 < line2.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some((r2) => r2.from <= to2 && r2.to >= to2)) {
              let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to2), false, true).head;
              if (lineStart > from)
                to2 = lineStart;
            }
            let size = this.gapSize(line2, from, to2, structure);
            let displaySize = wrapping || size < 2e6 ? size : 2e6;
            gap = new LineGap(from, to2, size, displaySize);
          }
          gaps.push(gap);
        };
        let checkLine = (line2) => {
          if (line2.length < doubleMargin || line2.type != BlockType.Text)
            return;
          let structure = lineStructure(line2.from, line2.to, this.stateDeco);
          if (structure.total < doubleMargin)
            return;
          let target2 = this.scrollTarget ? this.scrollTarget.range.head : null;
          let viewFrom, viewTo;
          if (wrapping) {
            let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight;
            let top2, bot;
            if (target2 != null) {
              let targetFrac = findFraction(structure, target2);
              let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line2.height;
              top2 = targetFrac - spaceFrac;
              bot = targetFrac + spaceFrac;
            } else {
              top2 = (this.visibleTop - line2.top - marginHeight) / line2.height;
              bot = (this.visibleBottom - line2.top + marginHeight) / line2.height;
            }
            viewFrom = findPosition(structure, top2);
            viewTo = findPosition(structure, bot);
          } else {
            let totalWidth = structure.total * this.heightOracle.charWidth;
            let marginWidth = margin * this.heightOracle.charWidth;
            let horizOffset = 0;
            if (totalWidth > 2e6)
              for (let old of current) {
                if (old.from >= line2.from && old.from < line2.to && old.size != old.displaySize && old.from * this.heightOracle.charWidth + horizOffset < this.pixelViewport.left)
                  horizOffset = old.size - old.displaySize;
              }
            let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset;
            let left, right;
            if (target2 != null) {
              let targetFrac = findFraction(structure, target2);
              let spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth;
              left = targetFrac - spaceFrac;
              right = targetFrac + spaceFrac;
            } else {
              left = (pxLeft - marginWidth) / totalWidth;
              right = (pxRight + marginWidth) / totalWidth;
            }
            viewFrom = findPosition(structure, left);
            viewTo = findPosition(structure, right);
          }
          if (viewFrom > line2.from)
            addGap(line2.from, viewFrom, line2, structure);
          if (viewTo < line2.to)
            addGap(viewTo, line2.to, line2, structure);
        };
        for (let line2 of this.viewportLines) {
          if (Array.isArray(line2.type))
            line2.type.forEach(checkLine);
          else
            checkLine(line2);
        }
        return gaps;
      }
      gapSize(line2, from, to2, structure) {
        let fraction = findFraction(structure, to2) - findFraction(structure, from);
        if (this.heightOracle.lineWrapping) {
          return line2.height * fraction;
        } else {
          return structure.total * this.heightOracle.charWidth * fraction;
        }
      }
      updateLineGaps(gaps) {
        if (!LineGap.same(gaps, this.lineGaps)) {
          this.lineGaps = gaps;
          this.lineGapDeco = Decoration.set(gaps.map((gap) => gap.draw(this, this.heightOracle.lineWrapping)));
        }
      }
      computeVisibleRanges(changes) {
        let deco = this.stateDeco;
        if (this.lineGaps.length)
          deco = deco.concat(this.lineGapDeco);
        let ranges = [];
        RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
          span(from, to2) {
            ranges.push({ from, to: to2 });
          },
          point() {
          }
        }, 20);
        let changed = 0;
        if (ranges.length != this.visibleRanges.length) {
          changed = 8 | 4;
        } else {
          for (let i2 = 0; i2 < ranges.length && !(changed & 8); i2++) {
            let old = this.visibleRanges[i2], nw = ranges[i2];
            if (old.from != nw.from || old.to != nw.to) {
              changed |= 4;
              if (!(changes && changes.mapPos(old.from, -1) == nw.from && changes.mapPos(old.to, 1) == nw.to))
                changed |= 8;
            }
          }
        }
        this.visibleRanges = ranges;
        return changed;
      }
      lineBlockAt(pos2) {
        return pos2 >= this.viewport.from && pos2 <= this.viewport.to && this.viewportLines.find((b) => b.from <= pos2 && b.to >= pos2) || scaleBlock(this.heightMap.lineAt(pos2, QueryType.ByPos, this.heightOracle, 0, 0), this.scaler);
      }
      lineBlockAtHeight(height) {
        return height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom && this.viewportLines.find((l) => l.top <= height && l.bottom >= height) || scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);
      }
      scrollAnchorAt(scrollTop) {
        let block2 = this.lineBlockAtHeight(scrollTop + 8);
        return block2.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block2 : this.viewportLines[0];
      }
      elementAtHeight(height) {
        return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
      }
      get docHeight() {
        return this.scaler.toDOM(this.heightMap.height);
      }
      get contentHeight() {
        return this.docHeight + this.paddingTop + this.paddingBottom;
      }
    }
    class Viewport {
      constructor(from, to2) {
        this.from = from;
        this.to = to2;
      }
    }
    function lineStructure(from, to2, stateDeco) {
      let ranges = [], pos2 = from, total = 0;
      RangeSet.spans(stateDeco, from, to2, {
        span() {
        },
        point(from2, to3) {
          if (from2 > pos2) {
            ranges.push({ from: pos2, to: from2 });
            total += from2 - pos2;
          }
          pos2 = to3;
        }
      }, 20);
      if (pos2 < to2) {
        ranges.push({ from: pos2, to: to2 });
        total += to2 - pos2;
      }
      return { total, ranges };
    }
    function findPosition({ total, ranges }, ratio) {
      if (ratio <= 0)
        return ranges[0].from;
      if (ratio >= 1)
        return ranges[ranges.length - 1].to;
      let dist2 = Math.floor(total * ratio);
      for (let i2 = 0; ; i2++) {
        let { from, to: to2 } = ranges[i2], size = to2 - from;
        if (dist2 <= size)
          return from + dist2;
        dist2 -= size;
      }
    }
    function findFraction(structure, pos2) {
      let counted = 0;
      for (let { from, to: to2 } of structure.ranges) {
        if (pos2 <= to2) {
          counted += pos2 - from;
          break;
        }
        counted += to2 - from;
      }
      return counted / structure.total;
    }
    function find(array, f) {
      for (let val of array)
        if (f(val))
          return val;
      return void 0;
    }
    const IdScaler = {
      toDOM(n) {
        return n;
      },
      fromDOM(n) {
        return n;
      },
      scale: 1,
      eq(other) {
        return other == this;
      }
    };
    class BigScaler {
      constructor(oracle, heightMap, viewports) {
        let vpHeight = 0, base2 = 0, domBase = 0;
        this.viewports = viewports.map(({ from, to: to2 }) => {
          let top2 = heightMap.lineAt(from, QueryType.ByPos, oracle, 0, 0).top;
          let bottom = heightMap.lineAt(to2, QueryType.ByPos, oracle, 0, 0).bottom;
          vpHeight += bottom - top2;
          return { from, to: to2, top: top2, bottom, domTop: 0, domBottom: 0 };
        });
        this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight);
        for (let obj of this.viewports) {
          obj.domTop = domBase + (obj.top - base2) * this.scale;
          domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
          base2 = obj.bottom;
        }
      }
      toDOM(n) {
        for (let i2 = 0, base2 = 0, domBase = 0; ; i2++) {
          let vp = i2 < this.viewports.length ? this.viewports[i2] : null;
          if (!vp || n < vp.top)
            return domBase + (n - base2) * this.scale;
          if (n <= vp.bottom)
            return vp.domTop + (n - vp.top);
          base2 = vp.bottom;
          domBase = vp.domBottom;
        }
      }
      fromDOM(n) {
        for (let i2 = 0, base2 = 0, domBase = 0; ; i2++) {
          let vp = i2 < this.viewports.length ? this.viewports[i2] : null;
          if (!vp || n < vp.domTop)
            return base2 + (n - domBase) / this.scale;
          if (n <= vp.domBottom)
            return vp.top + (n - vp.domTop);
          base2 = vp.bottom;
          domBase = vp.domBottom;
        }
      }
      eq(other) {
        if (!(other instanceof BigScaler))
          return false;
        return this.scale == other.scale && this.viewports.length == other.viewports.length && this.viewports.every((vp, i2) => vp.from == other.viewports[i2].from && vp.to == other.viewports[i2].to);
      }
    }
    function scaleBlock(block2, scaler) {
      if (scaler.scale == 1)
        return block2;
      let bTop = scaler.toDOM(block2.top), bBottom = scaler.toDOM(block2.bottom);
      return new BlockInfo(block2.from, block2.length, bTop, bBottom - bTop, Array.isArray(block2._content) ? block2._content.map((b) => scaleBlock(b, scaler)) : block2._content);
    }
    const theme = /* @__PURE__ */ Facet.define({ combine: (strs) => strs.join(" ") });
    const darkTheme = /* @__PURE__ */ Facet.define({ combine: (values) => values.indexOf(true) > -1 });
    const baseThemeID = /* @__PURE__ */ StyleModule.newName(), baseLightID = /* @__PURE__ */ StyleModule.newName(), baseDarkID = /* @__PURE__ */ StyleModule.newName();
    const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
    function buildTheme(main, spec, scopes) {
      return new StyleModule(spec, {
        finish(sel) {
          return /&/.test(sel) ? sel.replace(/&\w*/, (m) => {
            if (m == "&")
              return main;
            if (!scopes || !scopes[m])
              throw new RangeError(`Unsupported selector: ${m}`);
            return scopes[m];
          }) : main + " " + sel;
        }
      });
    }
    const baseTheme$1$1 = /* @__PURE__ */ buildTheme("." + baseThemeID, {
      "&": {
        position: "relative !important",
        boxSizing: "border-box",
        "&.cm-focused": {
          // Provide a simple default outline to make sure a focused
          // editor is visually distinct. Can't leave the default behavior
          // because that will apply to the content element, which is
          // inside the scrollable container and doesn't include the
          // gutters. We also can't use an 'auto' outline, since those
          // are, for some reason, drawn behind the element content, which
          // will cause things like the active line background to cover
          // the outline (#297).
          outline: "1px dotted #212121"
        },
        display: "flex !important",
        flexDirection: "column"
      },
      ".cm-scroller": {
        display: "flex !important",
        alignItems: "flex-start !important",
        fontFamily: "monospace",
        lineHeight: 1.4,
        height: "100%",
        overflowX: "auto",
        position: "relative",
        zIndex: 0,
        overflowAnchor: "none"
      },
      ".cm-content": {
        margin: 0,
        flexGrow: 2,
        flexShrink: 0,
        display: "block",
        whiteSpace: "pre",
        wordWrap: "normal",
        // https://github.com/codemirror/dev/issues/456
        boxSizing: "border-box",
        minHeight: "100%",
        padding: "4px 0",
        outline: "none",
        "&[contenteditable=true]": {
          WebkitUserModify: "read-write-plaintext-only"
        }
      },
      ".cm-lineWrapping": {
        whiteSpace_fallback: "pre-wrap",
        // For IE
        whiteSpace: "break-spaces",
        wordBreak: "break-word",
        // For Safari, which doesn't support overflow-wrap: anywhere
        overflowWrap: "anywhere",
        flexShrink: 1
      },
      "&light .cm-content": { caretColor: "black" },
      "&dark .cm-content": { caretColor: "white" },
      ".cm-line": {
        display: "block",
        padding: "0 2px 0 6px"
      },
      ".cm-layer": {
        position: "absolute",
        left: 0,
        top: 0,
        contain: "size style",
        "& > *": {
          position: "absolute"
        }
      },
      "&light .cm-selectionBackground": {
        background: "#d9d9d9"
      },
      "&dark .cm-selectionBackground": {
        background: "#222"
      },
      "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
        background: "#d7d4f0"
      },
      "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
        background: "#233"
      },
      ".cm-cursorLayer": {
        pointerEvents: "none"
      },
      "&.cm-focused > .cm-scroller > .cm-cursorLayer": {
        animation: "steps(1) cm-blink 1.2s infinite"
      },
      // Two animations defined so that we can switch between them to
      // restart the animation without forcing another style
      // recomputation.
      "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
      "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
      ".cm-cursor, .cm-dropCursor": {
        borderLeft: "1.2px solid black",
        marginLeft: "-0.6px",
        pointerEvents: "none"
      },
      ".cm-cursor": {
        display: "none"
      },
      "&dark .cm-cursor": {
        borderLeftColor: "#ddd"
      },
      ".cm-dropCursor": {
        position: "absolute"
      },
      "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
        display: "block"
      },
      ".cm-iso": {
        unicodeBidi: "isolate"
      },
      ".cm-announced": {
        position: "fixed",
        top: "-10000px"
      },
      "@media print": {
        ".cm-announced": { display: "none" }
      },
      "&light .cm-activeLine": { backgroundColor: "#cceeff44" },
      "&dark .cm-activeLine": { backgroundColor: "#99eeff33" },
      "&light .cm-specialChar": { color: "red" },
      "&dark .cm-specialChar": { color: "#f78" },
      ".cm-gutters": {
        flexShrink: 0,
        display: "flex",
        height: "100%",
        boxSizing: "border-box",
        insetInlineStart: 0,
        zIndex: 200
      },
      "&light .cm-gutters": {
        backgroundColor: "#f5f5f5",
        color: "#6c6c6c",
        borderRight: "1px solid #ddd"
      },
      "&dark .cm-gutters": {
        backgroundColor: "#333338",
        color: "#ccc"
      },
      ".cm-gutter": {
        display: "flex !important",
        // Necessary -- prevents margin collapsing
        flexDirection: "column",
        flexShrink: 0,
        boxSizing: "border-box",
        minHeight: "100%",
        overflow: "hidden"
      },
      ".cm-gutterElement": {
        boxSizing: "border-box"
      },
      ".cm-lineNumbers .cm-gutterElement": {
        padding: "0 3px 0 5px",
        minWidth: "20px",
        textAlign: "right",
        whiteSpace: "nowrap"
      },
      "&light .cm-activeLineGutter": {
        backgroundColor: "#e2f2ff"
      },
      "&dark .cm-activeLineGutter": {
        backgroundColor: "#222227"
      },
      ".cm-panels": {
        boxSizing: "border-box",
        position: "sticky",
        left: 0,
        right: 0,
        zIndex: 300
      },
      "&light .cm-panels": {
        backgroundColor: "#f5f5f5",
        color: "black"
      },
      "&light .cm-panels-top": {
        borderBottom: "1px solid #ddd"
      },
      "&light .cm-panels-bottom": {
        borderTop: "1px solid #ddd"
      },
      "&dark .cm-panels": {
        backgroundColor: "#333338",
        color: "white"
      },
      ".cm-tab": {
        display: "inline-block",
        overflow: "hidden",
        verticalAlign: "bottom"
      },
      ".cm-widgetBuffer": {
        verticalAlign: "text-top",
        height: "1em",
        width: 0,
        display: "inline"
      },
      ".cm-placeholder": {
        color: "#888",
        display: "inline-block",
        verticalAlign: "top"
      },
      ".cm-highlightSpace": {
        backgroundImage: "radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",
        backgroundPosition: "center"
      },
      ".cm-highlightTab": {
        backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,
        backgroundSize: "auto 100%",
        backgroundPosition: "right 90%",
        backgroundRepeat: "no-repeat"
      },
      ".cm-trailingSpace": {
        backgroundColor: "#ff332255"
      },
      ".cm-button": {
        verticalAlign: "middle",
        color: "inherit",
        fontSize: "70%",
        padding: ".2em 1em",
        borderRadius: "1px"
      },
      "&light .cm-button": {
        backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
        border: "1px solid #888",
        "&:active": {
          backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
        }
      },
      "&dark .cm-button": {
        backgroundImage: "linear-gradient(#393939, #111)",
        border: "1px solid #888",
        "&:active": {
          backgroundImage: "linear-gradient(#111, #333)"
        }
      },
      ".cm-textfield": {
        verticalAlign: "middle",
        color: "inherit",
        fontSize: "70%",
        border: "1px solid silver",
        padding: ".2em .5em"
      },
      "&light .cm-textfield": {
        backgroundColor: "white"
      },
      "&dark .cm-textfield": {
        border: "1px solid #555",
        backgroundColor: "inherit"
      }
    }, lightDarkIDs);
    const observeOptions = {
      childList: true,
      characterData: true,
      subtree: true,
      attributes: true,
      characterDataOldValue: true
    };
    const useCharData = browser.ie && browser.ie_version <= 11;
    class DOMObserver {
      constructor(view) {
        this.view = view;
        this.active = false;
        this.editContext = null;
        this.selectionRange = new DOMSelectionState();
        this.selectionChanged = false;
        this.delayedFlush = -1;
        this.resizeTimeout = -1;
        this.queue = [];
        this.delayedAndroidKey = null;
        this.flushingAndroidKey = -1;
        this.lastChange = 0;
        this.scrollTargets = [];
        this.intersection = null;
        this.resizeScroll = null;
        this.intersecting = false;
        this.gapIntersection = null;
        this.gaps = [];
        this.printQuery = null;
        this.parentCheck = -1;
        this.dom = view.contentDOM;
        this.observer = new MutationObserver((mutations) => {
          for (let mut of mutations)
            this.queue.push(mut);
          if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length))
            this.flushSoon();
          else
            this.flush();
        });
        if (window.EditContext && view.constructor.EDIT_CONTEXT !== false && // Chrome <126 doesn't support inverted selections in edit context (#1392)
        !(browser.chrome && browser.chrome_version < 126)) {
          this.editContext = new EditContextManager(view);
          if (view.state.facet(editable))
            view.contentDOM.editContext = this.editContext.editContext;
        }
        if (useCharData)
          this.onCharData = (event) => {
            this.queue.push({
              target: event.target,
              type: "characterData",
              oldValue: event.prevValue
            });
            this.flushSoon();
          };
        this.onSelectionChange = this.onSelectionChange.bind(this);
        this.onResize = this.onResize.bind(this);
        this.onPrint = this.onPrint.bind(this);
        this.onScroll = this.onScroll.bind(this);
        if (window.matchMedia)
          this.printQuery = window.matchMedia("print");
        if (typeof ResizeObserver == "function") {
          this.resizeScroll = new ResizeObserver(() => {
            var _a2;
            if (((_a2 = this.view.docView) === null || _a2 === void 0 ? void 0 : _a2.lastUpdate) < Date.now() - 75)
              this.onResize();
          });
          this.resizeScroll.observe(view.scrollDOM);
        }
        this.addWindowListeners(this.win = view.win);
        this.start();
        if (typeof IntersectionObserver == "function") {
          this.intersection = new IntersectionObserver((entries) => {
            if (this.parentCheck < 0)
              this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3);
            if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 != this.intersecting) {
              this.intersecting = !this.intersecting;
              if (this.intersecting != this.view.inView)
                this.onScrollChanged(document.createEvent("Event"));
            }
          }, { threshold: [0, 1e-3] });
          this.intersection.observe(this.dom);
          this.gapIntersection = new IntersectionObserver((entries) => {
            if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
              this.onScrollChanged(document.createEvent("Event"));
          }, {});
        }
        this.listenForScroll();
        this.readSelectionRange();
      }
      onScrollChanged(e) {
        this.view.inputState.runHandlers("scroll", e);
        if (this.intersecting)
          this.view.measure();
      }
      onScroll(e) {
        if (this.intersecting)
          this.flush(false);
        if (this.editContext)
          this.view.requestMeasure(this.editContext.measureReq);
        this.onScrollChanged(e);
      }
      onResize() {
        if (this.resizeTimeout < 0)
          this.resizeTimeout = setTimeout(() => {
            this.resizeTimeout = -1;
            this.view.requestMeasure();
          }, 50);
      }
      onPrint(event) {
        if ((event.type == "change" || !event.type) && !event.matches)
          return;
        this.view.viewState.printing = true;
        this.view.measure();
        setTimeout(() => {
          this.view.viewState.printing = false;
          this.view.requestMeasure();
        }, 500);
      }
      updateGaps(gaps) {
        if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i2) => g != gaps[i2]))) {
          this.gapIntersection.disconnect();
          for (let gap of gaps)
            this.gapIntersection.observe(gap);
          this.gaps = gaps;
        }
      }
      onSelectionChange(event) {
        let wasChanged = this.selectionChanged;
        if (!this.readSelectionRange() || this.delayedAndroidKey)
          return;
        let { view } = this, sel = this.selectionRange;
        if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(this.dom, sel))
          return;
        let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);
        if (context && context.ignoreEvent(event)) {
          if (!wasChanged)
            this.selectionChanged = false;
          return;
        }
        if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && // (Selection.isCollapsed isn't reliable on IE)
        sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
          this.flushSoon();
        else
          this.flush(false);
      }
      readSelectionRange() {
        let { view } = this;
        let selection = getSelection(view.root);
        if (!selection)
          return false;
        let range = browser.safari && view.root.nodeType == 11 && view.root.activeElement == this.dom && safariSelectionRangeHack(this.view, selection) || selection;
        if (!range || this.selectionRange.eq(range))
          return false;
        let local = hasSelection(this.dom, range);
        if (local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart(this.dom, range)) {
          this.view.inputState.lastFocusTime = 0;
          view.docView.updateSelection();
          return false;
        }
        this.selectionRange.setRange(range);
        if (local)
          this.selectionChanged = true;
        return true;
      }
      setSelectionRange(anchor, head) {
        this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
        this.selectionChanged = false;
      }
      clearSelectionRange() {
        this.selectionRange.set(null, 0, null, 0);
      }
      listenForScroll() {
        this.parentCheck = -1;
        let i2 = 0, changed = null;
        for (let dom = this.dom; dom; ) {
          if (dom.nodeType == 1) {
            if (!changed && i2 < this.scrollTargets.length && this.scrollTargets[i2] == dom)
              i2++;
            else if (!changed)
              changed = this.scrollTargets.slice(0, i2);
            if (changed)
              changed.push(dom);
            dom = dom.assignedSlot || dom.parentNode;
          } else if (dom.nodeType == 11) {
            dom = dom.host;
          } else {
            break;
          }
        }
        if (i2 < this.scrollTargets.length && !changed)
          changed = this.scrollTargets.slice(0, i2);
        if (changed) {
          for (let dom of this.scrollTargets)
            dom.removeEventListener("scroll", this.onScroll);
          for (let dom of this.scrollTargets = changed)
            dom.addEventListener("scroll", this.onScroll);
        }
      }
      ignore(f) {
        if (!this.active)
          return f();
        try {
          this.stop();
          return f();
        } finally {
          this.start();
          this.clear();
        }
      }
      start() {
        if (this.active)
          return;
        this.observer.observe(this.dom, observeOptions);
        if (useCharData)
          this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
        this.active = true;
      }
      stop() {
        if (!this.active)
          return;
        this.active = false;
        this.observer.disconnect();
        if (useCharData)
          this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
      }
      // Throw away any pending changes
      clear() {
        this.processRecords();
        this.queue.length = 0;
        this.selectionChanged = false;
      }
      // Chrome Android, especially in combination with GBoard, not only
      // doesn't reliably fire regular key events, but also often
      // surrounds the effect of enter or backspace with a bunch of
      // composition events that, when interrupted, cause text duplication
      // or other kinds of corruption. This hack makes the editor back off
      // from handling DOM changes for a moment when such a key is
      // detected (via beforeinput or keydown), and then tries to flush
      // them or, if that has no effect, dispatches the given key.
      delayAndroidKey(key2, keyCode) {
        var _a2;
        if (!this.delayedAndroidKey) {
          let flush = () => {
            let key3 = this.delayedAndroidKey;
            if (key3) {
              this.clearDelayedAndroidKey();
              this.view.inputState.lastKeyCode = key3.keyCode;
              this.view.inputState.lastKeyTime = Date.now();
              let flushed = this.flush();
              if (!flushed && key3.force)
                dispatchKey(this.dom, key3.key, key3.keyCode);
            }
          };
          this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
        }
        if (!this.delayedAndroidKey || key2 == "Enter")
          this.delayedAndroidKey = {
            key: key2,
            keyCode,
            // Only run the key handler when no changes are detected if
            // this isn't coming right after another change, in which case
            // it is probably part of a weird chain of updates, and should
            // be ignored if it returns the DOM to its previous state.
            force: this.lastChange < Date.now() - 50 || !!((_a2 = this.delayedAndroidKey) === null || _a2 === void 0 ? void 0 : _a2.force)
          };
      }
      clearDelayedAndroidKey() {
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
        this.delayedAndroidKey = null;
        this.flushingAndroidKey = -1;
      }
      flushSoon() {
        if (this.delayedFlush < 0)
          this.delayedFlush = this.view.win.requestAnimationFrame(() => {
            this.delayedFlush = -1;
            this.flush();
          });
      }
      forceFlush() {
        if (this.delayedFlush >= 0) {
          this.view.win.cancelAnimationFrame(this.delayedFlush);
          this.delayedFlush = -1;
        }
        this.flush();
      }
      pendingRecords() {
        for (let mut of this.observer.takeRecords())
          this.queue.push(mut);
        return this.queue;
      }
      processRecords() {
        let records = this.pendingRecords();
        if (records.length)
          this.queue = [];
        let from = -1, to2 = -1, typeOver = false;
        for (let record of records) {
          let range = this.readMutation(record);
          if (!range)
            continue;
          if (range.typeOver)
            typeOver = true;
          if (from == -1) {
            ({ from, to: to2 } = range);
          } else {
            from = Math.min(range.from, from);
            to2 = Math.max(range.to, to2);
          }
        }
        return { from, to: to2, typeOver };
      }
      readChange() {
        let { from, to: to2, typeOver } = this.processRecords();
        let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
        if (from < 0 && !newSel)
          return null;
        if (from > -1)
          this.lastChange = Date.now();
        this.view.inputState.lastFocusTime = 0;
        this.selectionChanged = false;
        let change = new DOMChange(this.view, from, to2, typeOver);
        this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };
        return change;
      }
      // Apply pending changes, if any
      flush(readSelection = true) {
        if (this.delayedFlush >= 0 || this.delayedAndroidKey)
          return false;
        if (readSelection)
          this.readSelectionRange();
        let domChange = this.readChange();
        if (!domChange) {
          this.view.requestMeasure();
          return false;
        }
        let startState = this.view.state;
        let handled = applyDOMChange(this.view, domChange);
        if (this.view.state == startState && (domChange.domChanged || domChange.newSel && !domChange.newSel.main.eq(this.view.state.selection.main)))
          this.view.update([]);
        return handled;
      }
      readMutation(rec) {
        let cView = this.view.docView.nearest(rec.target);
        if (!cView || cView.ignoreMutation(rec))
          return null;
        cView.markDirty(rec.type == "attributes");
        if (rec.type == "attributes")
          cView.flags |= 4;
        if (rec.type == "childList") {
          let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);
          let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);
          return {
            from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
            to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd,
            typeOver: false
          };
        } else if (rec.type == "characterData") {
          return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
        } else {
          return null;
        }
      }
      setWindow(win) {
        if (win != this.win) {
          this.removeWindowListeners(this.win);
          this.win = win;
          this.addWindowListeners(this.win);
        }
      }
      addWindowListeners(win) {
        win.addEventListener("resize", this.onResize);
        if (this.printQuery) {
          if (this.printQuery.addEventListener)
            this.printQuery.addEventListener("change", this.onPrint);
          else
            this.printQuery.addListener(this.onPrint);
        } else
          win.addEventListener("beforeprint", this.onPrint);
        win.addEventListener("scroll", this.onScroll);
        win.document.addEventListener("selectionchange", this.onSelectionChange);
      }
      removeWindowListeners(win) {
        win.removeEventListener("scroll", this.onScroll);
        win.removeEventListener("resize", this.onResize);
        if (this.printQuery) {
          if (this.printQuery.removeEventListener)
            this.printQuery.removeEventListener("change", this.onPrint);
          else
            this.printQuery.removeListener(this.onPrint);
        } else
          win.removeEventListener("beforeprint", this.onPrint);
        win.document.removeEventListener("selectionchange", this.onSelectionChange);
      }
      update(update) {
        if (this.editContext) {
          this.editContext.update(update);
          if (update.startState.facet(editable) != update.state.facet(editable))
            update.view.contentDOM.editContext = update.state.facet(editable) ? this.editContext.editContext : null;
        }
      }
      destroy() {
        var _a2, _b2, _c;
        this.stop();
        (_a2 = this.intersection) === null || _a2 === void 0 ? void 0 : _a2.disconnect();
        (_b2 = this.gapIntersection) === null || _b2 === void 0 ? void 0 : _b2.disconnect();
        (_c = this.resizeScroll) === null || _c === void 0 ? void 0 : _c.disconnect();
        for (let dom of this.scrollTargets)
          dom.removeEventListener("scroll", this.onScroll);
        this.removeWindowListeners(this.win);
        clearTimeout(this.parentCheck);
        clearTimeout(this.resizeTimeout);
        this.win.cancelAnimationFrame(this.delayedFlush);
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
        if (this.editContext) {
          this.view.contentDOM.editContext = null;
          this.editContext.destroy();
        }
      }
    }
    function findChild(cView, dom, dir) {
      while (dom) {
        let curView = ContentView.get(dom);
        if (curView && curView.parent == cView)
          return curView;
        let parent = dom.parentNode;
        dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
      }
      return null;
    }
    function buildSelectionRangeFromRange(view, range) {
      let anchorNode = range.startContainer, anchorOffset = range.startOffset;
      let focusNode = range.endContainer, focusOffset = range.endOffset;
      let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);
      if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
        [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
      return { anchorNode, anchorOffset, focusNode, focusOffset };
    }
    function safariSelectionRangeHack(view, selection) {
      if (selection.getComposedRanges) {
        let range = selection.getComposedRanges(view.root)[0];
        if (range)
          return buildSelectionRangeFromRange(view, range);
      }
      let found = null;
      function read2(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        found = event.getTargetRanges()[0];
      }
      view.contentDOM.addEventListener("beforeinput", read2, true);
      view.dom.ownerDocument.execCommand("indent");
      view.contentDOM.removeEventListener("beforeinput", read2, true);
      return found ? buildSelectionRangeFromRange(view, found) : null;
    }
    class EditContextManager {
      constructor(view) {
        this.from = 0;
        this.to = 0;
        this.pendingContextChange = null;
        this.handlers = /* @__PURE__ */ Object.create(null);
        this.composing = null;
        this.resetRange(view.state);
        let context = this.editContext = new window.EditContext({
          text: view.state.doc.sliceString(this.from, this.to),
          selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))),
          selectionEnd: this.toContextPos(view.state.selection.main.head)
        });
        this.handlers.textupdate = (e) => {
          let main = view.state.selection.main, { anchor, head } = main;
          let from = this.toEditorPos(e.updateRangeStart), to2 = this.toEditorPos(e.updateRangeEnd);
          if (view.inputState.composing >= 0 && !this.composing)
            this.composing = { contextBase: e.updateRangeStart, editorBase: from, drifted: false };
          let change = { from, to: to2, insert: Text.of(e.text.split("\n")) };
          if (change.from == this.from && anchor < this.from)
            change.from = anchor;
          else if (change.to == this.to && anchor > this.to)
            change.to = anchor;
          if (change.from == change.to && !change.insert.length) {
            let newSel = EditorSelection.single(this.toEditorPos(e.selectionStart), this.toEditorPos(e.selectionEnd));
            if (!newSel.main.eq(main))
              view.dispatch({ selection: newSel, userEvent: "select" });
            return;
          }
          if ((browser.mac || browser.android) && change.from == head - 1 && /^\. ?$/.test(e.text) && view.contentDOM.getAttribute("autocorrect") == "off")
            change = { from, to: to2, insert: Text.of([e.text.replace(".", " ")]) };
          this.pendingContextChange = change;
          if (!view.state.readOnly) {
            let newLen = this.to - this.from + (change.to - change.from + change.insert.length);
            applyDOMChangeInner(view, change, EditorSelection.single(this.toEditorPos(e.selectionStart, newLen), this.toEditorPos(e.selectionEnd, newLen)));
          }
          if (this.pendingContextChange) {
            this.revertPending(view.state);
            this.setSelection(view.state);
          }
        };
        this.handlers.characterboundsupdate = (e) => {
          let rects = [], prev = null;
          for (let i2 = this.toEditorPos(e.rangeStart), end = this.toEditorPos(e.rangeEnd); i2 < end; i2++) {
            let rect = view.coordsForChar(i2);
            prev = rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top) || prev || new DOMRect();
            rects.push(prev);
          }
          context.updateCharacterBounds(e.rangeStart, rects);
        };
        this.handlers.textformatupdate = (e) => {
          let deco = [];
          for (let format2 of e.getTextFormats()) {
            let lineStyle = format2.underlineStyle, thickness = format2.underlineThickness;
            if (lineStyle != "None" && thickness != "None") {
              let from = this.toEditorPos(format2.rangeStart), to2 = this.toEditorPos(format2.rangeEnd);
              if (from < to2) {
                let style2 = `text-decoration: underline ${lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${thickness == "Thin" ? 1 : 2}px`;
                deco.push(Decoration.mark({ attributes: { style: style2 } }).range(from, to2));
              }
            }
          }
          view.dispatch({ effects: setEditContextFormatting.of(Decoration.set(deco)) });
        };
        this.handlers.compositionstart = () => {
          if (view.inputState.composing < 0) {
            view.inputState.composing = 0;
            view.inputState.compositionFirstChange = true;
          }
        };
        this.handlers.compositionend = () => {
          view.inputState.composing = -1;
          view.inputState.compositionFirstChange = null;
          if (this.composing) {
            let { drifted } = this.composing;
            this.composing = null;
            if (drifted)
              this.reset(view.state);
          }
        };
        for (let event in this.handlers)
          context.addEventListener(event, this.handlers[event]);
        this.measureReq = { read: (view2) => {
          this.editContext.updateControlBounds(view2.contentDOM.getBoundingClientRect());
          let sel = getSelection(view2.root);
          if (sel && sel.rangeCount)
            this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect());
        } };
      }
      applyEdits(update) {
        let off = 0, abort = false, pending = this.pendingContextChange;
        update.changes.iterChanges((fromA, toA, _fromB, _toB, insert2) => {
          if (abort)
            return;
          let dLen = insert2.length - (toA - fromA);
          if (pending && toA >= pending.to) {
            if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert2)) {
              pending = this.pendingContextChange = null;
              off += dLen;
              this.to += dLen;
              return;
            } else {
              pending = null;
              this.revertPending(update.state);
            }
          }
          fromA += off;
          toA += off;
          if (toA <= this.from) {
            this.from += dLen;
            this.to += dLen;
          } else if (fromA < this.to) {
            if (fromA < this.from || toA > this.to || this.to - this.from + insert2.length > 3e4) {
              abort = true;
              return;
            }
            this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert2.toString());
            this.to += dLen;
          }
          off += dLen;
        });
        if (pending && !abort)
          this.revertPending(update.state);
        return !abort;
      }
      update(update) {
        let reverted = this.pendingContextChange, startSel = update.startState.selection.main;
        if (this.composing && (this.composing.drifted || !update.changes.touchesRange(startSel.from, startSel.to) && update.transactions.some((tr2) => !tr2.isUserEvent("input.type") && tr2.changes.touchesRange(this.from, this.to)))) {
          this.composing.drifted = true;
          this.composing.editorBase = update.changes.mapPos(this.composing.editorBase);
        } else if (!this.applyEdits(update) || !this.rangeIsValid(update.state)) {
          this.pendingContextChange = null;
          this.reset(update.state);
        } else if (update.docChanged || update.selectionSet || reverted) {
          this.setSelection(update.state);
        }
        if (update.geometryChanged || update.docChanged || update.selectionSet)
          update.view.requestMeasure(this.measureReq);
      }
      resetRange(state) {
        let { head } = state.selection.main;
        this.from = Math.max(
          0,
          head - 1e4
          /* CxVp.Margin */
        );
        this.to = Math.min(
          state.doc.length,
          head + 1e4
          /* CxVp.Margin */
        );
      }
      reset(state) {
        this.resetRange(state);
        this.editContext.updateText(0, this.editContext.text.length, state.doc.sliceString(this.from, this.to));
        this.setSelection(state);
      }
      revertPending(state) {
        let pending = this.pendingContextChange;
        this.pendingContextChange = null;
        this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.from + pending.insert.length), state.doc.sliceString(pending.from, pending.to));
      }
      setSelection(state) {
        let { main } = state.selection;
        let start = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor)));
        let end = this.toContextPos(main.head);
        if (this.editContext.selectionStart != start || this.editContext.selectionEnd != end)
          this.editContext.updateSelection(start, end);
      }
      rangeIsValid(state) {
        let { head } = state.selection.main;
        return !(this.from > 0 && head - this.from < 500 || this.to < state.doc.length && this.to - head < 500 || this.to - this.from > 1e4 * 3);
      }
      toEditorPos(contextPos, clipLen = this.to - this.from) {
        contextPos = Math.min(contextPos, clipLen);
        let c2 = this.composing;
        return c2 && c2.drifted ? c2.editorBase + (contextPos - c2.contextBase) : contextPos + this.from;
      }
      toContextPos(editorPos) {
        let c2 = this.composing;
        return c2 && c2.drifted ? c2.contextBase + (editorPos - c2.editorBase) : editorPos - this.from;
      }
      destroy() {
        for (let event in this.handlers)
          this.editContext.removeEventListener(event, this.handlers[event]);
      }
    }
    class EditorView {
      /**
      The current editor state.
      */
      get state() {
        return this.viewState.state;
      }
      /**
      To be able to display large documents without consuming too much
      memory or overloading the browser, CodeMirror only draws the
      code that is visible (plus a margin around it) to the DOM. This
      property tells you the extent of the current drawn viewport, in
      document positions.
      */
      get viewport() {
        return this.viewState.viewport;
      }
      /**
      When there are, for example, large collapsed ranges in the
      viewport, its size can be a lot bigger than the actual visible
      content. Thus, if you are doing something like styling the
      content in the viewport, it is preferable to only do so for
      these ranges, which are the subset of the viewport that is
      actually drawn.
      */
      get visibleRanges() {
        return this.viewState.visibleRanges;
      }
      /**
      Returns false when the editor is entirely scrolled out of view
      or otherwise hidden.
      */
      get inView() {
        return this.viewState.inView;
      }
      /**
      Indicates whether the user is currently composing text via
      [IME](https://en.wikipedia.org/wiki/Input_method), and at least
      one change has been made in the current composition.
      */
      get composing() {
        return this.inputState.composing > 0;
      }
      /**
      Indicates whether the user is currently in composing state. Note
      that on some platforms, like Android, this will be the case a
      lot, since just putting the cursor on a word starts a
      composition there.
      */
      get compositionStarted() {
        return this.inputState.composing >= 0;
      }
      /**
      The document or shadow root that the view lives in.
      */
      get root() {
        return this._root;
      }
      /**
      @internal
      */
      get win() {
        return this.dom.ownerDocument.defaultView || window;
      }
      /**
      Construct a new view. You'll want to either provide a `parent`
      option, or put `view.dom` into your document after creating a
      view, so that the user can see the editor.
      */
      constructor(config2 = {}) {
        var _a2;
        this.plugins = [];
        this.pluginMap = /* @__PURE__ */ new Map();
        this.editorAttrs = {};
        this.contentAttrs = {};
        this.bidiCache = [];
        this.destroyed = false;
        this.updateState = 2;
        this.measureScheduled = -1;
        this.measureRequests = [];
        this.contentDOM = document.createElement("div");
        this.scrollDOM = document.createElement("div");
        this.scrollDOM.tabIndex = -1;
        this.scrollDOM.className = "cm-scroller";
        this.scrollDOM.appendChild(this.contentDOM);
        this.announceDOM = document.createElement("div");
        this.announceDOM.className = "cm-announced";
        this.announceDOM.setAttribute("aria-live", "polite");
        this.dom = document.createElement("div");
        this.dom.appendChild(this.announceDOM);
        this.dom.appendChild(this.scrollDOM);
        if (config2.parent)
          config2.parent.appendChild(this.dom);
        let { dispatch } = config2;
        this.dispatchTransactions = config2.dispatchTransactions || dispatch && ((trs) => trs.forEach((tr2) => dispatch(tr2, this))) || ((trs) => this.update(trs));
        this.dispatch = this.dispatch.bind(this);
        this._root = config2.root || getRoot(config2.parent) || document;
        this.viewState = new ViewState(config2.state || EditorState.create(config2));
        if (config2.scrollTo && config2.scrollTo.is(scrollIntoView$1))
          this.viewState.scrollTarget = config2.scrollTo.value.clip(this.viewState.state);
        this.plugins = this.state.facet(viewPlugin).map((spec) => new PluginInstance(spec));
        for (let plugin of this.plugins)
          plugin.update(this);
        this.observer = new DOMObserver(this);
        this.inputState = new InputState(this);
        this.inputState.ensureHandlers(this.plugins);
        this.docView = new DocView(this);
        this.mountStyles();
        this.updateAttrs();
        this.updateState = 0;
        this.requestMeasure();
        if ((_a2 = document.fonts) === null || _a2 === void 0 ? void 0 : _a2.ready)
          document.fonts.ready.then(() => this.requestMeasure());
      }
      dispatch(...input2) {
        let trs = input2.length == 1 && input2[0] instanceof Transaction ? input2 : input2.length == 1 && Array.isArray(input2[0]) ? input2[0] : [this.state.update(...input2)];
        this.dispatchTransactions(trs, this);
      }
      /**
      Update the view for the given array of transactions. This will
      update the visible document and selection to match the state
      produced by the transactions, and notify view plugins of the
      change. You should usually call
      [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
      as a primitive.
      */
      update(transactions) {
        if (this.updateState != 0)
          throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
        let redrawn = false, attrsChanged = false, update;
        let state = this.state;
        for (let tr2 of transactions) {
          if (tr2.startState != state)
            throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
          state = tr2.state;
        }
        if (this.destroyed) {
          this.viewState.state = state;
          return;
        }
        let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
        if (transactions.some((tr2) => tr2.annotation(isFocusChange))) {
          this.inputState.notifiedFocused = focus;
          focusFlag = 1;
        } else if (focus != this.inputState.notifiedFocused) {
          this.inputState.notifiedFocused = focus;
          dispatchFocus = focusChangeTransaction(state, focus);
          if (!dispatchFocus)
            focusFlag = 1;
        }
        let pendingKey = this.observer.delayedAndroidKey, domChange = null;
        if (pendingKey) {
          this.observer.clearDelayedAndroidKey();
          domChange = this.observer.readChange();
          if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))
            domChange = null;
        } else {
          this.observer.clear();
        }
        if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))
          return this.setState(state);
        update = ViewUpdate.create(this, state, transactions);
        update.flags |= focusFlag;
        let scrollTarget = this.viewState.scrollTarget;
        try {
          this.updateState = 2;
          for (let tr2 of transactions) {
            if (scrollTarget)
              scrollTarget = scrollTarget.map(tr2.changes);
            if (tr2.scrollIntoView) {
              let { main } = tr2.state.selection;
              scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
            }
            for (let e of tr2.effects)
              if (e.is(scrollIntoView$1))
                scrollTarget = e.value.clip(this.state);
          }
          this.viewState.update(update, scrollTarget);
          this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);
          if (!update.empty) {
            this.updatePlugins(update);
            this.inputState.update(update);
          }
          redrawn = this.docView.update(update);
          if (this.state.facet(styleModule) != this.styleModules)
            this.mountStyles();
          attrsChanged = this.updateAttrs();
          this.showAnnouncements(transactions);
          this.docView.updateSelection(redrawn, transactions.some((tr2) => tr2.isUserEvent("select.pointer")));
        } finally {
          this.updateState = 0;
        }
        if (update.startState.facet(theme) != update.state.facet(theme))
          this.viewState.mustMeasureContent = true;
        if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
          this.requestMeasure();
        if (redrawn)
          this.docViewUpdate();
        if (!update.empty)
          for (let listener of this.state.facet(updateListener)) {
            try {
              listener(update);
            } catch (e) {
              logException(this.state, e, "update listener");
            }
          }
        if (dispatchFocus || domChange)
          Promise.resolve().then(() => {
            if (dispatchFocus && this.state == dispatchFocus.startState)
              this.dispatch(dispatchFocus);
            if (domChange) {
              if (!applyDOMChange(this, domChange) && pendingKey.force)
                dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
            }
          });
      }
      /**
      Reset the view to the given state. (This will cause the entire
      document to be redrawn and all view plugins to be reinitialized,
      so you should probably only use it when the new state isn't
      derived from the old state. Otherwise, use
      [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
      */
      setState(newState) {
        if (this.updateState != 0)
          throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
        if (this.destroyed) {
          this.viewState.state = newState;
          return;
        }
        this.updateState = 2;
        let hadFocus = this.hasFocus;
        try {
          for (let plugin of this.plugins)
            plugin.destroy(this);
          this.viewState = new ViewState(newState);
          this.plugins = newState.facet(viewPlugin).map((spec) => new PluginInstance(spec));
          this.pluginMap.clear();
          for (let plugin of this.plugins)
            plugin.update(this);
          this.docView.destroy();
          this.docView = new DocView(this);
          this.inputState.ensureHandlers(this.plugins);
          this.mountStyles();
          this.updateAttrs();
          this.bidiCache = [];
        } finally {
          this.updateState = 0;
        }
        if (hadFocus)
          this.focus();
        this.requestMeasure();
      }
      updatePlugins(update) {
        let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);
        if (prevSpecs != specs) {
          let newPlugins = [];
          for (let spec of specs) {
            let found = prevSpecs.indexOf(spec);
            if (found < 0) {
              newPlugins.push(new PluginInstance(spec));
            } else {
              let plugin = this.plugins[found];
              plugin.mustUpdate = update;
              newPlugins.push(plugin);
            }
          }
          for (let plugin of this.plugins)
            if (plugin.mustUpdate != update)
              plugin.destroy(this);
          this.plugins = newPlugins;
          this.pluginMap.clear();
        } else {
          for (let p of this.plugins)
            p.mustUpdate = update;
        }
        for (let i2 = 0; i2 < this.plugins.length; i2++)
          this.plugins[i2].update(this);
        if (prevSpecs != specs)
          this.inputState.ensureHandlers(this.plugins);
      }
      docViewUpdate() {
        for (let plugin of this.plugins) {
          let val = plugin.value;
          if (val && val.docViewUpdate) {
            try {
              val.docViewUpdate(this);
            } catch (e) {
              logException(this.state, e, "doc view update listener");
            }
          }
        }
      }
      /**
      @internal
      */
      measure(flush = true) {
        if (this.destroyed)
          return;
        if (this.measureScheduled > -1)
          this.win.cancelAnimationFrame(this.measureScheduled);
        if (this.observer.delayedAndroidKey) {
          this.measureScheduled = -1;
          this.requestMeasure();
          return;
        }
        this.measureScheduled = 0;
        if (flush)
          this.observer.forceFlush();
        let updated = null;
        let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
        let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
        if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)
          scrollAnchorHeight = -1;
        this.viewState.scrollAnchorHeight = -1;
        try {
          for (let i2 = 0; ; i2++) {
            if (scrollAnchorHeight < 0) {
              if (isScrolledToBottom(sDOM)) {
                scrollAnchorPos = -1;
                scrollAnchorHeight = this.viewState.heightMap.height;
              } else {
                let block2 = this.viewState.scrollAnchorAt(scrollTop);
                scrollAnchorPos = block2.from;
                scrollAnchorHeight = block2.top;
              }
            }
            this.updateState = 1;
            let changed = this.viewState.measure(this);
            if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
              break;
            if (i2 > 5) {
              console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize");
              break;
            }
            let measuring = [];
            if (!(changed & 4))
              [this.measureRequests, measuring] = [measuring, this.measureRequests];
            let measured = measuring.map((m) => {
              try {
                return m.read(this);
              } catch (e) {
                logException(this.state, e);
                return BadMeasure;
              }
            });
            let update = ViewUpdate.create(this, this.state, []), redrawn = false;
            update.flags |= changed;
            if (!updated)
              updated = update;
            else
              updated.flags |= changed;
            this.updateState = 2;
            if (!update.empty) {
              this.updatePlugins(update);
              this.inputState.update(update);
              this.updateAttrs();
              redrawn = this.docView.update(update);
              if (redrawn)
                this.docViewUpdate();
            }
            for (let i3 = 0; i3 < measuring.length; i3++)
              if (measured[i3] != BadMeasure) {
                try {
                  let m = measuring[i3];
                  if (m.write)
                    m.write(measured[i3], this);
                } catch (e) {
                  logException(this.state, e);
                }
              }
            if (redrawn)
              this.docView.updateSelection(true);
            if (!update.viewportChanged && this.measureRequests.length == 0) {
              if (this.viewState.editorHeight) {
                if (this.viewState.scrollTarget) {
                  this.docView.scrollIntoView(this.viewState.scrollTarget);
                  this.viewState.scrollTarget = null;
                  scrollAnchorHeight = -1;
                  continue;
                } else {
                  let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top;
                  let diff2 = newAnchorHeight - scrollAnchorHeight;
                  if (diff2 > 1 || diff2 < -1) {
                    scrollTop = scrollTop + diff2;
                    sDOM.scrollTop = scrollTop / this.scaleY;
                    scrollAnchorHeight = -1;
                    continue;
                  }
                }
              }
              break;
            }
          }
        } finally {
          this.updateState = 0;
          this.measureScheduled = -1;
        }
        if (updated && !updated.empty)
          for (let listener of this.state.facet(updateListener))
            listener(updated);
      }
      /**
      Get the CSS classes for the currently active editor themes.
      */
      get themeClasses() {
        return baseThemeID + " " + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + this.state.facet(theme);
      }
      updateAttrs() {
        let editorAttrs = attrsFromFacet(this, editorAttributes, {
          class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
        });
        let contentAttrs = {
          spellcheck: "false",
          autocorrect: "off",
          autocapitalize: "off",
          writingsuggestions: "false",
          translate: "no",
          contenteditable: !this.state.facet(editable) ? "false" : "true",
          class: "cm-content",
          style: `${browser.tabSize}: ${this.state.tabSize}`,
          role: "textbox",
          "aria-multiline": "true"
        };
        if (this.state.readOnly)
          contentAttrs["aria-readonly"] = "true";
        attrsFromFacet(this, contentAttributes, contentAttrs);
        let changed = this.observer.ignore(() => {
          let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
          let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
          return changedContent || changedEditor;
        });
        this.editorAttrs = editorAttrs;
        this.contentAttrs = contentAttrs;
        return changed;
      }
      showAnnouncements(trs) {
        let first2 = true;
        for (let tr2 of trs)
          for (let effect of tr2.effects)
            if (effect.is(EditorView.announce)) {
              if (first2)
                this.announceDOM.textContent = "";
              first2 = false;
              let div = this.announceDOM.appendChild(document.createElement("div"));
              div.textContent = effect.value;
            }
      }
      mountStyles() {
        this.styleModules = this.state.facet(styleModule);
        let nonce = this.state.facet(EditorView.cspNonce);
        StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$1).reverse(), nonce ? { nonce } : void 0);
      }
      readMeasured() {
        if (this.updateState == 2)
          throw new Error("Reading the editor layout isn't allowed during an update");
        if (this.updateState == 0 && this.measureScheduled > -1)
          this.measure(false);
      }
      /**
      Schedule a layout measurement, optionally providing callbacks to
      do custom DOM measuring followed by a DOM write phase. Using
      this is preferable reading DOM layout directly from, for
      example, an event handler, because it'll make sure measuring and
      drawing done by other components is synchronized, avoiding
      unnecessary DOM layout computations.
      */
      requestMeasure(request) {
        if (this.measureScheduled < 0)
          this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
        if (request) {
          if (this.measureRequests.indexOf(request) > -1)
            return;
          if (request.key != null)
            for (let i2 = 0; i2 < this.measureRequests.length; i2++) {
              if (this.measureRequests[i2].key === request.key) {
                this.measureRequests[i2] = request;
                return;
              }
            }
          this.measureRequests.push(request);
        }
      }
      /**
      Get the value of a specific plugin, if present. Note that
      plugins that crash can be dropped from a view, so even when you
      know you registered a given plugin, it is recommended to check
      the return value of this method.
      */
      plugin(plugin) {
        let known = this.pluginMap.get(plugin);
        if (known === void 0 || known && known.spec != plugin)
          this.pluginMap.set(plugin, known = this.plugins.find((p) => p.spec == plugin) || null);
        return known && known.update(this).value;
      }
      /**
      The top position of the document, in screen coordinates. This
      may be negative when the editor is scrolled down. Points
      directly to the top of the first line, not above the padding.
      */
      get documentTop() {
        return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
      }
      /**
      Reports the padding above and below the document.
      */
      get documentPadding() {
        return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
      }
      /**
      If the editor is transformed with CSS, this provides the scale
      along the X axis. Otherwise, it will just be 1. Note that
      transforms other than translation and scaling are not supported.
      */
      get scaleX() {
        return this.viewState.scaleX;
      }
      /**
      Provide the CSS transformed scale along the Y axis.
      */
      get scaleY() {
        return this.viewState.scaleY;
      }
      /**
      Find the text line or block widget at the given vertical
      position (which is interpreted as relative to the [top of the
      document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
      */
      elementAtHeight(height) {
        this.readMeasured();
        return this.viewState.elementAtHeight(height);
      }
      /**
      Find the line block (see
      [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given
      height, again interpreted relative to the [top of the
      document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
      */
      lineBlockAtHeight(height) {
        this.readMeasured();
        return this.viewState.lineBlockAtHeight(height);
      }
      /**
      Get the extent and vertical position of all [line
      blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
      are relative to the [top of the
      document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
      */
      get viewportLineBlocks() {
        return this.viewState.viewportLines;
      }
      /**
      Find the line block around the given document position. A line
      block is a range delimited on both sides by either a
      non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line break, or the
      start/end of the document. It will usually just hold a line of
      text, but may be broken into multiple textblocks by block
      widgets.
      */
      lineBlockAt(pos2) {
        return this.viewState.lineBlockAt(pos2);
      }
      /**
      The editor's total content height.
      */
      get contentHeight() {
        return this.viewState.contentHeight;
      }
      /**
      Move a cursor position by [grapheme
      cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
      the motion is away from the line start, or towards it. In
      bidirectional text, the line is traversed in visual order, using
      the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
      When the start position was the last one on the line, the
      returned position will be across the line break. If there is no
      further line, the original position is returned.
      
      By default, this method moves over a single cluster. The
      optional `by` argument can be used to move across more. It will
      be called with the first cluster as argument, and should return
      a predicate that determines, for each subsequent cluster,
      whether it should also be moved over.
      */
      moveByChar(start, forward, by) {
        return skipAtoms(this, start, moveByChar(this, start, forward, by));
      }
      /**
      Move a cursor position across the next group of either
      [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
      non-whitespace characters.
      */
      moveByGroup(start, forward) {
        return skipAtoms(this, start, moveByChar(this, start, forward, (initial) => byGroup(this, start.head, initial)));
      }
      /**
      Get the cursor position visually at the start or end of a line.
      Note that this may differ from the _logical_ position at its
      start or end (which is simply at `line.from`/`line.to`) if text
      at the start or end goes against the line's base text direction.
      */
      visualLineSide(line2, end) {
        let order = this.bidiSpans(line2), dir = this.textDirectionAt(line2.from);
        let span = order[end ? order.length - 1 : 0];
        return EditorSelection.cursor(span.side(end, dir) + line2.from, span.forward(!end, dir) ? 1 : -1);
      }
      /**
      Move to the next line boundary in the given direction. If
      `includeWrap` is true, line wrapping is on, and there is a
      further wrap point on the current line, the wrap point will be
      returned. Otherwise this function will return the start or end
      of the line.
      */
      moveToLineBoundary(start, forward, includeWrap = true) {
        return moveToLineBoundary(this, start, forward, includeWrap);
      }
      /**
      Move a cursor position vertically. When `distance` isn't given,
      it defaults to moving to the next line (including wrapped
      lines). Otherwise, `distance` should provide a positive distance
      in pixels.
      
      When `start` has a
      [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
      motion will use that as a target horizontal position. Otherwise,
      the cursor's own horizontal position is used. The returned
      cursor will have its goal column set to whichever column was
      used.
      */
      moveVertically(start, forward, distance) {
        return skipAtoms(this, start, moveVertically(this, start, forward, distance));
      }
      /**
      Find the DOM parent node and offset (child offset if `node` is
      an element, character offset when it is a text node) at the
      given document position.
      
      Note that for positions that aren't currently in
      `visibleRanges`, the resulting DOM position isn't necessarily
      meaningful (it may just point before or after a placeholder
      element).
      */
      domAtPos(pos2) {
        return this.docView.domAtPos(pos2);
      }
      /**
      Find the document position at the given DOM node. Can be useful
      for associating positions with DOM events. Will raise an error
      when `node` isn't part of the editor content.
      */
      posAtDOM(node2, offset = 0) {
        return this.docView.posFromDOM(node2, offset);
      }
      posAtCoords(coords, precise = true) {
        this.readMeasured();
        return posAtCoords(this, coords, precise);
      }
      /**
      Get the screen coordinates at the given document position.
      `side` determines whether the coordinates are based on the
      element before (-1) or after (1) the position (if no element is
      available on the given side, the method will transparently use
      another strategy to get reasonable coordinates).
      */
      coordsAtPos(pos2, side = 1) {
        this.readMeasured();
        let rect = this.docView.coordsAt(pos2, side);
        if (!rect || rect.left == rect.right)
          return rect;
        let line2 = this.state.doc.lineAt(pos2), order = this.bidiSpans(line2);
        let span = order[BidiSpan.find(order, pos2 - line2.from, -1, side)];
        return flattenRect(rect, span.dir == Direction.LTR == side > 0);
      }
      /**
      Return the rectangle around a given character. If `pos` does not
      point in front of a character that is in the viewport and
      rendered (i.e. not replaced, not a line break), this will return
      null. For space characters that are a line wrap point, this will
      return the position before the line break.
      */
      coordsForChar(pos2) {
        this.readMeasured();
        return this.docView.coordsForChar(pos2);
      }
      /**
      The default width of a character in the editor. May not
      accurately reflect the width of all characters (given variable
      width fonts or styling of invididual ranges).
      */
      get defaultCharacterWidth() {
        return this.viewState.heightOracle.charWidth;
      }
      /**
      The default height of a line in the editor. May not be accurate
      for all lines.
      */
      get defaultLineHeight() {
        return this.viewState.heightOracle.lineHeight;
      }
      /**
      The text direction
      ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
      CSS property) of the editor's content element.
      */
      get textDirection() {
        return this.viewState.defaultTextDirection;
      }
      /**
      Find the text direction of the block at the given position, as
      assigned by CSS. If
      [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
      isn't enabled, or the given position is outside of the viewport,
      this will always return the same as
      [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
      this may trigger a DOM layout.
      */
      textDirectionAt(pos2) {
        let perLine = this.state.facet(perLineTextDirection);
        if (!perLine || pos2 < this.viewport.from || pos2 > this.viewport.to)
          return this.textDirection;
        this.readMeasured();
        return this.docView.textDirectionAt(pos2);
      }
      /**
      Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
      (as determined by the
      [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
      CSS property of its content element).
      */
      get lineWrapping() {
        return this.viewState.heightOracle.lineWrapping;
      }
      /**
      Returns the bidirectional text structure of the given line
      (which should be in the current document) as an array of span
      objects. The order of these spans matches the [text
      direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
      left-to-right, the leftmost spans come first, otherwise the
      rightmost spans come first.
      */
      bidiSpans(line2) {
        if (line2.length > MaxBidiLine)
          return trivialOrder(line2.length);
        let dir = this.textDirectionAt(line2.from), isolates;
        for (let entry2 of this.bidiCache) {
          if (entry2.from == line2.from && entry2.dir == dir && (entry2.fresh || isolatesEq(entry2.isolates, isolates = getIsolatedRanges(this, line2))))
            return entry2.order;
        }
        if (!isolates)
          isolates = getIsolatedRanges(this, line2);
        let order = computeOrder(line2.text, dir, isolates);
        this.bidiCache.push(new CachedOrder(line2.from, line2.to, dir, isolates, true, order));
        return order;
      }
      /**
      Check whether the editor has focus.
      */
      get hasFocus() {
        var _a2;
        return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a2 = this.inputState) === null || _a2 === void 0 ? void 0 : _a2.lastContextMenu) > Date.now() - 3e4) && this.root.activeElement == this.contentDOM;
      }
      /**
      Put focus on the editor.
      */
      focus() {
        this.observer.ignore(() => {
          focusPreventScroll(this.contentDOM);
          this.docView.updateSelection();
        });
      }
      /**
      Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
      necessary when moving the editor's existing DOM to a new window or shadow root.
      */
      setRoot(root2) {
        if (this._root != root2) {
          this._root = root2;
          this.observer.setWindow((root2.nodeType == 9 ? root2 : root2.ownerDocument).defaultView || window);
          this.mountStyles();
        }
      }
      /**
      Clean up this editor view, removing its element from the
      document, unregistering event handlers, and notifying
      plugins. The view instance can no longer be used after
      calling this.
      */
      destroy() {
        if (this.root.activeElement == this.contentDOM)
          this.contentDOM.blur();
        for (let plugin of this.plugins)
          plugin.destroy(this);
        this.plugins = [];
        this.inputState.destroy();
        this.docView.destroy();
        this.dom.remove();
        this.observer.destroy();
        if (this.measureScheduled > -1)
          this.win.cancelAnimationFrame(this.measureScheduled);
        this.destroyed = true;
      }
      /**
      Returns an effect that can be
      [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
      cause it to scroll the given position or range into view.
      */
      static scrollIntoView(pos2, options2 = {}) {
        return scrollIntoView$1.of(new ScrollTarget(typeof pos2 == "number" ? EditorSelection.cursor(pos2) : pos2, options2.y, options2.x, options2.yMargin, options2.xMargin));
      }
      /**
      Return an effect that resets the editor to its current (at the
      time this method was called) scroll position. Note that this
      only affects the editor's own scrollable element, not parents.
      See also
      [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
      
      The effect should be used with a document identical to the one
      it was created for. Failing to do so is not an error, but may
      not scroll to the expected position. You can
      [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
      */
      scrollSnapshot() {
        let { scrollTop, scrollLeft } = this.scrollDOM;
        let ref = this.viewState.scrollAnchorAt(scrollTop);
        return scrollIntoView$1.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, true));
      }
      /**
      Enable or disable tab-focus mode, which disables key bindings
      for Tab and Shift-Tab, letting the browser's default
      focus-changing behavior go through instead. This is useful to
      prevent trapping keyboard users in your editor.
      
      Without argument, this toggles the mode. With a boolean, it
      enables (true) or disables it (false). Given a number, it
      temporarily enables the mode until that number of milliseconds
      have passed or another non-Tab key is pressed.
      */
      setTabFocusMode(to2) {
        if (to2 == null)
          this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1;
        else if (typeof to2 == "boolean")
          this.inputState.tabFocusMode = to2 ? 0 : -1;
        else if (this.inputState.tabFocusMode != 0)
          this.inputState.tabFocusMode = Date.now() + to2;
      }
      /**
      Returns an extension that can be used to add DOM event handlers.
      The value should be an object mapping event names to handler
      functions. For any given event, such functions are ordered by
      extension precedence, and the first handler to return true will
      be assumed to have handled that event, and no other handlers or
      built-in behavior will be activated for it. These are registered
      on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
      for `scroll` handlers, which will be called any time the
      editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
      its parent nodes is scrolled.
      */
      static domEventHandlers(handlers2) {
        return ViewPlugin.define(() => ({}), { eventHandlers: handlers2 });
      }
      /**
      Create an extension that registers DOM event observers. Contrary
      to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
      observers can't be prevented from running by a higher-precedence
      handler returning true. They also don't prevent other handlers
      and observers from running when they return true, and should not
      call `preventDefault`.
      */
      static domEventObservers(observers2) {
        return ViewPlugin.define(() => ({}), { eventObservers: observers2 });
      }
      /**
      Create a theme extension. The first argument can be a
      [`style-mod`](https://github.com/marijnh/style-mod#documentation)
      style spec providing the styles for the theme. These will be
      prefixed with a generated class for the style.
      
      Because the selectors will be prefixed with a scope class, rule
      that directly match the editor's [wrapper
      element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
      added—need to be explicitly differentiated by adding an `&` to
      the selector for that element—for example
      `&.cm-focused`.
      
      When `dark` is set to true, the theme will be marked as dark,
      which will cause the `&dark` rules from [base
      themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
      `&light` when a light theme is active).
      */
      static theme(spec, options2) {
        let prefix2 = StyleModule.newName();
        let result2 = [theme.of(prefix2), styleModule.of(buildTheme(`.${prefix2}`, spec))];
        if (options2 && options2.dark)
          result2.push(darkTheme.of(true));
        return result2;
      }
      /**
      Create an extension that adds styles to the base theme. Like
      with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
      place of the editor wrapper element when directly targeting
      that. You can also use `&dark` or `&light` instead to only
      target editors with a dark or light theme.
      */
      static baseTheme(spec) {
        return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
      }
      /**
      Retrieve an editor view instance from the view's DOM
      representation.
      */
      static findFromDOM(dom) {
        var _a2;
        let content2 = dom.querySelector(".cm-content");
        let cView = content2 && ContentView.get(content2) || ContentView.get(dom);
        return ((_a2 = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a2 === void 0 ? void 0 : _a2.view) || null;
      }
    }
    EditorView.styleModule = styleModule;
    EditorView.inputHandler = inputHandler;
    EditorView.clipboardInputFilter = clipboardInputFilter;
    EditorView.clipboardOutputFilter = clipboardOutputFilter;
    EditorView.scrollHandler = scrollHandler;
    EditorView.focusChangeEffect = focusChangeEffect;
    EditorView.perLineTextDirection = perLineTextDirection;
    EditorView.exceptionSink = exceptionSink;
    EditorView.updateListener = updateListener;
    EditorView.editable = editable;
    EditorView.mouseSelectionStyle = mouseSelectionStyle;
    EditorView.dragMovesSelection = dragMovesSelection$1;
    EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
    EditorView.decorations = decorations;
    EditorView.outerDecorations = outerDecorations;
    EditorView.atomicRanges = atomicRanges;
    EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
    EditorView.scrollMargins = scrollMargins;
    EditorView.darkTheme = darkTheme;
    EditorView.cspNonce = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : "" });
    EditorView.contentAttributes = contentAttributes;
    EditorView.editorAttributes = editorAttributes;
    EditorView.lineWrapping = /* @__PURE__ */ EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
    EditorView.announce = /* @__PURE__ */ StateEffect.define();
    const MaxBidiLine = 4096;
    const BadMeasure = {};
    class CachedOrder {
      constructor(from, to2, dir, isolates, fresh, order) {
        this.from = from;
        this.to = to2;
        this.dir = dir;
        this.isolates = isolates;
        this.fresh = fresh;
        this.order = order;
      }
      static update(cache, changes) {
        if (changes.empty && !cache.some((c2) => c2.fresh))
          return cache;
        let result2 = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
        for (let i2 = Math.max(0, cache.length - 10); i2 < cache.length; i2++) {
          let entry2 = cache[i2];
          if (entry2.dir == lastDir && !changes.touchesRange(entry2.from, entry2.to))
            result2.push(new CachedOrder(changes.mapPos(entry2.from, 1), changes.mapPos(entry2.to, -1), entry2.dir, entry2.isolates, false, entry2.order));
        }
        return result2;
      }
    }
    function attrsFromFacet(view, facet, base2) {
      for (let sources = view.state.facet(facet), i2 = sources.length - 1; i2 >= 0; i2--) {
        let source2 = sources[i2], value2 = typeof source2 == "function" ? source2(view) : source2;
        if (value2)
          combineAttrs(value2, base2);
      }
      return base2;
    }
    const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
    function normalizeKeyName(name2, platform) {
      const parts = name2.split(/-(?!$)/);
      let result2 = parts[parts.length - 1];
      if (result2 == "Space")
        result2 = " ";
      let alt, ctrl, shift2, meta2;
      for (let i2 = 0; i2 < parts.length - 1; ++i2) {
        const mod2 = parts[i2];
        if (/^(cmd|meta|m)$/i.test(mod2))
          meta2 = true;
        else if (/^a(lt)?$/i.test(mod2))
          alt = true;
        else if (/^(c|ctrl|control)$/i.test(mod2))
          ctrl = true;
        else if (/^s(hift)?$/i.test(mod2))
          shift2 = true;
        else if (/^mod$/i.test(mod2)) {
          if (platform == "mac")
            meta2 = true;
          else
            ctrl = true;
        } else
          throw new Error("Unrecognized modifier name: " + mod2);
      }
      if (alt)
        result2 = "Alt-" + result2;
      if (ctrl)
        result2 = "Ctrl-" + result2;
      if (meta2)
        result2 = "Meta-" + result2;
      if (shift2)
        result2 = "Shift-" + result2;
      return result2;
    }
    function modifiers(name2, event, shift2) {
      if (event.altKey)
        name2 = "Alt-" + name2;
      if (event.ctrlKey)
        name2 = "Ctrl-" + name2;
      if (event.metaKey)
        name2 = "Meta-" + name2;
      if (shift2 !== false && event.shiftKey)
        name2 = "Shift-" + name2;
      return name2;
    }
    const handleKeyEvents = /* @__PURE__ */ Prec.default(/* @__PURE__ */ EditorView.domEventHandlers({
      keydown(event, view) {
        return runHandlers(getKeymap(view.state), event, view, "editor");
      }
    }));
    const keymap = /* @__PURE__ */ Facet.define({ enables: handleKeyEvents });
    const Keymaps = /* @__PURE__ */ new WeakMap();
    function getKeymap(state) {
      let bindings = state.facet(keymap);
      let map2 = Keymaps.get(bindings);
      if (!map2)
        Keymaps.set(bindings, map2 = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
      return map2;
    }
    let storedPrefix = null;
    const PrefixTimeout = 4e3;
    function buildKeymap(bindings, platform = currentPlatform) {
      let bound = /* @__PURE__ */ Object.create(null);
      let isPrefix = /* @__PURE__ */ Object.create(null);
      let checkPrefix = (name2, is2) => {
        let current = isPrefix[name2];
        if (current == null)
          isPrefix[name2] = is2;
        else if (current != is2)
          throw new Error("Key binding " + name2 + " is used both as a regular binding and as a multi-stroke prefix");
      };
      let add2 = (scope, key2, command2, preventDefault, stopPropagation) => {
        var _a2, _b2;
        let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
        let parts = key2.split(/ (?!$)/).map((k) => normalizeKeyName(k, platform));
        for (let i2 = 1; i2 < parts.length; i2++) {
          let prefix2 = parts.slice(0, i2).join(" ");
          checkPrefix(prefix2, true);
          if (!scopeObj[prefix2])
            scopeObj[prefix2] = {
              preventDefault: true,
              stopPropagation: false,
              run: [(view) => {
                let ourObj = storedPrefix = { view, prefix: prefix2, scope };
                setTimeout(() => {
                  if (storedPrefix == ourObj)
                    storedPrefix = null;
                }, PrefixTimeout);
                return true;
              }]
            };
        }
        let full = parts.join(" ");
        checkPrefix(full, false);
        let binding = scopeObj[full] || (scopeObj[full] = {
          preventDefault: false,
          stopPropagation: false,
          run: ((_b2 = (_a2 = scopeObj._any) === null || _a2 === void 0 ? void 0 : _a2.run) === null || _b2 === void 0 ? void 0 : _b2.slice()) || []
        });
        if (command2)
          binding.run.push(command2);
        if (preventDefault)
          binding.preventDefault = true;
        if (stopPropagation)
          binding.stopPropagation = true;
      };
      for (let b of bindings) {
        let scopes = b.scope ? b.scope.split(" ") : ["editor"];
        if (b.any)
          for (let scope of scopes) {
            let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
            if (!scopeObj._any)
              scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };
            let { any } = b;
            for (let key2 in scopeObj)
              scopeObj[key2].run.push((view) => any(view, currentKeyEvent));
          }
        let name2 = b[platform] || b.key;
        if (!name2)
          continue;
        for (let scope of scopes) {
          add2(scope, name2, b.run, b.preventDefault, b.stopPropagation);
          if (b.shift)
            add2(scope, "Shift-" + name2, b.shift, b.preventDefault, b.stopPropagation);
        }
      }
      return bound;
    }
    let currentKeyEvent = null;
    function runHandlers(map2, event, view, scope) {
      currentKeyEvent = event;
      let name2 = keyName(event);
      let charCode = codePointAt(name2, 0), isChar = codePointSize(charCode) == name2.length && name2 != " ";
      let prefix2 = "", handled = false, prevented = false, stopPropagation = false;
      if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
        prefix2 = storedPrefix.prefix + " ";
        if (modifierCodes.indexOf(event.keyCode) < 0) {
          prevented = true;
          storedPrefix = null;
        }
      }
      let ran = /* @__PURE__ */ new Set();
      let runFor = (binding) => {
        if (binding) {
          for (let cmd2 of binding.run)
            if (!ran.has(cmd2)) {
              ran.add(cmd2);
              if (cmd2(view)) {
                if (binding.stopPropagation)
                  stopPropagation = true;
                return true;
              }
            }
          if (binding.preventDefault) {
            if (binding.stopPropagation)
              stopPropagation = true;
            prevented = true;
          }
        }
        return false;
      };
      let scopeObj = map2[scope], baseName, shiftName;
      if (scopeObj) {
        if (runFor(scopeObj[prefix2 + modifiers(name2, event, !isChar)])) {
          handled = true;
        } else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
        !(browser.windows && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name2) {
          if (runFor(scopeObj[prefix2 + modifiers(baseName, event, true)])) {
            handled = true;
          } else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name2 && shiftName != baseName && runFor(scopeObj[prefix2 + modifiers(shiftName, event, false)])) {
            handled = true;
          }
        } else if (isChar && event.shiftKey && runFor(scopeObj[prefix2 + modifiers(name2, event, true)])) {
          handled = true;
        }
        if (!handled && runFor(scopeObj._any))
          handled = true;
      }
      if (prevented)
        handled = true;
      if (handled && stopPropagation)
        event.stopPropagation();
      currentKeyEvent = null;
      return handled;
    }
    class RectangleMarker {
      /**
      Create a marker with the given class and dimensions. If `width`
      is null, the DOM element will get no width style.
      */
      constructor(className2, left, top2, width, height) {
        this.className = className2;
        this.left = left;
        this.top = top2;
        this.width = width;
        this.height = height;
      }
      draw() {
        let elt = document.createElement("div");
        elt.className = this.className;
        this.adjust(elt);
        return elt;
      }
      update(elt, prev) {
        if (prev.className != this.className)
          return false;
        this.adjust(elt);
        return true;
      }
      adjust(elt) {
        elt.style.left = this.left + "px";
        elt.style.top = this.top + "px";
        if (this.width != null)
          elt.style.width = this.width + "px";
        elt.style.height = this.height + "px";
      }
      eq(p) {
        return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && this.className == p.className;
      }
      /**
      Create a set of rectangles for the given selection range,
      assigning them theclass`className`. Will create a single
      rectangle for empty ranges, and a set of selection-style
      rectangles covering the range's content (in a bidi-aware
      way) for non-empty ones.
      */
      static forRange(view, className2, range) {
        if (range.empty) {
          let pos2 = view.coordsAtPos(range.head, range.assoc || 1);
          if (!pos2)
            return [];
          let base2 = getBase(view);
          return [new RectangleMarker(className2, pos2.left - base2.left, pos2.top - base2.top, null, pos2.bottom - pos2.top)];
        } else {
          return rectanglesForRange(view, className2, range);
        }
      }
    }
    function getBase(view) {
      let rect = view.scrollDOM.getBoundingClientRect();
      let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
      return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
    }
    function wrappedLine(view, pos2, side, inside2) {
      let coords = view.coordsAtPos(pos2, side * 2);
      if (!coords)
        return inside2;
      let editorRect = view.dom.getBoundingClientRect();
      let y = (coords.top + coords.bottom) / 2;
      let left = view.posAtCoords({ x: editorRect.left + 1, y });
      let right = view.posAtCoords({ x: editorRect.right - 1, y });
      if (left == null || right == null)
        return inside2;
      return { from: Math.max(inside2.from, Math.min(left, right)), to: Math.min(inside2.to, Math.max(left, right)) };
    }
    function rectanglesForRange(view, className2, range) {
      if (range.to <= view.viewport.from || range.from >= view.viewport.to)
        return [];
      let from = Math.max(range.from, view.viewport.from), to2 = Math.min(range.to, view.viewport.to);
      let ltr = view.textDirection == Direction.LTR;
      let content2 = view.contentDOM, contentRect = content2.getBoundingClientRect(), base2 = getBase(view);
      let lineElt = content2.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt);
      let leftSide = contentRect.left + (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
      let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
      let startBlock = blockAt(view, from), endBlock = blockAt(view, to2);
      let visualStart = startBlock.type == BlockType.Text ? startBlock : null;
      let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;
      if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))
        visualStart = wrappedLine(view, from, 1, visualStart);
      if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))
        visualEnd = wrappedLine(view, to2, -1, visualEnd);
      if (visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) {
        return pieces(drawForLine(range.from, range.to, visualStart));
      } else {
        let top2 = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);
        let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);
        let between = [];
        if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) || startBlock.widgetLineBreaks > 1 && top2.bottom + view.defaultLineHeight / 2 < bottom.top)
          between.push(piece(leftSide, top2.bottom, rightSide, bottom.top));
        else if (top2.bottom < bottom.top && view.elementAtHeight((top2.bottom + bottom.top) / 2).type == BlockType.Text)
          top2.bottom = bottom.top = (top2.bottom + bottom.top) / 2;
        return pieces(top2).concat(between).concat(pieces(bottom));
      }
      function piece(left, top2, right, bottom) {
        return new RectangleMarker(className2, left - base2.left, top2 - base2.top, right - left, bottom - top2);
      }
      function pieces({ top: top2, bottom, horizontal }) {
        let pieces2 = [];
        for (let i2 = 0; i2 < horizontal.length; i2 += 2)
          pieces2.push(piece(horizontal[i2], top2, horizontal[i2 + 1], bottom));
        return pieces2;
      }
      function drawForLine(from2, to3, line2) {
        let top2 = 1e9, bottom = -1e9, horizontal = [];
        function addSpan(from3, fromOpen, to4, toOpen, dir) {
          let fromCoords = view.coordsAtPos(from3, from3 == line2.to ? -2 : 2);
          let toCoords = view.coordsAtPos(to4, to4 == line2.from ? 2 : -2);
          if (!fromCoords || !toCoords)
            return;
          top2 = Math.min(fromCoords.top, toCoords.top, top2);
          bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
          if (dir == Direction.LTR)
            horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
          else
            horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
        }
        let start = from2 !== null && from2 !== void 0 ? from2 : line2.from, end = to3 !== null && to3 !== void 0 ? to3 : line2.to;
        for (let r2 of view.visibleRanges)
          if (r2.to > start && r2.from < end) {
            for (let pos2 = Math.max(r2.from, start), endPos = Math.min(r2.to, end); ; ) {
              let docLine = view.state.doc.lineAt(pos2);
              for (let span of view.bidiSpans(docLine)) {
                let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
                if (spanFrom >= endPos)
                  break;
                if (spanTo > pos2)
                  addSpan(Math.max(spanFrom, pos2), from2 == null && spanFrom <= start, Math.min(spanTo, endPos), to3 == null && spanTo >= end, span.dir);
              }
              pos2 = docLine.to + 1;
              if (pos2 >= endPos)
                break;
            }
          }
        if (horizontal.length == 0)
          addSpan(start, from2 == null, end, to3 == null, view.textDirection);
        return { top: top2, bottom, horizontal };
      }
      function drawForWidget(block2, top2) {
        let y = contentRect.top + (top2 ? block2.top : block2.bottom);
        return { top: y, bottom: y, horizontal: [] };
      }
    }
    function sameMarker(a, b) {
      return a.constructor == b.constructor && a.eq(b);
    }
    class LayerView {
      constructor(view, layer2) {
        this.view = view;
        this.layer = layer2;
        this.drawn = [];
        this.scaleX = 1;
        this.scaleY = 1;
        this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };
        this.dom = view.scrollDOM.appendChild(document.createElement("div"));
        this.dom.classList.add("cm-layer");
        if (layer2.above)
          this.dom.classList.add("cm-layer-above");
        if (layer2.class)
          this.dom.classList.add(layer2.class);
        this.scale();
        this.dom.setAttribute("aria-hidden", "true");
        this.setOrder(view.state);
        view.requestMeasure(this.measureReq);
        if (layer2.mount)
          layer2.mount(this.dom, view);
      }
      update(update) {
        if (update.startState.facet(layerOrder) != update.state.facet(layerOrder))
          this.setOrder(update.state);
        if (this.layer.update(update, this.dom) || update.geometryChanged) {
          this.scale();
          update.view.requestMeasure(this.measureReq);
        }
      }
      docViewUpdate(view) {
        if (this.layer.updateOnDocViewUpdate !== false)
          view.requestMeasure(this.measureReq);
      }
      setOrder(state) {
        let pos2 = 0, order = state.facet(layerOrder);
        while (pos2 < order.length && order[pos2] != this.layer)
          pos2++;
        this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos2);
      }
      measure() {
        return this.layer.markers(this.view);
      }
      scale() {
        let { scaleX, scaleY } = this.view;
        if (scaleX != this.scaleX || scaleY != this.scaleY) {
          this.scaleX = scaleX;
          this.scaleY = scaleY;
          this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
        }
      }
      draw(markers) {
        if (markers.length != this.drawn.length || markers.some((p, i2) => !sameMarker(p, this.drawn[i2]))) {
          let old = this.dom.firstChild, oldI = 0;
          for (let marker of markers) {
            if (marker.update && old && marker.constructor && this.drawn[oldI].constructor && marker.update(old, this.drawn[oldI])) {
              old = old.nextSibling;
              oldI++;
            } else {
              this.dom.insertBefore(marker.draw(), old);
            }
          }
          while (old) {
            let next = old.nextSibling;
            old.remove();
            old = next;
          }
          this.drawn = markers;
        }
      }
      destroy() {
        if (this.layer.destroy)
          this.layer.destroy(this.dom, this.view);
        this.dom.remove();
      }
    }
    const layerOrder = /* @__PURE__ */ Facet.define();
    function layer(config2) {
      return [
        ViewPlugin.define((v) => new LayerView(v, config2)),
        layerOrder.of(config2)
      ];
    }
    const CanHidePrimary = !(browser.ios && browser.webkit && browser.webkit_version < 534);
    const selectionConfig = /* @__PURE__ */ Facet.define({
      combine(configs) {
        return combineConfig(configs, {
          cursorBlinkRate: 1200,
          drawRangeCursor: true
        }, {
          cursorBlinkRate: (a, b) => Math.min(a, b),
          drawRangeCursor: (a, b) => a || b
        });
      }
    });
    function drawSelection(config2 = {}) {
      return [
        selectionConfig.of(config2),
        cursorLayer,
        selectionLayer,
        hideNativeSelection,
        nativeSelectionHidden.of(true)
      ];
    }
    function configChanged(update) {
      return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);
    }
    const cursorLayer = /* @__PURE__ */ layer({
      above: true,
      markers(view) {
        let { state } = view, conf = state.facet(selectionConfig);
        let cursors = [];
        for (let r2 of state.selection.ranges) {
          let prim = r2 == state.selection.main;
          if (r2.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
            let className2 = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
            let cursor = r2.empty ? r2 : EditorSelection.cursor(r2.head, r2.head > r2.anchor ? -1 : 1);
            for (let piece of RectangleMarker.forRange(view, className2, cursor))
              cursors.push(piece);
          }
        }
        return cursors;
      },
      update(update, dom) {
        if (update.transactions.some((tr2) => tr2.selection))
          dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
        let confChange = configChanged(update);
        if (confChange)
          setBlinkRate(update.state, dom);
        return update.docChanged || update.selectionSet || confChange;
      },
      mount(dom, view) {
        setBlinkRate(view.state, dom);
      },
      class: "cm-cursorLayer"
    });
    function setBlinkRate(state, dom) {
      dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
    }
    const selectionLayer = /* @__PURE__ */ layer({
      above: false,
      markers(view) {
        return view.state.selection.ranges.map((r2) => r2.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r2)).reduce((a, b) => a.concat(b));
      },
      update(update, dom) {
        return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);
      },
      class: "cm-selectionLayer"
    });
    const themeSpec = {
      ".cm-line": {
        "& ::selection, &::selection": { backgroundColor: "transparent !important" }
      },
      ".cm-content": {
        "& :focus": {
          caretColor: "initial !important",
          "&::selection, & ::selection": {
            backgroundColor: "Highlight !important"
          }
        }
      }
    };
    if (CanHidePrimary)
      themeSpec[".cm-line"].caretColor = themeSpec[".cm-content"].caretColor = "transparent !important";
    const hideNativeSelection = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.theme(themeSpec));
    function iterMatches(doc2, re2, from, to2, f) {
      re2.lastIndex = 0;
      for (let cursor = doc2.iterRange(from, to2), pos2 = from, m; !cursor.next().done; pos2 += cursor.value.length) {
        if (!cursor.lineBreak)
          while (m = re2.exec(cursor.value))
            f(pos2 + m.index, m);
      }
    }
    function matchRanges(view, maxLength) {
      let visible2 = view.visibleRanges;
      if (visible2.length == 1 && visible2[0].from == view.viewport.from && visible2[0].to == view.viewport.to)
        return visible2;
      let result2 = [];
      for (let { from, to: to2 } of visible2) {
        from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
        to2 = Math.min(view.state.doc.lineAt(to2).to, to2 + maxLength);
        if (result2.length && result2[result2.length - 1].to >= from)
          result2[result2.length - 1].to = to2;
        else
          result2.push({ from, to: to2 });
      }
      return result2;
    }
    class MatchDecorator {
      /**
      Create a decorator.
      */
      constructor(config2) {
        const { regexp, decoration, decorate, boundary, maxLength = 1e3 } = config2;
        if (!regexp.global)
          throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
        this.regexp = regexp;
        if (decorate) {
          this.addMatch = (match, view, from, add2) => decorate(add2, from, from + match[0].length, match, view);
        } else if (typeof decoration == "function") {
          this.addMatch = (match, view, from, add2) => {
            let deco = decoration(match, view, from);
            if (deco)
              add2(from, from + match[0].length, deco);
          };
        } else if (decoration) {
          this.addMatch = (match, _view, from, add2) => add2(from, from + match[0].length, decoration);
        } else {
          throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
        }
        this.boundary = boundary;
        this.maxLength = maxLength;
      }
      /**
      Compute the full set of decorations for matches in the given
      view's viewport. You'll want to call this when initializing your
      plugin.
      */
      createDeco(view) {
        let build = new RangeSetBuilder(), add2 = build.add.bind(build);
        for (let { from, to: to2 } of matchRanges(view, this.maxLength))
          iterMatches(view.state.doc, this.regexp, from, to2, (from2, m) => this.addMatch(m, view, from2, add2));
        return build.finish();
      }
      /**
      Update a set of decorations for a view update. `deco` _must_ be
      the set of decorations produced by _this_ `MatchDecorator` for
      the view state before the update.
      */
      updateDeco(update, deco) {
        let changeFrom = 1e9, changeTo = -1;
        if (update.docChanged)
          update.changes.iterChanges((_f, _t2, from, to2) => {
            if (to2 >= update.view.viewport.from && from <= update.view.viewport.to) {
              changeFrom = Math.min(from, changeFrom);
              changeTo = Math.max(to2, changeTo);
            }
          });
        if (update.viewportMoved || changeTo - changeFrom > 1e3)
          return this.createDeco(update.view);
        if (changeTo > -1)
          return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);
        return deco;
      }
      updateRange(view, deco, updateFrom, updateTo) {
        for (let r2 of view.visibleRanges) {
          let from = Math.max(r2.from, updateFrom), to2 = Math.min(r2.to, updateTo);
          if (to2 > from) {
            let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to2 ? view.state.doc.lineAt(to2) : fromLine;
            let start = Math.max(r2.from, fromLine.from), end = Math.min(r2.to, toLine.to);
            if (this.boundary) {
              for (; from > fromLine.from; from--)
                if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
                  start = from;
                  break;
                }
              for (; to2 < toLine.to; to2++)
                if (this.boundary.test(toLine.text[to2 - toLine.from])) {
                  end = to2;
                  break;
                }
            }
            let ranges = [], m;
            let add2 = (from2, to3, deco2) => ranges.push(deco2.range(from2, to3));
            if (fromLine == toLine) {
              this.regexp.lastIndex = start - fromLine.from;
              while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)
                this.addMatch(m, view, m.index + fromLine.from, add2);
            } else {
              iterMatches(view.state.doc, this.regexp, start, end, (from2, m2) => this.addMatch(m2, view, from2, add2));
            }
            deco = deco.update({ filterFrom: start, filterTo: end, filter: (from2, to3) => from2 < start || to3 > end, add: ranges });
          }
        }
        return deco;
      }
    }
    const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
    const Specials = /* @__PURE__ */ new RegExp("[\0-\b\n--­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF￹-￼]", UnicodeRegexpSupport);
    const Names = {
      0: "null",
      7: "bell",
      8: "backspace",
      10: "newline",
      11: "vertical tab",
      13: "carriage return",
      27: "escape",
      8203: "zero width space",
      8204: "zero width non-joiner",
      8205: "zero width joiner",
      8206: "left-to-right mark",
      8207: "right-to-left mark",
      8232: "line separator",
      8237: "left-to-right override",
      8238: "right-to-left override",
      8294: "left-to-right isolate",
      8295: "right-to-left isolate",
      8297: "pop directional isolate",
      8233: "paragraph separator",
      65279: "zero width no-break space",
      65532: "object replacement"
    };
    let _supportsTabSize = null;
    function supportsTabSize() {
      var _a2;
      if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
        let styles2 = document.body.style;
        _supportsTabSize = ((_a2 = styles2.tabSize) !== null && _a2 !== void 0 ? _a2 : styles2.MozTabSize) != null;
      }
      return _supportsTabSize || false;
    }
    const specialCharConfig = /* @__PURE__ */ Facet.define({
      combine(configs) {
        let config2 = combineConfig(configs, {
          render: null,
          specialChars: Specials,
          addSpecialChars: null
        });
        if (config2.replaceTabs = !supportsTabSize())
          config2.specialChars = new RegExp("	|" + config2.specialChars.source, UnicodeRegexpSupport);
        if (config2.addSpecialChars)
          config2.specialChars = new RegExp(config2.specialChars.source + "|" + config2.addSpecialChars.source, UnicodeRegexpSupport);
        return config2;
      }
    });
    function highlightSpecialChars(config2 = {}) {
      return [specialCharConfig.of(config2), specialCharPlugin()];
    }
    let _plugin = null;
    function specialCharPlugin() {
      return _plugin || (_plugin = ViewPlugin.fromClass(class {
        constructor(view) {
          this.view = view;
          this.decorations = Decoration.none;
          this.decorationCache = /* @__PURE__ */ Object.create(null);
          this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
          this.decorations = this.decorator.createDeco(view);
        }
        makeDecorator(conf) {
          return new MatchDecorator({
            regexp: conf.specialChars,
            decoration: (m, view, pos2) => {
              let { doc: doc2 } = view.state;
              let code2 = codePointAt(m[0], 0);
              if (code2 == 9) {
                let line2 = doc2.lineAt(pos2);
                let size = view.state.tabSize, col = countColumn(line2.text, size, pos2 - line2.from);
                return Decoration.replace({
                  widget: new TabWidget((size - col % size) * this.view.defaultCharacterWidth / this.view.scaleX)
                });
              }
              return this.decorationCache[code2] || (this.decorationCache[code2] = Decoration.replace({ widget: new SpecialCharWidget(conf, code2) }));
            },
            boundary: conf.replaceTabs ? void 0 : /[^]/
          });
        }
        update(update) {
          let conf = update.state.facet(specialCharConfig);
          if (update.startState.facet(specialCharConfig) != conf) {
            this.decorator = this.makeDecorator(conf);
            this.decorations = this.decorator.createDeco(update.view);
          } else {
            this.decorations = this.decorator.updateDeco(update, this.decorations);
          }
        }
      }, {
        decorations: (v) => v.decorations
      }));
    }
    const DefaultPlaceholder = "•";
    function placeholder$1(code2) {
      if (code2 >= 32)
        return DefaultPlaceholder;
      if (code2 == 10)
        return "␤";
      return String.fromCharCode(9216 + code2);
    }
    class SpecialCharWidget extends WidgetType {
      constructor(options2, code2) {
        super();
        this.options = options2;
        this.code = code2;
      }
      eq(other) {
        return other.code == this.code;
      }
      toDOM(view) {
        let ph = placeholder$1(this.code);
        let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
        let custom = this.options.render && this.options.render(this.code, desc, ph);
        if (custom)
          return custom;
        let span = document.createElement("span");
        span.textContent = ph;
        span.title = desc;
        span.setAttribute("aria-label", desc);
        span.className = "cm-specialChar";
        return span;
      }
      ignoreEvent() {
        return false;
      }
    }
    class TabWidget extends WidgetType {
      constructor(width) {
        super();
        this.width = width;
      }
      eq(other) {
        return other.width == this.width;
      }
      toDOM() {
        let span = document.createElement("span");
        span.textContent = "	";
        span.className = "cm-tab";
        span.style.width = this.width + "px";
        return span;
      }
      ignoreEvent() {
        return false;
      }
    }
    const Outside = "-10000px";
    class TooltipViewManager {
      constructor(view, facet, createTooltipView, removeTooltipView) {
        this.facet = facet;
        this.createTooltipView = createTooltipView;
        this.removeTooltipView = removeTooltipView;
        this.input = view.state.facet(facet);
        this.tooltips = this.input.filter((t2) => t2);
        let prev = null;
        this.tooltipViews = this.tooltips.map((t2) => prev = createTooltipView(t2, prev));
      }
      update(update, above) {
        var _a2;
        let input2 = update.state.facet(this.facet);
        let tooltips = input2.filter((x2) => x2);
        if (input2 === this.input) {
          for (let t2 of this.tooltipViews)
            if (t2.update)
              t2.update(update);
          return false;
        }
        let tooltipViews = [], newAbove = above ? [] : null;
        for (let i2 = 0; i2 < tooltips.length; i2++) {
          let tip = tooltips[i2], known = -1;
          if (!tip)
            continue;
          for (let i3 = 0; i3 < this.tooltips.length; i3++) {
            let other = this.tooltips[i3];
            if (other && other.create == tip.create)
              known = i3;
          }
          if (known < 0) {
            tooltipViews[i2] = this.createTooltipView(tip, i2 ? tooltipViews[i2 - 1] : null);
            if (newAbove)
              newAbove[i2] = !!tip.above;
          } else {
            let tooltipView = tooltipViews[i2] = this.tooltipViews[known];
            if (newAbove)
              newAbove[i2] = above[known];
            if (tooltipView.update)
              tooltipView.update(update);
          }
        }
        for (let t2 of this.tooltipViews)
          if (tooltipViews.indexOf(t2) < 0) {
            this.removeTooltipView(t2);
            (_a2 = t2.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(t2);
          }
        if (above) {
          newAbove.forEach((val, i2) => above[i2] = val);
          above.length = newAbove.length;
        }
        this.input = input2;
        this.tooltips = tooltips;
        this.tooltipViews = tooltipViews;
        return true;
      }
    }
    function windowSpace(view) {
      let docElt = view.dom.ownerDocument.documentElement;
      return { top: 0, left: 0, bottom: docElt.clientHeight, right: docElt.clientWidth };
    }
    const tooltipConfig = /* @__PURE__ */ Facet.define({
      combine: (values) => {
        var _a2, _b2, _c;
        return {
          position: browser.ios ? "absolute" : ((_a2 = values.find((conf) => conf.position)) === null || _a2 === void 0 ? void 0 : _a2.position) || "fixed",
          parent: ((_b2 = values.find((conf) => conf.parent)) === null || _b2 === void 0 ? void 0 : _b2.parent) || null,
          tooltipSpace: ((_c = values.find((conf) => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace
        };
      }
    });
    const knownHeight = /* @__PURE__ */ new WeakMap();
    const tooltipPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
      constructor(view) {
        this.view = view;
        this.above = [];
        this.inView = true;
        this.madeAbsolute = false;
        this.lastTransaction = 0;
        this.measureTimeout = -1;
        let config2 = view.state.facet(tooltipConfig);
        this.position = config2.position;
        this.parent = config2.parent;
        this.classes = view.themeClasses;
        this.createContainer();
        this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
        this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null;
        this.manager = new TooltipViewManager(view, showTooltip, (t2, p) => this.createTooltip(t2, p), (t2) => {
          if (this.resizeObserver)
            this.resizeObserver.unobserve(t2.dom);
          t2.dom.remove();
        });
        this.above = this.manager.tooltips.map((t2) => !!t2.above);
        this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver((entries) => {
          if (Date.now() > this.lastTransaction - 50 && entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)
            this.measureSoon();
        }, { threshold: [1] }) : null;
        this.observeIntersection();
        view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
        this.maybeMeasure();
      }
      createContainer() {
        if (this.parent) {
          this.container = document.createElement("div");
          this.container.style.position = "relative";
          this.container.className = this.view.themeClasses;
          this.parent.appendChild(this.container);
        } else {
          this.container = this.view.dom;
        }
      }
      observeIntersection() {
        if (this.intersectionObserver) {
          this.intersectionObserver.disconnect();
          for (let tooltip of this.manager.tooltipViews)
            this.intersectionObserver.observe(tooltip.dom);
        }
      }
      measureSoon() {
        if (this.measureTimeout < 0)
          this.measureTimeout = setTimeout(() => {
            this.measureTimeout = -1;
            this.maybeMeasure();
          }, 50);
      }
      update(update) {
        if (update.transactions.length)
          this.lastTransaction = Date.now();
        let updated = this.manager.update(update, this.above);
        if (updated)
          this.observeIntersection();
        let shouldMeasure = updated || update.geometryChanged;
        let newConfig = update.state.facet(tooltipConfig);
        if (newConfig.position != this.position && !this.madeAbsolute) {
          this.position = newConfig.position;
          for (let t2 of this.manager.tooltipViews)
            t2.dom.style.position = this.position;
          shouldMeasure = true;
        }
        if (newConfig.parent != this.parent) {
          if (this.parent)
            this.container.remove();
          this.parent = newConfig.parent;
          this.createContainer();
          for (let t2 of this.manager.tooltipViews)
            this.container.appendChild(t2.dom);
          shouldMeasure = true;
        } else if (this.parent && this.view.themeClasses != this.classes) {
          this.classes = this.container.className = this.view.themeClasses;
        }
        if (shouldMeasure)
          this.maybeMeasure();
      }
      createTooltip(tooltip, prev) {
        let tooltipView = tooltip.create(this.view);
        let before = prev ? prev.dom : null;
        tooltipView.dom.classList.add("cm-tooltip");
        if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
          let arrow = document.createElement("div");
          arrow.className = "cm-tooltip-arrow";
          tooltipView.dom.appendChild(arrow);
        }
        tooltipView.dom.style.position = this.position;
        tooltipView.dom.style.top = Outside;
        tooltipView.dom.style.left = "0px";
        this.container.insertBefore(tooltipView.dom, before);
        if (tooltipView.mount)
          tooltipView.mount(this.view);
        if (this.resizeObserver)
          this.resizeObserver.observe(tooltipView.dom);
        return tooltipView;
      }
      destroy() {
        var _a2, _b2, _c;
        this.view.win.removeEventListener("resize", this.measureSoon);
        for (let tooltipView of this.manager.tooltipViews) {
          tooltipView.dom.remove();
          (_a2 = tooltipView.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(tooltipView);
        }
        if (this.parent)
          this.container.remove();
        (_b2 = this.resizeObserver) === null || _b2 === void 0 ? void 0 : _b2.disconnect();
        (_c = this.intersectionObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
        clearTimeout(this.measureTimeout);
      }
      readMeasure() {
        let scaleX = 1, scaleY = 1, makeAbsolute = false;
        if (this.position == "fixed" && this.manager.tooltipViews.length) {
          let { dom } = this.manager.tooltipViews[0];
          if (browser.gecko) {
            makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;
          } else if (dom.style.top == Outside && dom.style.left == "0px") {
            let rect = dom.getBoundingClientRect();
            makeAbsolute = Math.abs(rect.top + 1e4) > 1 || Math.abs(rect.left) > 1;
          }
        }
        if (makeAbsolute || this.position == "absolute") {
          if (this.parent) {
            let rect = this.parent.getBoundingClientRect();
            if (rect.width && rect.height) {
              scaleX = rect.width / this.parent.offsetWidth;
              scaleY = rect.height / this.parent.offsetHeight;
            }
          } else {
            ({ scaleX, scaleY } = this.view.viewState);
          }
        }
        let visible2 = this.view.scrollDOM.getBoundingClientRect(), margins = getScrollMargins(this.view);
        return {
          visible: {
            left: visible2.left + margins.left,
            top: visible2.top + margins.top,
            right: visible2.right - margins.right,
            bottom: visible2.bottom - margins.bottom
          },
          parent: this.parent ? this.container.getBoundingClientRect() : this.view.dom.getBoundingClientRect(),
          pos: this.manager.tooltips.map((t2, i2) => {
            let tv = this.manager.tooltipViews[i2];
            return tv.getCoords ? tv.getCoords(t2.pos) : this.view.coordsAtPos(t2.pos);
          }),
          size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
          space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
          scaleX,
          scaleY,
          makeAbsolute
        };
      }
      writeMeasure(measured) {
        var _a2;
        if (measured.makeAbsolute) {
          this.madeAbsolute = true;
          this.position = "absolute";
          for (let t2 of this.manager.tooltipViews)
            t2.dom.style.position = "absolute";
        }
        let { visible: visible2, space, scaleX, scaleY } = measured;
        let others = [];
        for (let i2 = 0; i2 < this.manager.tooltips.length; i2++) {
          let tooltip = this.manager.tooltips[i2], tView = this.manager.tooltipViews[i2], { dom } = tView;
          let pos2 = measured.pos[i2], size = measured.size[i2];
          if (!pos2 || tooltip.clip !== false && (pos2.bottom <= Math.max(visible2.top, space.top) || pos2.top >= Math.min(visible2.bottom, space.bottom) || pos2.right < Math.max(visible2.left, space.left) - 0.1 || pos2.left > Math.min(visible2.right, space.right) + 0.1)) {
            dom.style.top = Outside;
            continue;
          }
          let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
          let arrowHeight = arrow ? 7 : 0;
          let width = size.right - size.left, height = (_a2 = knownHeight.get(tView)) !== null && _a2 !== void 0 ? _a2 : size.bottom - size.top;
          let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;
          let left = size.width > space.right - space.left ? ltr ? space.left : space.right - size.width : ltr ? Math.max(space.left, Math.min(pos2.left - (arrow ? 14 : 0) + offset.x, space.right - width)) : Math.min(Math.max(space.left, pos2.left - width + (arrow ? 14 : 0) - offset.x), space.right - width);
          let above = this.above[i2];
          if (!tooltip.strictSide && (above ? pos2.top - height - arrowHeight - offset.y < space.top : pos2.bottom + height + arrowHeight + offset.y > space.bottom) && above == space.bottom - pos2.bottom > pos2.top - space.top)
            above = this.above[i2] = !above;
          let spaceVert = (above ? pos2.top - space.top : space.bottom - pos2.bottom) - arrowHeight;
          if (spaceVert < height && tView.resize !== false) {
            if (spaceVert < this.view.defaultLineHeight) {
              dom.style.top = Outside;
              continue;
            }
            knownHeight.set(tView, height);
            dom.style.height = (height = spaceVert) / scaleY + "px";
          } else if (dom.style.height) {
            dom.style.height = "";
          }
          let top2 = above ? pos2.top - height - arrowHeight - offset.y : pos2.bottom + arrowHeight + offset.y;
          let right = left + width;
          if (tView.overlap !== true) {
            for (let r2 of others)
              if (r2.left < right && r2.right > left && r2.top < top2 + height && r2.bottom > top2)
                top2 = above ? r2.top - height - 2 - arrowHeight : r2.bottom + arrowHeight + 2;
          }
          if (this.position == "absolute") {
            dom.style.top = (top2 - measured.parent.top) / scaleY + "px";
            setLeftStyle(dom, (left - measured.parent.left) / scaleX);
          } else {
            dom.style.top = top2 / scaleY + "px";
            setLeftStyle(dom, left / scaleX);
          }
          if (arrow) {
            let arrowLeft = pos2.left + (ltr ? offset.x : -offset.x) - (left + 14 - 7);
            arrow.style.left = arrowLeft / scaleX + "px";
          }
          if (tView.overlap !== true)
            others.push({ left, top: top2, right, bottom: top2 + height });
          dom.classList.toggle("cm-tooltip-above", above);
          dom.classList.toggle("cm-tooltip-below", !above);
          if (tView.positioned)
            tView.positioned(measured.space);
        }
      }
      maybeMeasure() {
        if (this.manager.tooltips.length) {
          if (this.view.inView)
            this.view.requestMeasure(this.measureReq);
          if (this.inView != this.view.inView) {
            this.inView = this.view.inView;
            if (!this.inView)
              for (let tv of this.manager.tooltipViews)
                tv.dom.style.top = Outside;
          }
        }
      }
    }, {
      eventObservers: {
        scroll() {
          this.maybeMeasure();
        }
      }
    });
    function setLeftStyle(elt, value2) {
      let current = parseInt(elt.style.left, 10);
      if (isNaN(current) || Math.abs(value2 - current) > 1)
        elt.style.left = value2 + "px";
    }
    const baseTheme$3 = /* @__PURE__ */ EditorView.baseTheme({
      ".cm-tooltip": {
        zIndex: 500,
        boxSizing: "border-box"
      },
      "&light .cm-tooltip": {
        border: "1px solid #bbb",
        backgroundColor: "#f5f5f5"
      },
      "&light .cm-tooltip-section:not(:first-child)": {
        borderTop: "1px solid #bbb"
      },
      "&dark .cm-tooltip": {
        backgroundColor: "#333338",
        color: "white"
      },
      ".cm-tooltip-arrow": {
        height: `${7}px`,
        width: `${7 * 2}px`,
        position: "absolute",
        zIndex: -1,
        overflow: "hidden",
        "&:before, &:after": {
          content: "''",
          position: "absolute",
          width: 0,
          height: 0,
          borderLeft: `${7}px solid transparent`,
          borderRight: `${7}px solid transparent`
        },
        ".cm-tooltip-above &": {
          bottom: `-${7}px`,
          "&:before": {
            borderTop: `${7}px solid #bbb`
          },
          "&:after": {
            borderTop: `${7}px solid #f5f5f5`,
            bottom: "1px"
          }
        },
        ".cm-tooltip-below &": {
          top: `-${7}px`,
          "&:before": {
            borderBottom: `${7}px solid #bbb`
          },
          "&:after": {
            borderBottom: `${7}px solid #f5f5f5`,
            top: "1px"
          }
        }
      },
      "&dark .cm-tooltip .cm-tooltip-arrow": {
        "&:before": {
          borderTopColor: "#333338",
          borderBottomColor: "#333338"
        },
        "&:after": {
          borderTopColor: "transparent",
          borderBottomColor: "transparent"
        }
      }
    });
    const noOffset = { x: 0, y: 0 };
    const showTooltip = /* @__PURE__ */ Facet.define({
      enables: [tooltipPlugin, baseTheme$3]
    });
    const showHoverTooltip = /* @__PURE__ */ Facet.define({
      combine: (inputs) => inputs.reduce((a, i2) => a.concat(i2), [])
    });
    class HoverTooltipHost {
      // Needs to be static so that host tooltip instances always match
      static create(view) {
        return new HoverTooltipHost(view);
      }
      constructor(view) {
        this.view = view;
        this.mounted = false;
        this.dom = document.createElement("div");
        this.dom.classList.add("cm-tooltip-hover");
        this.manager = new TooltipViewManager(view, showHoverTooltip, (t2, p) => this.createHostedView(t2, p), (t2) => t2.dom.remove());
      }
      createHostedView(tooltip, prev) {
        let hostedView = tooltip.create(this.view);
        hostedView.dom.classList.add("cm-tooltip-section");
        this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
        if (this.mounted && hostedView.mount)
          hostedView.mount(this.view);
        return hostedView;
      }
      mount(view) {
        for (let hostedView of this.manager.tooltipViews) {
          if (hostedView.mount)
            hostedView.mount(view);
        }
        this.mounted = true;
      }
      positioned(space) {
        for (let hostedView of this.manager.tooltipViews) {
          if (hostedView.positioned)
            hostedView.positioned(space);
        }
      }
      update(update) {
        this.manager.update(update);
      }
      destroy() {
        var _a2;
        for (let t2 of this.manager.tooltipViews)
          (_a2 = t2.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(t2);
      }
      passProp(name2) {
        let value2 = void 0;
        for (let view of this.manager.tooltipViews) {
          let given = view[name2];
          if (given !== void 0) {
            if (value2 === void 0)
              value2 = given;
            else if (value2 !== given)
              return void 0;
          }
        }
        return value2;
      }
      get offset() {
        return this.passProp("offset");
      }
      get getCoords() {
        return this.passProp("getCoords");
      }
      get overlap() {
        return this.passProp("overlap");
      }
      get resize() {
        return this.passProp("resize");
      }
    }
    const showHoverTooltipHost = /* @__PURE__ */ showTooltip.compute([showHoverTooltip], (state) => {
      let tooltips = state.facet(showHoverTooltip);
      if (tooltips.length === 0)
        return null;
      return {
        pos: Math.min(...tooltips.map((t2) => t2.pos)),
        end: Math.max(...tooltips.map((t2) => {
          var _a2;
          return (_a2 = t2.end) !== null && _a2 !== void 0 ? _a2 : t2.pos;
        })),
        create: HoverTooltipHost.create,
        above: tooltips[0].above,
        arrow: tooltips.some((t2) => t2.arrow)
      };
    });
    class HoverPlugin {
      constructor(view, source2, field, setHover, hoverTime) {
        this.view = view;
        this.source = source2;
        this.field = field;
        this.setHover = setHover;
        this.hoverTime = hoverTime;
        this.hoverTimeout = -1;
        this.restartTimeout = -1;
        this.pending = null;
        this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };
        this.checkHover = this.checkHover.bind(this);
        view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
        view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
      }
      update() {
        if (this.pending) {
          this.pending = null;
          clearTimeout(this.restartTimeout);
          this.restartTimeout = setTimeout(() => this.startHover(), 20);
        }
      }
      get active() {
        return this.view.state.field(this.field);
      }
      checkHover() {
        this.hoverTimeout = -1;
        if (this.active.length)
          return;
        let hovered = Date.now() - this.lastMove.time;
        if (hovered < this.hoverTime)
          this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);
        else
          this.startHover();
      }
      startHover() {
        clearTimeout(this.restartTimeout);
        let { view, lastMove } = this;
        let desc = view.docView.nearest(lastMove.target);
        if (!desc)
          return;
        let pos2, side = 1;
        if (desc instanceof WidgetView) {
          pos2 = desc.posAtStart;
        } else {
          pos2 = view.posAtCoords(lastMove);
          if (pos2 == null)
            return;
          let posCoords = view.coordsAtPos(pos2);
          if (!posCoords || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - view.defaultCharacterWidth || lastMove.x > posCoords.right + view.defaultCharacterWidth)
            return;
          let bidi = view.bidiSpans(view.state.doc.lineAt(pos2)).find((s) => s.from <= pos2 && s.to >= pos2);
          let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
          side = lastMove.x < posCoords.left ? -rtl : rtl;
        }
        let open = this.source(view, pos2, side);
        if (open === null || open === void 0 ? void 0 : open.then) {
          let pending = this.pending = { pos: pos2 };
          open.then((result2) => {
            if (this.pending == pending) {
              this.pending = null;
              if (result2 && !(Array.isArray(result2) && !result2.length))
                view.dispatch({ effects: this.setHover.of(Array.isArray(result2) ? result2 : [result2]) });
            }
          }, (e) => logException(view.state, e, "hover tooltip"));
        } else if (open && !(Array.isArray(open) && !open.length)) {
          view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });
        }
      }
      get tooltip() {
        let plugin = this.view.plugin(tooltipPlugin);
        let index2 = plugin ? plugin.manager.tooltips.findIndex((t2) => t2.create == HoverTooltipHost.create) : -1;
        return index2 > -1 ? plugin.manager.tooltipViews[index2] : null;
      }
      mousemove(event) {
        var _a2, _b2;
        this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };
        if (this.hoverTimeout < 0)
          this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
        let { active: active2, tooltip } = this;
        if (active2.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) {
          let { pos: pos2 } = active2[0] || this.pending, end = (_b2 = (_a2 = active2[0]) === null || _a2 === void 0 ? void 0 : _a2.end) !== null && _b2 !== void 0 ? _b2 : pos2;
          if (pos2 == end ? this.view.posAtCoords(this.lastMove) != pos2 : !isOverRange(this.view, pos2, end, event.clientX, event.clientY)) {
            this.view.dispatch({ effects: this.setHover.of([]) });
            this.pending = null;
          }
        }
      }
      mouseleave(event) {
        clearTimeout(this.hoverTimeout);
        this.hoverTimeout = -1;
        let { active: active2 } = this;
        if (active2.length) {
          let { tooltip } = this;
          let inTooltip = tooltip && tooltip.dom.contains(event.relatedTarget);
          if (!inTooltip)
            this.view.dispatch({ effects: this.setHover.of([]) });
          else
            this.watchTooltipLeave(tooltip.dom);
        }
      }
      watchTooltipLeave(tooltip) {
        let watch = (event) => {
          tooltip.removeEventListener("mouseleave", watch);
          if (this.active.length && !this.view.dom.contains(event.relatedTarget))
            this.view.dispatch({ effects: this.setHover.of([]) });
        };
        tooltip.addEventListener("mouseleave", watch);
      }
      destroy() {
        clearTimeout(this.hoverTimeout);
        this.view.dom.removeEventListener("mouseleave", this.mouseleave);
        this.view.dom.removeEventListener("mousemove", this.mousemove);
      }
    }
    const tooltipMargin = 4;
    function isInTooltip(tooltip, event) {
      let { left, right, top: top2, bottom } = tooltip.getBoundingClientRect(), arrow;
      if (arrow = tooltip.querySelector(".cm-tooltip-arrow")) {
        let arrowRect = arrow.getBoundingClientRect();
        top2 = Math.min(arrowRect.top, top2);
        bottom = Math.max(arrowRect.bottom, bottom);
      }
      return event.clientX >= left - tooltipMargin && event.clientX <= right + tooltipMargin && event.clientY >= top2 - tooltipMargin && event.clientY <= bottom + tooltipMargin;
    }
    function isOverRange(view, from, to2, x2, y, margin) {
      let rect = view.scrollDOM.getBoundingClientRect();
      let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
      if (rect.left > x2 || rect.right < x2 || rect.top > y || Math.min(rect.bottom, docBottom) < y)
        return false;
      let pos2 = view.posAtCoords({ x: x2, y }, false);
      return pos2 >= from && pos2 <= to2;
    }
    function hoverTooltip(source2, options2 = {}) {
      let setHover = StateEffect.define();
      let hoverState = StateField.define({
        create() {
          return [];
        },
        update(value2, tr2) {
          if (value2.length) {
            if (options2.hideOnChange && (tr2.docChanged || tr2.selection))
              value2 = [];
            else if (options2.hideOn)
              value2 = value2.filter((v) => !options2.hideOn(tr2, v));
            if (tr2.docChanged) {
              let mapped = [];
              for (let tooltip of value2) {
                let newPos = tr2.changes.mapPos(tooltip.pos, -1, MapMode.TrackDel);
                if (newPos != null) {
                  let copy = Object.assign(/* @__PURE__ */ Object.create(null), tooltip);
                  copy.pos = newPos;
                  if (copy.end != null)
                    copy.end = tr2.changes.mapPos(copy.end);
                  mapped.push(copy);
                }
              }
              value2 = mapped;
            }
          }
          for (let effect of tr2.effects) {
            if (effect.is(setHover))
              value2 = effect.value;
            if (effect.is(closeHoverTooltipEffect))
              value2 = [];
          }
          return value2;
        },
        provide: (f) => showHoverTooltip.from(f)
      });
      return {
        active: hoverState,
        extension: [
          hoverState,
          ViewPlugin.define((view) => new HoverPlugin(
            view,
            source2,
            hoverState,
            setHover,
            options2.hoverTime || 300
            /* Hover.Time */
          )),
          showHoverTooltipHost
        ]
      };
    }
    function getTooltip(view, tooltip) {
      let plugin = view.plugin(tooltipPlugin);
      if (!plugin)
        return null;
      let found = plugin.manager.tooltips.indexOf(tooltip);
      return found < 0 ? null : plugin.manager.tooltipViews[found];
    }
    const closeHoverTooltipEffect = /* @__PURE__ */ StateEffect.define();
    const panelConfig = /* @__PURE__ */ Facet.define({
      combine(configs) {
        let topContainer, bottomContainer;
        for (let c2 of configs) {
          topContainer = topContainer || c2.topContainer;
          bottomContainer = bottomContainer || c2.bottomContainer;
        }
        return { topContainer, bottomContainer };
      }
    });
    const panelPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
      constructor(view) {
        this.input = view.state.facet(showPanel);
        this.specs = this.input.filter((s) => s);
        this.panels = this.specs.map((spec) => spec(view));
        let conf = view.state.facet(panelConfig);
        this.top = new PanelGroup(view, true, conf.topContainer);
        this.bottom = new PanelGroup(view, false, conf.bottomContainer);
        this.top.sync(this.panels.filter((p) => p.top));
        this.bottom.sync(this.panels.filter((p) => !p.top));
        for (let p of this.panels) {
          p.dom.classList.add("cm-panel");
          if (p.mount)
            p.mount();
        }
      }
      update(update) {
        let conf = update.state.facet(panelConfig);
        if (this.top.container != conf.topContainer) {
          this.top.sync([]);
          this.top = new PanelGroup(update.view, true, conf.topContainer);
        }
        if (this.bottom.container != conf.bottomContainer) {
          this.bottom.sync([]);
          this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);
        }
        this.top.syncClasses();
        this.bottom.syncClasses();
        let input2 = update.state.facet(showPanel);
        if (input2 != this.input) {
          let specs = input2.filter((x2) => x2);
          let panels = [], top2 = [], bottom = [], mount2 = [];
          for (let spec of specs) {
            let known = this.specs.indexOf(spec), panel2;
            if (known < 0) {
              panel2 = spec(update.view);
              mount2.push(panel2);
            } else {
              panel2 = this.panels[known];
              if (panel2.update)
                panel2.update(update);
            }
            panels.push(panel2);
            (panel2.top ? top2 : bottom).push(panel2);
          }
          this.specs = specs;
          this.panels = panels;
          this.top.sync(top2);
          this.bottom.sync(bottom);
          for (let p of mount2) {
            p.dom.classList.add("cm-panel");
            if (p.mount)
              p.mount();
          }
        } else {
          for (let p of this.panels)
            if (p.update)
              p.update(update);
        }
      }
      destroy() {
        this.top.sync([]);
        this.bottom.sync([]);
      }
    }, {
      provide: (plugin) => EditorView.scrollMargins.of((view) => {
        let value2 = view.plugin(plugin);
        return value2 && { top: value2.top.scrollMargin(), bottom: value2.bottom.scrollMargin() };
      })
    });
    class PanelGroup {
      constructor(view, top2, container2) {
        this.view = view;
        this.top = top2;
        this.container = container2;
        this.dom = void 0;
        this.classes = "";
        this.panels = [];
        this.syncClasses();
      }
      sync(panels) {
        for (let p of this.panels)
          if (p.destroy && panels.indexOf(p) < 0)
            p.destroy();
        this.panels = panels;
        this.syncDOM();
      }
      syncDOM() {
        if (this.panels.length == 0) {
          if (this.dom) {
            this.dom.remove();
            this.dom = void 0;
          }
          return;
        }
        if (!this.dom) {
          this.dom = document.createElement("div");
          this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
          this.dom.style[this.top ? "top" : "bottom"] = "0";
          let parent = this.container || this.view.dom;
          parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
        }
        let curDOM = this.dom.firstChild;
        for (let panel2 of this.panels) {
          if (panel2.dom.parentNode == this.dom) {
            while (curDOM != panel2.dom)
              curDOM = rm(curDOM);
            curDOM = curDOM.nextSibling;
          } else {
            this.dom.insertBefore(panel2.dom, curDOM);
          }
        }
        while (curDOM)
          curDOM = rm(curDOM);
      }
      scrollMargin() {
        return !this.dom || this.container ? 0 : Math.max(0, this.top ? this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) : Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
      }
      syncClasses() {
        if (!this.container || this.classes == this.view.themeClasses)
          return;
        for (let cls of this.classes.split(" "))
          if (cls)
            this.container.classList.remove(cls);
        for (let cls of (this.classes = this.view.themeClasses).split(" "))
          if (cls)
            this.container.classList.add(cls);
      }
    }
    function rm(node2) {
      let next = node2.nextSibling;
      node2.remove();
      return next;
    }
    const showPanel = /* @__PURE__ */ Facet.define({
      enables: panelPlugin
    });
    class GutterMarker extends RangeValue {
      /**
      @internal
      */
      compare(other) {
        return this == other || this.constructor == other.constructor && this.eq(other);
      }
      /**
      Compare this marker to another marker of the same type.
      */
      eq(other) {
        return false;
      }
      /**
      Called if the marker has a `toDOM` method and its representation
      was removed from a gutter.
      */
      destroy(dom) {
      }
    }
    GutterMarker.prototype.elementClass = "";
    GutterMarker.prototype.toDOM = void 0;
    GutterMarker.prototype.mapMode = MapMode.TrackBefore;
    GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
    GutterMarker.prototype.point = true;
    const DefaultBufferLength = 1024;
    let nextPropID = 0;
    class Range {
      constructor(from, to2) {
        this.from = from;
        this.to = to2;
      }
    }
    class NodeProp {
      /**
      Create a new node prop type.
      */
      constructor(config2 = {}) {
        this.id = nextPropID++;
        this.perNode = !!config2.perNode;
        this.deserialize = config2.deserialize || (() => {
          throw new Error("This node type doesn't define a deserialize function");
        });
      }
      /**
      This is meant to be used with
      [`NodeSet.extend`](#common.NodeSet.extend) or
      [`LRParser.configure`](#lr.ParserConfig.props) to compute
      prop values for each node type in the set. Takes a [match
      object](#common.NodeType^match) or function that returns undefined
      if the node type doesn't get this prop, and the prop's value if
      it does.
      */
      add(match) {
        if (this.perNode)
          throw new RangeError("Can't add per-node props to node types");
        if (typeof match != "function")
          match = NodeType.match(match);
        return (type) => {
          let result2 = match(type);
          return result2 === void 0 ? null : [this, result2];
        };
      }
    }
    NodeProp.closedBy = new NodeProp({ deserialize: (str2) => str2.split(" ") });
    NodeProp.openedBy = new NodeProp({ deserialize: (str2) => str2.split(" ") });
    NodeProp.group = new NodeProp({ deserialize: (str2) => str2.split(" ") });
    NodeProp.isolate = new NodeProp({ deserialize: (value2) => {
      if (value2 && value2 != "rtl" && value2 != "ltr" && value2 != "auto")
        throw new RangeError("Invalid value for isolate: " + value2);
      return value2 || "auto";
    } });
    NodeProp.contextHash = new NodeProp({ perNode: true });
    NodeProp.lookAhead = new NodeProp({ perNode: true });
    NodeProp.mounted = new NodeProp({ perNode: true });
    class MountedTree {
      constructor(tree, overlay, parser2) {
        this.tree = tree;
        this.overlay = overlay;
        this.parser = parser2;
      }
      /**
      @internal
      */
      static get(tree) {
        return tree && tree.props && tree.props[NodeProp.mounted.id];
      }
    }
    const noProps = /* @__PURE__ */ Object.create(null);
    class NodeType {
      /**
      @internal
      */
      constructor(name2, props, id, flags = 0) {
        this.name = name2;
        this.props = props;
        this.id = id;
        this.flags = flags;
      }
      /**
      Define a node type.
      */
      static define(spec) {
        let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
        let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
        let type = new NodeType(spec.name || "", props, spec.id, flags);
        if (spec.props)
          for (let src of spec.props) {
            if (!Array.isArray(src))
              src = src(type);
            if (src) {
              if (src[0].perNode)
                throw new RangeError("Can't store a per-node prop on a node type");
              props[src[0].id] = src[1];
            }
          }
        return type;
      }
      /**
      Retrieves a node prop for this type. Will return `undefined` if
      the prop isn't present on this node.
      */
      prop(prop) {
        return this.props[prop.id];
      }
      /**
      True when this is the top node of a grammar.
      */
      get isTop() {
        return (this.flags & 1) > 0;
      }
      /**
      True when this node is produced by a skip rule.
      */
      get isSkipped() {
        return (this.flags & 2) > 0;
      }
      /**
      Indicates whether this is an error node.
      */
      get isError() {
        return (this.flags & 4) > 0;
      }
      /**
      When true, this node type doesn't correspond to a user-declared
      named node, for example because it is used to cache repetition.
      */
      get isAnonymous() {
        return (this.flags & 8) > 0;
      }
      /**
      Returns true when this node's name or one of its
      [groups](#common.NodeProp^group) matches the given string.
      */
      is(name2) {
        if (typeof name2 == "string") {
          if (this.name == name2)
            return true;
          let group = this.prop(NodeProp.group);
          return group ? group.indexOf(name2) > -1 : false;
        }
        return this.id == name2;
      }
      /**
      Create a function from node types to arbitrary values by
      specifying an object whose property names are node or
      [group](#common.NodeProp^group) names. Often useful with
      [`NodeProp.add`](#common.NodeProp.add). You can put multiple
      names, separated by spaces, in a single property name to map
      multiple node names to a single value.
      */
      static match(map2) {
        let direct = /* @__PURE__ */ Object.create(null);
        for (let prop in map2)
          for (let name2 of prop.split(" "))
            direct[name2] = map2[prop];
        return (node2) => {
          for (let groups = node2.prop(NodeProp.group), i2 = -1; i2 < (groups ? groups.length : 0); i2++) {
            let found = direct[i2 < 0 ? node2.name : groups[i2]];
            if (found)
              return found;
          }
        };
      }
    }
    NodeType.none = new NodeType(
      "",
      /* @__PURE__ */ Object.create(null),
      0,
      8
      /* NodeFlag.Anonymous */
    );
    class NodeSet {
      /**
      Create a set with the given types. The `id` property of each
      type should correspond to its position within the array.
      */
      constructor(types2) {
        this.types = types2;
        for (let i2 = 0; i2 < types2.length; i2++)
          if (types2[i2].id != i2)
            throw new RangeError("Node type ids should correspond to array positions when creating a node set");
      }
      /**
      Create a copy of this set with some node properties added. The
      arguments to this method can be created with
      [`NodeProp.add`](#common.NodeProp.add).
      */
      extend(...props) {
        let newTypes = [];
        for (let type of this.types) {
          let newProps = null;
          for (let source2 of props) {
            let add2 = source2(type);
            if (add2) {
              if (!newProps)
                newProps = Object.assign({}, type.props);
              newProps[add2[0].id] = add2[1];
            }
          }
          newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
        }
        return new NodeSet(newTypes);
      }
    }
    const CachedNode = /* @__PURE__ */ new WeakMap(), CachedInnerNode = /* @__PURE__ */ new WeakMap();
    var IterMode;
    (function(IterMode2) {
      IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
      IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
      IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
      IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
    })(IterMode || (IterMode = {}));
    class Tree {
      /**
      Construct a new tree. See also [`Tree.build`](#common.Tree^build).
      */
      constructor(type, children2, positions, length, props) {
        this.type = type;
        this.children = children2;
        this.positions = positions;
        this.length = length;
        this.props = null;
        if (props && props.length) {
          this.props = /* @__PURE__ */ Object.create(null);
          for (let [prop, value2] of props)
            this.props[typeof prop == "number" ? prop : prop.id] = value2;
        }
      }
      /**
      @internal
      */
      toString() {
        let mounted = MountedTree.get(this);
        if (mounted && !mounted.overlay)
          return mounted.tree.toString();
        let children2 = "";
        for (let ch3 of this.children) {
          let str2 = ch3.toString();
          if (str2) {
            if (children2)
              children2 += ",";
            children2 += str2;
          }
        }
        return !this.type.name ? children2 : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children2.length ? "(" + children2 + ")" : "");
      }
      /**
      Get a [tree cursor](#common.TreeCursor) positioned at the top of
      the tree. Mode can be used to [control](#common.IterMode) which
      nodes the cursor visits.
      */
      cursor(mode = 0) {
        return new TreeCursor(this.topNode, mode);
      }
      /**
      Get a [tree cursor](#common.TreeCursor) pointing into this tree
      at the given position and side (see
      [`moveTo`](#common.TreeCursor.moveTo).
      */
      cursorAt(pos2, side = 0, mode = 0) {
        let scope = CachedNode.get(this) || this.topNode;
        let cursor = new TreeCursor(scope);
        cursor.moveTo(pos2, side);
        CachedNode.set(this, cursor._tree);
        return cursor;
      }
      /**
      Get a [syntax node](#common.SyntaxNode) object for the top of the
      tree.
      */
      get topNode() {
        return new TreeNode(this, 0, 0, null);
      }
      /**
      Get the [syntax node](#common.SyntaxNode) at the given position.
      If `side` is -1, this will move into nodes that end at the
      position. If 1, it'll move into nodes that start at the
      position. With 0, it'll only enter nodes that cover the position
      from both sides.
      
      Note that this will not enter
      [overlays](#common.MountedTree.overlay), and you often want
      [`resolveInner`](#common.Tree.resolveInner) instead.
      */
      resolve(pos2, side = 0) {
        let node2 = resolveNode(CachedNode.get(this) || this.topNode, pos2, side, false);
        CachedNode.set(this, node2);
        return node2;
      }
      /**
      Like [`resolve`](#common.Tree.resolve), but will enter
      [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
      pointing into the innermost overlaid tree at the given position
      (with parent links going through all parent structure, including
      the host trees).
      */
      resolveInner(pos2, side = 0) {
        let node2 = resolveNode(CachedInnerNode.get(this) || this.topNode, pos2, side, true);
        CachedInnerNode.set(this, node2);
        return node2;
      }
      /**
      In some situations, it can be useful to iterate through all
      nodes around a position, including those in overlays that don't
      directly cover the position. This method gives you an iterator
      that will produce all nodes, from small to big, around the given
      position.
      */
      resolveStack(pos2, side = 0) {
        return stackIterator(this, pos2, side);
      }
      /**
      Iterate over the tree and its children, calling `enter` for any
      node that touches the `from`/`to` region (if given) before
      running over such a node's children, and `leave` (if given) when
      leaving the node. When `enter` returns `false`, that node will
      not have its children iterated over (or `leave` called).
      */
      iterate(spec) {
        let { enter, leave, from = 0, to: to2 = this.length } = spec;
        let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
        for (let c2 = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
          let entered = false;
          if (c2.from <= to2 && c2.to >= from && (!anon && c2.type.isAnonymous || enter(c2) !== false)) {
            if (c2.firstChild())
              continue;
            entered = true;
          }
          for (; ; ) {
            if (entered && leave && (anon || !c2.type.isAnonymous))
              leave(c2);
            if (c2.nextSibling())
              break;
            if (!c2.parent())
              return;
            entered = true;
          }
        }
      }
      /**
      Get the value of the given [node prop](#common.NodeProp) for this
      node. Works with both per-node and per-type props.
      */
      prop(prop) {
        return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
      }
      /**
      Returns the node's [per-node props](#common.NodeProp.perNode) in a
      format that can be passed to the [`Tree`](#common.Tree)
      constructor.
      */
      get propValues() {
        let result2 = [];
        if (this.props)
          for (let id in this.props)
            result2.push([+id, this.props[id]]);
        return result2;
      }
      /**
      Balance the direct children of this tree, producing a copy of
      which may have children grouped into subtrees with type
      [`NodeType.none`](#common.NodeType^none).
      */
      balance(config2 = {}) {
        return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children2, positions, length) => new Tree(this.type, children2, positions, length, this.propValues), config2.makeTree || ((children2, positions, length) => new Tree(NodeType.none, children2, positions, length)));
      }
      /**
      Build a tree from a postfix-ordered buffer of node information,
      or a cursor over such a buffer.
      */
      static build(data) {
        return buildTree(data);
      }
    }
    Tree.empty = new Tree(NodeType.none, [], [], 0);
    class FlatBufferCursor {
      constructor(buffer2, index2) {
        this.buffer = buffer2;
        this.index = index2;
      }
      get id() {
        return this.buffer[this.index - 4];
      }
      get start() {
        return this.buffer[this.index - 3];
      }
      get end() {
        return this.buffer[this.index - 2];
      }
      get size() {
        return this.buffer[this.index - 1];
      }
      get pos() {
        return this.index;
      }
      next() {
        this.index -= 4;
      }
      fork() {
        return new FlatBufferCursor(this.buffer, this.index);
      }
    }
    class TreeBuffer {
      /**
      Create a tree buffer.
      */
      constructor(buffer2, length, set) {
        this.buffer = buffer2;
        this.length = length;
        this.set = set;
      }
      /**
      @internal
      */
      get type() {
        return NodeType.none;
      }
      /**
      @internal
      */
      toString() {
        let result2 = [];
        for (let index2 = 0; index2 < this.buffer.length; ) {
          result2.push(this.childString(index2));
          index2 = this.buffer[index2 + 3];
        }
        return result2.join(",");
      }
      /**
      @internal
      */
      childString(index2) {
        let id = this.buffer[index2], endIndex = this.buffer[index2 + 3];
        let type = this.set.types[id], result2 = type.name;
        if (/\W/.test(result2) && !type.isError)
          result2 = JSON.stringify(result2);
        index2 += 4;
        if (endIndex == index2)
          return result2;
        let children2 = [];
        while (index2 < endIndex) {
          children2.push(this.childString(index2));
          index2 = this.buffer[index2 + 3];
        }
        return result2 + "(" + children2.join(",") + ")";
      }
      /**
      @internal
      */
      findChild(startIndex, endIndex, dir, pos2, side) {
        let { buffer: buffer2 } = this, pick = -1;
        for (let i2 = startIndex; i2 != endIndex; i2 = buffer2[i2 + 3]) {
          if (checkSide(side, pos2, buffer2[i2 + 1], buffer2[i2 + 2])) {
            pick = i2;
            if (dir > 0)
              break;
          }
        }
        return pick;
      }
      /**
      @internal
      */
      slice(startI, endI, from) {
        let b = this.buffer;
        let copy = new Uint16Array(endI - startI), len = 0;
        for (let i2 = startI, j2 = 0; i2 < endI; ) {
          copy[j2++] = b[i2++];
          copy[j2++] = b[i2++] - from;
          let to2 = copy[j2++] = b[i2++] - from;
          copy[j2++] = b[i2++] - startI;
          len = Math.max(len, to2);
        }
        return new TreeBuffer(copy, len, this.set);
      }
    }
    function checkSide(side, pos2, from, to2) {
      switch (side) {
        case -2:
          return from < pos2;
        case -1:
          return to2 >= pos2 && from < pos2;
        case 0:
          return from < pos2 && to2 > pos2;
        case 1:
          return from <= pos2 && to2 > pos2;
        case 2:
          return to2 > pos2;
        case 4:
          return true;
      }
    }
    function resolveNode(node2, pos2, side, overlays) {
      var _a2;
      while (node2.from == node2.to || (side < 1 ? node2.from >= pos2 : node2.from > pos2) || (side > -1 ? node2.to <= pos2 : node2.to < pos2)) {
        let parent = !overlays && node2 instanceof TreeNode && node2.index < 0 ? null : node2.parent;
        if (!parent)
          return node2;
        node2 = parent;
      }
      let mode = overlays ? 0 : IterMode.IgnoreOverlays;
      if (overlays)
        for (let scan = node2, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
          if (scan instanceof TreeNode && scan.index < 0 && ((_a2 = parent.enter(pos2, side, mode)) === null || _a2 === void 0 ? void 0 : _a2.from) != scan.from)
            node2 = parent;
        }
      for (; ; ) {
        let inner = node2.enter(pos2, side, mode);
        if (!inner)
          return node2;
        node2 = inner;
      }
    }
    class BaseNode {
      cursor(mode = 0) {
        return new TreeCursor(this, mode);
      }
      getChild(type, before = null, after = null) {
        let r2 = getChildren(this, type, before, after);
        return r2.length ? r2[0] : null;
      }
      getChildren(type, before = null, after = null) {
        return getChildren(this, type, before, after);
      }
      resolve(pos2, side = 0) {
        return resolveNode(this, pos2, side, false);
      }
      resolveInner(pos2, side = 0) {
        return resolveNode(this, pos2, side, true);
      }
      matchContext(context) {
        return matchNodeContext(this.parent, context);
      }
      enterUnfinishedNodesBefore(pos2) {
        let scan = this.childBefore(pos2), node2 = this;
        while (scan) {
          let last = scan.lastChild;
          if (!last || last.to != scan.to)
            break;
          if (last.type.isError && last.from == last.to) {
            node2 = scan;
            scan = last.prevSibling;
          } else {
            scan = last;
          }
        }
        return node2;
      }
      get node() {
        return this;
      }
      get next() {
        return this.parent;
      }
    }
    class TreeNode extends BaseNode {
      constructor(_tree, from, index2, _parent) {
        super();
        this._tree = _tree;
        this.from = from;
        this.index = index2;
        this._parent = _parent;
      }
      get type() {
        return this._tree.type;
      }
      get name() {
        return this._tree.type.name;
      }
      get to() {
        return this.from + this._tree.length;
      }
      nextChild(i2, dir, pos2, side, mode = 0) {
        for (let parent = this; ; ) {
          for (let { children: children2, positions } = parent._tree, e = dir > 0 ? children2.length : -1; i2 != e; i2 += dir) {
            let next = children2[i2], start = positions[i2] + parent.from;
            if (!checkSide(side, pos2, start, start + next.length))
              continue;
            if (next instanceof TreeBuffer) {
              if (mode & IterMode.ExcludeBuffers)
                continue;
              let index2 = next.findChild(0, next.buffer.length, dir, pos2 - start, side);
              if (index2 > -1)
                return new BufferNode(new BufferContext(parent, next, i2, start), null, index2);
            } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
              let mounted;
              if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
                return new TreeNode(mounted.tree, start, i2, parent);
              let inner = new TreeNode(next, start, i2, parent);
              return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos2, side);
            }
          }
          if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
            return null;
          if (parent.index >= 0)
            i2 = parent.index + dir;
          else
            i2 = dir < 0 ? -1 : parent._parent._tree.children.length;
          parent = parent._parent;
          if (!parent)
            return null;
        }
      }
      get firstChild() {
        return this.nextChild(
          0,
          1,
          0,
          4
          /* Side.DontCare */
        );
      }
      get lastChild() {
        return this.nextChild(
          this._tree.children.length - 1,
          -1,
          0,
          4
          /* Side.DontCare */
        );
      }
      childAfter(pos2) {
        return this.nextChild(
          0,
          1,
          pos2,
          2
          /* Side.After */
        );
      }
      childBefore(pos2) {
        return this.nextChild(
          this._tree.children.length - 1,
          -1,
          pos2,
          -2
          /* Side.Before */
        );
      }
      enter(pos2, side, mode = 0) {
        let mounted;
        if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
          let rPos = pos2 - this.from;
          for (let { from, to: to2 } of mounted.overlay) {
            if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to2 >= rPos : to2 > rPos))
              return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
          }
        }
        return this.nextChild(0, 1, pos2, side, mode);
      }
      nextSignificantParent() {
        let val = this;
        while (val.type.isAnonymous && val._parent)
          val = val._parent;
        return val;
      }
      get parent() {
        return this._parent ? this._parent.nextSignificantParent() : null;
      }
      get nextSibling() {
        return this._parent && this.index >= 0 ? this._parent.nextChild(
          this.index + 1,
          1,
          0,
          4
          /* Side.DontCare */
        ) : null;
      }
      get prevSibling() {
        return this._parent && this.index >= 0 ? this._parent.nextChild(
          this.index - 1,
          -1,
          0,
          4
          /* Side.DontCare */
        ) : null;
      }
      get tree() {
        return this._tree;
      }
      toTree() {
        return this._tree;
      }
      /**
      @internal
      */
      toString() {
        return this._tree.toString();
      }
    }
    function getChildren(node2, type, before, after) {
      let cur2 = node2.cursor(), result2 = [];
      if (!cur2.firstChild())
        return result2;
      if (before != null)
        for (let found = false; !found; ) {
          found = cur2.type.is(before);
          if (!cur2.nextSibling())
            return result2;
        }
      for (; ; ) {
        if (after != null && cur2.type.is(after))
          return result2;
        if (cur2.type.is(type))
          result2.push(cur2.node);
        if (!cur2.nextSibling())
          return after == null ? result2 : [];
      }
    }
    function matchNodeContext(node2, context, i2 = context.length - 1) {
      for (let p = node2; i2 >= 0; p = p.parent) {
        if (!p)
          return false;
        if (!p.type.isAnonymous) {
          if (context[i2] && context[i2] != p.name)
            return false;
          i2--;
        }
      }
      return true;
    }
    class BufferContext {
      constructor(parent, buffer2, index2, start) {
        this.parent = parent;
        this.buffer = buffer2;
        this.index = index2;
        this.start = start;
      }
    }
    class BufferNode extends BaseNode {
      get name() {
        return this.type.name;
      }
      get from() {
        return this.context.start + this.context.buffer.buffer[this.index + 1];
      }
      get to() {
        return this.context.start + this.context.buffer.buffer[this.index + 2];
      }
      constructor(context, _parent, index2) {
        super();
        this.context = context;
        this._parent = _parent;
        this.index = index2;
        this.type = context.buffer.set.types[context.buffer.buffer[index2]];
      }
      child(dir, pos2, side) {
        let { buffer: buffer2 } = this.context;
        let index2 = buffer2.findChild(this.index + 4, buffer2.buffer[this.index + 3], dir, pos2 - this.context.start, side);
        return index2 < 0 ? null : new BufferNode(this.context, this, index2);
      }
      get firstChild() {
        return this.child(
          1,
          0,
          4
          /* Side.DontCare */
        );
      }
      get lastChild() {
        return this.child(
          -1,
          0,
          4
          /* Side.DontCare */
        );
      }
      childAfter(pos2) {
        return this.child(
          1,
          pos2,
          2
          /* Side.After */
        );
      }
      childBefore(pos2) {
        return this.child(
          -1,
          pos2,
          -2
          /* Side.Before */
        );
      }
      enter(pos2, side, mode = 0) {
        if (mode & IterMode.ExcludeBuffers)
          return null;
        let { buffer: buffer2 } = this.context;
        let index2 = buffer2.findChild(this.index + 4, buffer2.buffer[this.index + 3], side > 0 ? 1 : -1, pos2 - this.context.start, side);
        return index2 < 0 ? null : new BufferNode(this.context, this, index2);
      }
      get parent() {
        return this._parent || this.context.parent.nextSignificantParent();
      }
      externalSibling(dir) {
        return this._parent ? null : this.context.parent.nextChild(
          this.context.index + dir,
          dir,
          0,
          4
          /* Side.DontCare */
        );
      }
      get nextSibling() {
        let { buffer: buffer2 } = this.context;
        let after = buffer2.buffer[this.index + 3];
        if (after < (this._parent ? buffer2.buffer[this._parent.index + 3] : buffer2.buffer.length))
          return new BufferNode(this.context, this._parent, after);
        return this.externalSibling(1);
      }
      get prevSibling() {
        let { buffer: buffer2 } = this.context;
        let parentStart = this._parent ? this._parent.index + 4 : 0;
        if (this.index == parentStart)
          return this.externalSibling(-1);
        return new BufferNode(this.context, this._parent, buffer2.findChild(
          parentStart,
          this.index,
          -1,
          0,
          4
          /* Side.DontCare */
        ));
      }
      get tree() {
        return null;
      }
      toTree() {
        let children2 = [], positions = [];
        let { buffer: buffer2 } = this.context;
        let startI = this.index + 4, endI = buffer2.buffer[this.index + 3];
        if (endI > startI) {
          let from = buffer2.buffer[this.index + 1];
          children2.push(buffer2.slice(startI, endI, from));
          positions.push(0);
        }
        return new Tree(this.type, children2, positions, this.to - this.from);
      }
      /**
      @internal
      */
      toString() {
        return this.context.buffer.childString(this.index);
      }
    }
    function iterStack(heads) {
      if (!heads.length)
        return null;
      let pick = 0, picked = heads[0];
      for (let i2 = 1; i2 < heads.length; i2++) {
        let node2 = heads[i2];
        if (node2.from > picked.from || node2.to < picked.to) {
          picked = node2;
          pick = i2;
        }
      }
      let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
      let newHeads = heads.slice();
      if (next)
        newHeads[pick] = next;
      else
        newHeads.splice(pick, 1);
      return new StackIterator(newHeads, picked);
    }
    class StackIterator {
      constructor(heads, node2) {
        this.heads = heads;
        this.node = node2;
      }
      get next() {
        return iterStack(this.heads);
      }
    }
    function stackIterator(tree, pos2, side) {
      let inner = tree.resolveInner(pos2, side), layers = null;
      for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
        if (scan.index < 0) {
          let parent = scan.parent;
          (layers || (layers = [inner])).push(parent.resolve(pos2, side));
          scan = parent;
        } else {
          let mount2 = MountedTree.get(scan.tree);
          if (mount2 && mount2.overlay && mount2.overlay[0].from <= pos2 && mount2.overlay[mount2.overlay.length - 1].to >= pos2) {
            let root2 = new TreeNode(mount2.tree, mount2.overlay[0].from + scan.from, -1, scan);
            (layers || (layers = [inner])).push(resolveNode(root2, pos2, side, false));
          }
        }
      }
      return layers ? iterStack(layers) : inner;
    }
    class TreeCursor {
      /**
      Shorthand for `.type.name`.
      */
      get name() {
        return this.type.name;
      }
      /**
      @internal
      */
      constructor(node2, mode = 0) {
        this.mode = mode;
        this.buffer = null;
        this.stack = [];
        this.index = 0;
        this.bufferNode = null;
        if (node2 instanceof TreeNode) {
          this.yieldNode(node2);
        } else {
          this._tree = node2.context.parent;
          this.buffer = node2.context;
          for (let n = node2._parent; n; n = n._parent)
            this.stack.unshift(n.index);
          this.bufferNode = node2;
          this.yieldBuf(node2.index);
        }
      }
      yieldNode(node2) {
        if (!node2)
          return false;
        this._tree = node2;
        this.type = node2.type;
        this.from = node2.from;
        this.to = node2.to;
        return true;
      }
      yieldBuf(index2, type) {
        this.index = index2;
        let { start, buffer: buffer2 } = this.buffer;
        this.type = type || buffer2.set.types[buffer2.buffer[index2]];
        this.from = start + buffer2.buffer[index2 + 1];
        this.to = start + buffer2.buffer[index2 + 2];
        return true;
      }
      /**
      @internal
      */
      yield(node2) {
        if (!node2)
          return false;
        if (node2 instanceof TreeNode) {
          this.buffer = null;
          return this.yieldNode(node2);
        }
        this.buffer = node2.context;
        return this.yieldBuf(node2.index, node2.type);
      }
      /**
      @internal
      */
      toString() {
        return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
      }
      /**
      @internal
      */
      enterChild(dir, pos2, side) {
        if (!this.buffer)
          return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos2, side, this.mode));
        let { buffer: buffer2 } = this.buffer;
        let index2 = buffer2.findChild(this.index + 4, buffer2.buffer[this.index + 3], dir, pos2 - this.buffer.start, side);
        if (index2 < 0)
          return false;
        this.stack.push(this.index);
        return this.yieldBuf(index2);
      }
      /**
      Move the cursor to this node's first child. When this returns
      false, the node has no child, and the cursor has not been moved.
      */
      firstChild() {
        return this.enterChild(
          1,
          0,
          4
          /* Side.DontCare */
        );
      }
      /**
      Move the cursor to this node's last child.
      */
      lastChild() {
        return this.enterChild(
          -1,
          0,
          4
          /* Side.DontCare */
        );
      }
      /**
      Move the cursor to the first child that ends after `pos`.
      */
      childAfter(pos2) {
        return this.enterChild(
          1,
          pos2,
          2
          /* Side.After */
        );
      }
      /**
      Move to the last child that starts before `pos`.
      */
      childBefore(pos2) {
        return this.enterChild(
          -1,
          pos2,
          -2
          /* Side.Before */
        );
      }
      /**
      Move the cursor to the child around `pos`. If side is -1 the
      child may end at that position, when 1 it may start there. This
      will also enter [overlaid](#common.MountedTree.overlay)
      [mounted](#common.NodeProp^mounted) trees unless `overlays` is
      set to false.
      */
      enter(pos2, side, mode = this.mode) {
        if (!this.buffer)
          return this.yield(this._tree.enter(pos2, side, mode));
        return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos2, side);
      }
      /**
      Move to the node's parent node, if this isn't the top node.
      */
      parent() {
        if (!this.buffer)
          return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
        if (this.stack.length)
          return this.yieldBuf(this.stack.pop());
        let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
        this.buffer = null;
        return this.yieldNode(parent);
      }
      /**
      @internal
      */
      sibling(dir) {
        if (!this.buffer)
          return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
        let { buffer: buffer2 } = this.buffer, d = this.stack.length - 1;
        if (dir < 0) {
          let parentStart = d < 0 ? 0 : this.stack[d] + 4;
          if (this.index != parentStart)
            return this.yieldBuf(buffer2.findChild(
              parentStart,
              this.index,
              -1,
              0,
              4
              /* Side.DontCare */
            ));
        } else {
          let after = buffer2.buffer[this.index + 3];
          if (after < (d < 0 ? buffer2.buffer.length : buffer2.buffer[this.stack[d] + 3]))
            return this.yieldBuf(after);
        }
        return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
      }
      /**
      Move to this node's next sibling, if any.
      */
      nextSibling() {
        return this.sibling(1);
      }
      /**
      Move to this node's previous sibling, if any.
      */
      prevSibling() {
        return this.sibling(-1);
      }
      atLastNode(dir) {
        let index2, parent, { buffer: buffer2 } = this;
        if (buffer2) {
          if (dir > 0) {
            if (this.index < buffer2.buffer.buffer.length)
              return false;
          } else {
            for (let i2 = 0; i2 < this.index; i2++)
              if (buffer2.buffer.buffer[i2 + 3] < this.index)
                return false;
          }
          ({ index: index2, parent } = buffer2);
        } else {
          ({ index: index2, _parent: parent } = this._tree);
        }
        for (; parent; { index: index2, _parent: parent } = parent) {
          if (index2 > -1)
            for (let i2 = index2 + dir, e = dir < 0 ? -1 : parent._tree.children.length; i2 != e; i2 += dir) {
              let child = parent._tree.children[i2];
              if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
                return false;
            }
        }
        return true;
      }
      move(dir, enter) {
        if (enter && this.enterChild(
          dir,
          0,
          4
          /* Side.DontCare */
        ))
          return true;
        for (; ; ) {
          if (this.sibling(dir))
            return true;
          if (this.atLastNode(dir) || !this.parent())
            return false;
        }
      }
      /**
      Move to the next node in a
      [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
      traversal, going from a node to its first child or, if the
      current node is empty or `enter` is false, its next sibling or
      the next sibling of the first parent node that has one.
      */
      next(enter = true) {
        return this.move(1, enter);
      }
      /**
      Move to the next node in a last-to-first pre-order traversal. A
      node is followed by its last child or, if it has none, its
      previous sibling or the previous sibling of the first parent
      node that has one.
      */
      prev(enter = true) {
        return this.move(-1, enter);
      }
      /**
      Move the cursor to the innermost node that covers `pos`. If
      `side` is -1, it will enter nodes that end at `pos`. If it is 1,
      it will enter nodes that start at `pos`.
      */
      moveTo(pos2, side = 0) {
        while (this.from == this.to || (side < 1 ? this.from >= pos2 : this.from > pos2) || (side > -1 ? this.to <= pos2 : this.to < pos2))
          if (!this.parent())
            break;
        while (this.enterChild(1, pos2, side)) {
        }
        return this;
      }
      /**
      Get a [syntax node](#common.SyntaxNode) at the cursor's current
      position.
      */
      get node() {
        if (!this.buffer)
          return this._tree;
        let cache = this.bufferNode, result2 = null, depth = 0;
        if (cache && cache.context == this.buffer) {
          scan: for (let index2 = this.index, d = this.stack.length; d >= 0; ) {
            for (let c2 = cache; c2; c2 = c2._parent)
              if (c2.index == index2) {
                if (index2 == this.index)
                  return c2;
                result2 = c2;
                depth = d + 1;
                break scan;
              }
            index2 = this.stack[--d];
          }
        }
        for (let i2 = depth; i2 < this.stack.length; i2++)
          result2 = new BufferNode(this.buffer, result2, this.stack[i2]);
        return this.bufferNode = new BufferNode(this.buffer, result2, this.index);
      }
      /**
      Get the [tree](#common.Tree) that represents the current node, if
      any. Will return null when the node is in a [tree
      buffer](#common.TreeBuffer).
      */
      get tree() {
        return this.buffer ? null : this._tree._tree;
      }
      /**
      Iterate over the current node and all its descendants, calling
      `enter` when entering a node and `leave`, if given, when leaving
      one. When `enter` returns `false`, any children of that node are
      skipped, and `leave` isn't called for it.
      */
      iterate(enter, leave) {
        for (let depth = 0; ; ) {
          let mustLeave = false;
          if (this.type.isAnonymous || enter(this) !== false) {
            if (this.firstChild()) {
              depth++;
              continue;
            }
            if (!this.type.isAnonymous)
              mustLeave = true;
          }
          for (; ; ) {
            if (mustLeave && leave)
              leave(this);
            mustLeave = this.type.isAnonymous;
            if (!depth)
              return;
            if (this.nextSibling())
              break;
            this.parent();
            depth--;
            mustLeave = true;
          }
        }
      }
      /**
      Test whether the current node matches a given context—a sequence
      of direct parent node names. Empty strings in the context array
      are treated as wildcards.
      */
      matchContext(context) {
        if (!this.buffer)
          return matchNodeContext(this.node.parent, context);
        let { buffer: buffer2 } = this.buffer, { types: types2 } = buffer2.set;
        for (let i2 = context.length - 1, d = this.stack.length - 1; i2 >= 0; d--) {
          if (d < 0)
            return matchNodeContext(this._tree, context, i2);
          let type = types2[buffer2.buffer[this.stack[d]]];
          if (!type.isAnonymous) {
            if (context[i2] && context[i2] != type.name)
              return false;
            i2--;
          }
        }
        return true;
      }
    }
    function hasChild(tree) {
      return tree.children.some((ch3) => ch3 instanceof TreeBuffer || !ch3.type.isAnonymous || hasChild(ch3));
    }
    function buildTree(data) {
      var _a2;
      let { buffer: buffer2, nodeSet: nodeSet2, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet2.types.length } = data;
      let cursor = Array.isArray(buffer2) ? new FlatBufferCursor(buffer2, buffer2.length) : buffer2;
      let types2 = nodeSet2.types;
      let contextHash = 0, lookAhead = 0;
      function takeNode(parentStart, minPos, children3, positions2, inRepeat, depth) {
        let { id, start, end, size } = cursor;
        let lookAheadAtStart = lookAhead, contextAtStart = contextHash;
        while (size < 0) {
          cursor.next();
          if (size == -1) {
            let node3 = reused[id];
            children3.push(node3);
            positions2.push(start - parentStart);
            return;
          } else if (size == -3) {
            contextHash = id;
            return;
          } else if (size == -4) {
            lookAhead = id;
            return;
          } else {
            throw new RangeError(`Unrecognized record size: ${size}`);
          }
        }
        let type = types2[id], node2, buffer3;
        let startPos = start - parentStart;
        if (end - start <= maxBufferLength && (buffer3 = findBufferSize(cursor.pos - minPos, inRepeat))) {
          let data2 = new Uint16Array(buffer3.size - buffer3.skip);
          let endPos = cursor.pos - buffer3.size, index2 = data2.length;
          while (cursor.pos > endPos)
            index2 = copyToBuffer(buffer3.start, data2, index2);
          node2 = new TreeBuffer(data2, end - buffer3.start, nodeSet2);
          startPos = buffer3.start - parentStart;
        } else {
          let endPos = cursor.pos - size;
          cursor.next();
          let localChildren = [], localPositions = [];
          let localInRepeat = id >= minRepeatType ? id : -1;
          let lastGroup = 0, lastEnd = end;
          while (cursor.pos > endPos) {
            if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
              if (cursor.end <= lastEnd - maxBufferLength) {
                makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
                lastGroup = localChildren.length;
                lastEnd = cursor.end;
              }
              cursor.next();
            } else if (depth > 2500) {
              takeFlatNode(start, endPos, localChildren, localPositions);
            } else {
              takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);
            }
          }
          if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
            makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
          localChildren.reverse();
          localPositions.reverse();
          if (localInRepeat > -1 && lastGroup > 0) {
            let make = makeBalanced(type, contextAtStart);
            node2 = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
          } else {
            node2 = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end, contextAtStart);
          }
        }
        children3.push(node2);
        positions2.push(startPos);
      }
      function takeFlatNode(parentStart, minPos, children3, positions2) {
        let nodes = [];
        let nodeCount = 0, stopAt = -1;
        while (cursor.pos > minPos) {
          let { id, start, end, size } = cursor;
          if (size > 4) {
            cursor.next();
          } else if (stopAt > -1 && start < stopAt) {
            break;
          } else {
            if (stopAt < 0)
              stopAt = end - maxBufferLength;
            nodes.push(id, start, end);
            nodeCount++;
            cursor.next();
          }
        }
        if (nodeCount) {
          let buffer3 = new Uint16Array(nodeCount * 4);
          let start = nodes[nodes.length - 2];
          for (let i2 = nodes.length - 3, j2 = 0; i2 >= 0; i2 -= 3) {
            buffer3[j2++] = nodes[i2];
            buffer3[j2++] = nodes[i2 + 1] - start;
            buffer3[j2++] = nodes[i2 + 2] - start;
            buffer3[j2++] = j2;
          }
          children3.push(new TreeBuffer(buffer3, nodes[2] - start, nodeSet2));
          positions2.push(start - parentStart);
        }
      }
      function makeBalanced(type, contextHash2) {
        return (children3, positions2, length2) => {
          let lookAhead2 = 0, lastI = children3.length - 1, last, lookAheadProp;
          if (lastI >= 0 && (last = children3[lastI]) instanceof Tree) {
            if (!lastI && last.type == type && last.length == length2)
              return last;
            if (lookAheadProp = last.prop(NodeProp.lookAhead))
              lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
          }
          return makeTree(type, children3, positions2, length2, lookAhead2, contextHash2);
        };
      }
      function makeRepeatLeaf(children3, positions2, base2, i2, from, to2, type, lookAhead2, contextHash2) {
        let localChildren = [], localPositions = [];
        while (children3.length > i2) {
          localChildren.push(children3.pop());
          localPositions.push(positions2.pop() + base2 - from);
        }
        children3.push(makeTree(nodeSet2.types[type], localChildren, localPositions, to2 - from, lookAhead2 - to2, contextHash2));
        positions2.push(from - base2);
      }
      function makeTree(type, children3, positions2, length2, lookAhead2, contextHash2, props) {
        if (contextHash2) {
          let pair = [NodeProp.contextHash, contextHash2];
          props = props ? [pair].concat(props) : [pair];
        }
        if (lookAhead2 > 25) {
          let pair = [NodeProp.lookAhead, lookAhead2];
          props = props ? [pair].concat(props) : [pair];
        }
        return new Tree(type, children3, positions2, length2, props);
      }
      function findBufferSize(maxSize, inRepeat) {
        let fork = cursor.fork();
        let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
        let result2 = { size: 0, start: 0, skip: 0 };
        scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
          let nodeSize2 = fork.size;
          if (fork.id == inRepeat && nodeSize2 >= 0) {
            result2.size = size;
            result2.start = start;
            result2.skip = skip;
            skip += 4;
            size += 4;
            fork.next();
            continue;
          }
          let startPos = fork.pos - nodeSize2;
          if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
            break;
          let localSkipped = fork.id >= minRepeatType ? 4 : 0;
          let nodeStart = fork.start;
          fork.next();
          while (fork.pos > startPos) {
            if (fork.size < 0) {
              if (fork.size == -3)
                localSkipped += 4;
              else
                break scan;
            } else if (fork.id >= minRepeatType) {
              localSkipped += 4;
            }
            fork.next();
          }
          start = nodeStart;
          size += nodeSize2;
          skip += localSkipped;
        }
        if (inRepeat < 0 || size == maxSize) {
          result2.size = size;
          result2.start = start;
          result2.skip = skip;
        }
        return result2.size > 4 ? result2 : void 0;
      }
      function copyToBuffer(bufferStart, buffer3, index2) {
        let { id, start, end, size } = cursor;
        cursor.next();
        if (size >= 0 && id < minRepeatType) {
          let startIndex = index2;
          if (size > 4) {
            let endPos = cursor.pos - (size - 4);
            while (cursor.pos > endPos)
              index2 = copyToBuffer(bufferStart, buffer3, index2);
          }
          buffer3[--index2] = startIndex;
          buffer3[--index2] = end - bufferStart;
          buffer3[--index2] = start - bufferStart;
          buffer3[--index2] = id;
        } else if (size == -3) {
          contextHash = id;
        } else if (size == -4) {
          lookAhead = id;
        }
        return index2;
      }
      let children2 = [], positions = [];
      while (cursor.pos > 0)
        takeNode(data.start || 0, data.bufferStart || 0, children2, positions, -1, 0);
      let length = (_a2 = data.length) !== null && _a2 !== void 0 ? _a2 : children2.length ? positions[0] + children2[0].length : 0;
      return new Tree(types2[data.topID], children2.reverse(), positions.reverse(), length);
    }
    const nodeSizeCache = /* @__PURE__ */ new WeakMap();
    function nodeSize(balanceType, node2) {
      if (!balanceType.isAnonymous || node2 instanceof TreeBuffer || node2.type != balanceType)
        return 1;
      let size = nodeSizeCache.get(node2);
      if (size == null) {
        size = 1;
        for (let child of node2.children) {
          if (child.type != balanceType || !(child instanceof Tree)) {
            size = 1;
            break;
          }
          size += nodeSize(balanceType, child);
        }
        nodeSizeCache.set(node2, size);
      }
      return size;
    }
    function balanceRange(balanceType, children2, positions, from, to2, start, length, mkTop, mkTree) {
      let total = 0;
      for (let i2 = from; i2 < to2; i2++)
        total += nodeSize(balanceType, children2[i2]);
      let maxChild = Math.ceil(
        total * 1.5 / 8
        /* Balance.BranchFactor */
      );
      let localChildren = [], localPositions = [];
      function divide(children3, positions2, from2, to3, offset) {
        for (let i2 = from2; i2 < to3; ) {
          let groupFrom = i2, groupStart = positions2[i2], groupSize = nodeSize(balanceType, children3[i2]);
          i2++;
          for (; i2 < to3; i2++) {
            let nextSize = nodeSize(balanceType, children3[i2]);
            if (groupSize + nextSize >= maxChild)
              break;
            groupSize += nextSize;
          }
          if (i2 == groupFrom + 1) {
            if (groupSize > maxChild) {
              let only = children3[groupFrom];
              divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
              continue;
            }
            localChildren.push(children3[groupFrom]);
          } else {
            let length2 = positions2[i2 - 1] + children3[i2 - 1].length - groupStart;
            localChildren.push(balanceRange(balanceType, children3, positions2, groupFrom, i2, groupStart, length2, null, mkTree));
          }
          localPositions.push(groupStart + offset - start);
        }
      }
      divide(children2, positions, from, to2, 0);
      return (mkTop || mkTree)(localChildren, localPositions, length);
    }
    class TreeFragment {
      /**
      Construct a tree fragment. You'll usually want to use
      [`addTree`](#common.TreeFragment^addTree) and
      [`applyChanges`](#common.TreeFragment^applyChanges) instead of
      calling this directly.
      */
      constructor(from, to2, tree, offset, openStart = false, openEnd = false) {
        this.from = from;
        this.to = to2;
        this.tree = tree;
        this.offset = offset;
        this.open = (openStart ? 1 : 0) | (openEnd ? 2 : 0);
      }
      /**
      Whether the start of the fragment represents the start of a
      parse, or the end of a change. (In the second case, it may not
      be safe to reuse some nodes at the start, depending on the
      parsing algorithm.)
      */
      get openStart() {
        return (this.open & 1) > 0;
      }
      /**
      Whether the end of the fragment represents the end of a
      full-document parse, or the start of a change.
      */
      get openEnd() {
        return (this.open & 2) > 0;
      }
      /**
      Create a set of fragments from a freshly parsed tree, or update
      an existing set of fragments by replacing the ones that overlap
      with a tree with content from the new tree. When `partial` is
      true, the parse is treated as incomplete, and the resulting
      fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
      true.
      */
      static addTree(tree, fragments = [], partial = false) {
        let result2 = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
        for (let f of fragments)
          if (f.to > tree.length)
            result2.push(f);
        return result2;
      }
      /**
      Apply a set of edits to an array of fragments, removing or
      splitting fragments as necessary to remove edited ranges, and
      adjusting offsets for fragments that moved.
      */
      static applyChanges(fragments, changes, minGap = 128) {
        if (!changes.length)
          return fragments;
        let result2 = [];
        let fI = 1, nextF = fragments.length ? fragments[0] : null;
        for (let cI = 0, pos2 = 0, off = 0; ; cI++) {
          let nextC = cI < changes.length ? changes[cI] : null;
          let nextPos = nextC ? nextC.fromA : 1e9;
          if (nextPos - pos2 >= minGap)
            while (nextF && nextF.from < nextPos) {
              let cut = nextF;
              if (pos2 >= cut.from || nextPos <= cut.to || off) {
                let fFrom = Math.max(cut.from, pos2) - off, fTo = Math.min(cut.to, nextPos) - off;
                cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
              }
              if (cut)
                result2.push(cut);
              if (nextF.to > nextPos)
                break;
              nextF = fI < fragments.length ? fragments[fI++] : null;
            }
          if (!nextC)
            break;
          pos2 = nextC.toA;
          off = nextC.toA - nextC.toB;
        }
        return result2;
      }
    }
    class Parser {
      /**
      Start a parse, returning a [partial parse](#common.PartialParse)
      object. [`fragments`](#common.TreeFragment) can be passed in to
      make the parse incremental.
      
      By default, the entire input is parsed. You can pass `ranges`,
      which should be a sorted array of non-empty, non-overlapping
      ranges, to parse only those ranges. The tree returned in that
      case will start at `ranges[0].from`.
      */
      startParse(input2, fragments, ranges) {
        if (typeof input2 == "string")
          input2 = new StringInput(input2);
        ranges = !ranges ? [new Range(0, input2.length)] : ranges.length ? ranges.map((r2) => new Range(r2.from, r2.to)) : [new Range(0, 0)];
        return this.createParse(input2, fragments || [], ranges);
      }
      /**
      Run a full parse, returning the resulting tree.
      */
      parse(input2, fragments, ranges) {
        let parse2 = this.startParse(input2, fragments, ranges);
        for (; ; ) {
          let done = parse2.advance();
          if (done)
            return done;
        }
      }
    }
    class StringInput {
      constructor(string2) {
        this.string = string2;
      }
      get length() {
        return this.string.length;
      }
      chunk(from) {
        return this.string.slice(from);
      }
      get lineChunks() {
        return false;
      }
      read(from, to2) {
        return this.string.slice(from, to2);
      }
    }
    new NodeProp({ perNode: true });
    let nextTagID = 0;
    class Tag {
      /**
      @internal
      */
      constructor(name2, set, base2, modified) {
        this.name = name2;
        this.set = set;
        this.base = base2;
        this.modified = modified;
        this.id = nextTagID++;
      }
      toString() {
        let { name: name2 } = this;
        for (let mod2 of this.modified)
          if (mod2.name)
            name2 = `${mod2.name}(${name2})`;
        return name2;
      }
      static define(nameOrParent, parent) {
        let name2 = typeof nameOrParent == "string" ? nameOrParent : "?";
        if (nameOrParent instanceof Tag)
          parent = nameOrParent;
        if (parent === null || parent === void 0 ? void 0 : parent.base)
          throw new Error("Can not derive from a modified tag");
        let tag = new Tag(name2, [], null, []);
        tag.set.push(tag);
        if (parent)
          for (let t2 of parent.set)
            tag.set.push(t2);
        return tag;
      }
      /**
      Define a tag _modifier_, which is a function that, given a tag,
      will return a tag that is a subtag of the original. Applying the
      same modifier to a twice tag will return the same value (`m1(t1)
      == m1(t1)`) and applying multiple modifiers will, regardless or
      order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
      
      When multiple modifiers are applied to a given base tag, each
      smaller set of modifiers is registered as a parent, so that for
      example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
      `m1(m3(t1)`, and so on.
      */
      static defineModifier(name2) {
        let mod2 = new Modifier(name2);
        return (tag) => {
          if (tag.modified.indexOf(mod2) > -1)
            return tag;
          return Modifier.get(tag.base || tag, tag.modified.concat(mod2).sort((a, b) => a.id - b.id));
        };
      }
    }
    let nextModifierID = 0;
    class Modifier {
      constructor(name2) {
        this.name = name2;
        this.instances = [];
        this.id = nextModifierID++;
      }
      static get(base2, mods) {
        if (!mods.length)
          return base2;
        let exists = mods[0].instances.find((t2) => t2.base == base2 && sameArray(mods, t2.modified));
        if (exists)
          return exists;
        let set = [], tag = new Tag(base2.name, set, base2, mods);
        for (let m of mods)
          m.instances.push(tag);
        let configs = powerSet(mods);
        for (let parent of base2.set)
          if (!parent.modified.length)
            for (let config2 of configs)
              set.push(Modifier.get(parent, config2));
        return tag;
      }
    }
    function sameArray(a, b) {
      return a.length == b.length && a.every((x2, i2) => x2 == b[i2]);
    }
    function powerSet(array) {
      let sets = [[]];
      for (let i2 = 0; i2 < array.length; i2++) {
        for (let j2 = 0, e = sets.length; j2 < e; j2++) {
          sets.push(sets[j2].concat(array[i2]));
        }
      }
      return sets.sort((a, b) => b.length - a.length);
    }
    function styleTags(spec) {
      let byName = /* @__PURE__ */ Object.create(null);
      for (let prop in spec) {
        let tags2 = spec[prop];
        if (!Array.isArray(tags2))
          tags2 = [tags2];
        for (let part of prop.split(" "))
          if (part) {
            let pieces = [], mode = 2, rest = part;
            for (let pos2 = 0; ; ) {
              if (rest == "..." && pos2 > 0 && pos2 + 3 == part.length) {
                mode = 1;
                break;
              }
              let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
              if (!m)
                throw new RangeError("Invalid path: " + part);
              pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
              pos2 += m[0].length;
              if (pos2 == part.length)
                break;
              let next = part[pos2++];
              if (pos2 == part.length && next == "!") {
                mode = 0;
                break;
              }
              if (next != "/")
                throw new RangeError("Invalid path: " + part);
              rest = part.slice(pos2);
            }
            let last = pieces.length - 1, inner = pieces[last];
            if (!inner)
              throw new RangeError("Invalid path: " + part);
            let rule = new Rule(tags2, mode, last > 0 ? pieces.slice(0, last) : null);
            byName[inner] = rule.sort(byName[inner]);
          }
      }
      return ruleNodeProp.add(byName);
    }
    const ruleNodeProp = new NodeProp();
    class Rule {
      constructor(tags2, mode, context, next) {
        this.tags = tags2;
        this.mode = mode;
        this.context = context;
        this.next = next;
      }
      get opaque() {
        return this.mode == 0;
      }
      get inherit() {
        return this.mode == 1;
      }
      sort(other) {
        if (!other || other.depth < this.depth) {
          this.next = other;
          return this;
        }
        other.next = this.sort(other.next);
        return other;
      }
      get depth() {
        return this.context ? this.context.length : 0;
      }
    }
    Rule.empty = new Rule([], 2, null);
    function tagHighlighter(tags2, options2) {
      let map2 = /* @__PURE__ */ Object.create(null);
      for (let style2 of tags2) {
        if (!Array.isArray(style2.tag))
          map2[style2.tag.id] = style2.class;
        else
          for (let tag of style2.tag)
            map2[tag.id] = style2.class;
      }
      let { scope, all: all2 = null } = options2 || {};
      return {
        style: (tags3) => {
          let cls = all2;
          for (let tag of tags3) {
            for (let sub of tag.set) {
              let tagClass = map2[sub.id];
              if (tagClass) {
                cls = cls ? cls + " " + tagClass : tagClass;
                break;
              }
            }
          }
          return cls;
        },
        scope
      };
    }
    function highlightTags(highlighters, tags2) {
      let result2 = null;
      for (let highlighter of highlighters) {
        let value2 = highlighter.style(tags2);
        if (value2)
          result2 = result2 ? result2 + " " + value2 : value2;
      }
      return result2;
    }
    function highlightTree(tree, highlighter, putStyle, from = 0, to2 = tree.length) {
      let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
      builder.highlightRange(tree.cursor(), from, to2, "", builder.highlighters);
      builder.flush(to2);
    }
    class HighlightBuilder {
      constructor(at2, highlighters, span) {
        this.at = at2;
        this.highlighters = highlighters;
        this.span = span;
        this.class = "";
      }
      startSpan(at2, cls) {
        if (cls != this.class) {
          this.flush(at2);
          if (at2 > this.at)
            this.at = at2;
          this.class = cls;
        }
      }
      flush(to2) {
        if (to2 > this.at && this.class)
          this.span(this.at, to2, this.class);
      }
      highlightRange(cursor, from, to2, inheritedClass, highlighters) {
        let { type, from: start, to: end } = cursor;
        if (start >= to2 || end <= from)
          return;
        if (type.isTop)
          highlighters = this.highlighters.filter((h) => !h.scope || h.scope(type));
        let cls = inheritedClass;
        let rule = getStyleTags(cursor) || Rule.empty;
        let tagCls = highlightTags(highlighters, rule.tags);
        if (tagCls) {
          if (cls)
            cls += " ";
          cls += tagCls;
          if (rule.mode == 1)
            inheritedClass += (inheritedClass ? " " : "") + tagCls;
        }
        this.startSpan(Math.max(from, start), cls);
        if (rule.opaque)
          return;
        let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
        if (mounted && mounted.overlay) {
          let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
          let innerHighlighters = this.highlighters.filter((h) => !h.scope || h.scope(mounted.tree.type));
          let hasChild2 = cursor.firstChild();
          for (let i2 = 0, pos2 = start; ; i2++) {
            let next = i2 < mounted.overlay.length ? mounted.overlay[i2] : null;
            let nextPos = next ? next.from + start : end;
            let rangeFrom2 = Math.max(from, pos2), rangeTo2 = Math.min(to2, nextPos);
            if (rangeFrom2 < rangeTo2 && hasChild2) {
              while (cursor.from < rangeTo2) {
                this.highlightRange(cursor, rangeFrom2, rangeTo2, inheritedClass, highlighters);
                this.startSpan(Math.min(rangeTo2, cursor.to), cls);
                if (cursor.to >= nextPos || !cursor.nextSibling())
                  break;
              }
            }
            if (!next || nextPos > to2)
              break;
            pos2 = next.to + start;
            if (pos2 > from) {
              this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to2, pos2), "", innerHighlighters);
              this.startSpan(Math.min(to2, pos2), cls);
            }
          }
          if (hasChild2)
            cursor.parent();
        } else if (cursor.firstChild()) {
          if (mounted)
            inheritedClass = "";
          do {
            if (cursor.to <= from)
              continue;
            if (cursor.from >= to2)
              break;
            this.highlightRange(cursor, from, to2, inheritedClass, highlighters);
            this.startSpan(Math.min(to2, cursor.to), cls);
          } while (cursor.nextSibling());
          cursor.parent();
        }
      }
    }
    function getStyleTags(node2) {
      let rule = node2.type.prop(ruleNodeProp);
      while (rule && rule.context && !node2.matchContext(rule.context))
        rule = rule.next;
      return rule || null;
    }
    const t = Tag.define;
    const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal$1 = t(), string = t(literal$1), number = t(literal$1), content$1 = t(), heading = t(content$1), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
    const tags = {
      /**
      A comment.
      */
      comment,
      /**
      A line [comment](#highlight.tags.comment).
      */
      lineComment: t(comment),
      /**
      A block [comment](#highlight.tags.comment).
      */
      blockComment: t(comment),
      /**
      A documentation [comment](#highlight.tags.comment).
      */
      docComment: t(comment),
      /**
      Any kind of identifier.
      */
      name,
      /**
      The [name](#highlight.tags.name) of a variable.
      */
      variableName: t(name),
      /**
      A type [name](#highlight.tags.name).
      */
      typeName,
      /**
      A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
      */
      tagName: t(typeName),
      /**
      A property or field [name](#highlight.tags.name).
      */
      propertyName,
      /**
      An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
      */
      attributeName: t(propertyName),
      /**
      The [name](#highlight.tags.name) of a class.
      */
      className: t(name),
      /**
      A label [name](#highlight.tags.name).
      */
      labelName: t(name),
      /**
      A namespace [name](#highlight.tags.name).
      */
      namespace: t(name),
      /**
      The [name](#highlight.tags.name) of a macro.
      */
      macroName: t(name),
      /**
      A literal value.
      */
      literal: literal$1,
      /**
      A string [literal](#highlight.tags.literal).
      */
      string,
      /**
      A documentation [string](#highlight.tags.string).
      */
      docString: t(string),
      /**
      A character literal (subtag of [string](#highlight.tags.string)).
      */
      character: t(string),
      /**
      An attribute value (subtag of [string](#highlight.tags.string)).
      */
      attributeValue: t(string),
      /**
      A number [literal](#highlight.tags.literal).
      */
      number,
      /**
      An integer [number](#highlight.tags.number) literal.
      */
      integer: t(number),
      /**
      A floating-point [number](#highlight.tags.number) literal.
      */
      float: t(number),
      /**
      A boolean [literal](#highlight.tags.literal).
      */
      bool: t(literal$1),
      /**
      Regular expression [literal](#highlight.tags.literal).
      */
      regexp: t(literal$1),
      /**
      An escape [literal](#highlight.tags.literal), for example a
      backslash escape in a string.
      */
      escape: t(literal$1),
      /**
      A color [literal](#highlight.tags.literal).
      */
      color: t(literal$1),
      /**
      A URL [literal](#highlight.tags.literal).
      */
      url: t(literal$1),
      /**
      A language keyword.
      */
      keyword,
      /**
      The [keyword](#highlight.tags.keyword) for the self or this
      object.
      */
      self: t(keyword),
      /**
      The [keyword](#highlight.tags.keyword) for null.
      */
      null: t(keyword),
      /**
      A [keyword](#highlight.tags.keyword) denoting some atomic value.
      */
      atom: t(keyword),
      /**
      A [keyword](#highlight.tags.keyword) that represents a unit.
      */
      unit: t(keyword),
      /**
      A modifier [keyword](#highlight.tags.keyword).
      */
      modifier: t(keyword),
      /**
      A [keyword](#highlight.tags.keyword) that acts as an operator.
      */
      operatorKeyword: t(keyword),
      /**
      A control-flow related [keyword](#highlight.tags.keyword).
      */
      controlKeyword: t(keyword),
      /**
      A [keyword](#highlight.tags.keyword) that defines something.
      */
      definitionKeyword: t(keyword),
      /**
      A [keyword](#highlight.tags.keyword) related to defining or
      interfacing with modules.
      */
      moduleKeyword: t(keyword),
      /**
      An operator.
      */
      operator,
      /**
      An [operator](#highlight.tags.operator) that dereferences something.
      */
      derefOperator: t(operator),
      /**
      Arithmetic-related [operator](#highlight.tags.operator).
      */
      arithmeticOperator: t(operator),
      /**
      Logical [operator](#highlight.tags.operator).
      */
      logicOperator: t(operator),
      /**
      Bit [operator](#highlight.tags.operator).
      */
      bitwiseOperator: t(operator),
      /**
      Comparison [operator](#highlight.tags.operator).
      */
      compareOperator: t(operator),
      /**
      [Operator](#highlight.tags.operator) that updates its operand.
      */
      updateOperator: t(operator),
      /**
      [Operator](#highlight.tags.operator) that defines something.
      */
      definitionOperator: t(operator),
      /**
      Type-related [operator](#highlight.tags.operator).
      */
      typeOperator: t(operator),
      /**
      Control-flow [operator](#highlight.tags.operator).
      */
      controlOperator: t(operator),
      /**
      Program or markup punctuation.
      */
      punctuation,
      /**
      [Punctuation](#highlight.tags.punctuation) that separates
      things.
      */
      separator: t(punctuation),
      /**
      Bracket-style [punctuation](#highlight.tags.punctuation).
      */
      bracket,
      /**
      Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
      tokens).
      */
      angleBracket: t(bracket),
      /**
      Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
      tokens).
      */
      squareBracket: t(bracket),
      /**
      Parentheses (usually `(` and `)` tokens). Subtag of
      [bracket](#highlight.tags.bracket).
      */
      paren: t(bracket),
      /**
      Braces (usually `{` and `}` tokens). Subtag of
      [bracket](#highlight.tags.bracket).
      */
      brace: t(bracket),
      /**
      Content, for example plain text in XML or markup documents.
      */
      content: content$1,
      /**
      [Content](#highlight.tags.content) that represents a heading.
      */
      heading,
      /**
      A level 1 [heading](#highlight.tags.heading).
      */
      heading1: t(heading),
      /**
      A level 2 [heading](#highlight.tags.heading).
      */
      heading2: t(heading),
      /**
      A level 3 [heading](#highlight.tags.heading).
      */
      heading3: t(heading),
      /**
      A level 4 [heading](#highlight.tags.heading).
      */
      heading4: t(heading),
      /**
      A level 5 [heading](#highlight.tags.heading).
      */
      heading5: t(heading),
      /**
      A level 6 [heading](#highlight.tags.heading).
      */
      heading6: t(heading),
      /**
      A prose [content](#highlight.tags.content) separator (such as a horizontal rule).
      */
      contentSeparator: t(content$1),
      /**
      [Content](#highlight.tags.content) that represents a list.
      */
      list: t(content$1),
      /**
      [Content](#highlight.tags.content) that represents a quote.
      */
      quote: t(content$1),
      /**
      [Content](#highlight.tags.content) that is emphasized.
      */
      emphasis: t(content$1),
      /**
      [Content](#highlight.tags.content) that is styled strong.
      */
      strong: t(content$1),
      /**
      [Content](#highlight.tags.content) that is part of a link.
      */
      link: t(content$1),
      /**
      [Content](#highlight.tags.content) that is styled as code or
      monospace.
      */
      monospace: t(content$1),
      /**
      [Content](#highlight.tags.content) that has a strike-through
      style.
      */
      strikethrough: t(content$1),
      /**
      Inserted text in a change-tracking format.
      */
      inserted: t(),
      /**
      Deleted text.
      */
      deleted: t(),
      /**
      Changed text.
      */
      changed: t(),
      /**
      An invalid or unsyntactic element.
      */
      invalid: t(),
      /**
      Metadata or meta-instruction.
      */
      meta,
      /**
      [Metadata](#highlight.tags.meta) that applies to the entire
      document.
      */
      documentMeta: t(meta),
      /**
      [Metadata](#highlight.tags.meta) that annotates or adds
      attributes to a given syntactic element.
      */
      annotation: t(meta),
      /**
      Processing instruction or preprocessor directive. Subtag of
      [meta](#highlight.tags.meta).
      */
      processingInstruction: t(meta),
      /**
      [Modifier](#highlight.Tag^defineModifier) that indicates that a
      given element is being defined. Expected to be used with the
      various [name](#highlight.tags.name) tags.
      */
      definition: Tag.defineModifier("definition"),
      /**
      [Modifier](#highlight.Tag^defineModifier) that indicates that
      something is constant. Mostly expected to be used with
      [variable names](#highlight.tags.variableName).
      */
      constant: Tag.defineModifier("constant"),
      /**
      [Modifier](#highlight.Tag^defineModifier) used to indicate that
      a [variable](#highlight.tags.variableName) or [property
      name](#highlight.tags.propertyName) is being called or defined
      as a function.
      */
      function: Tag.defineModifier("function"),
      /**
      [Modifier](#highlight.Tag^defineModifier) that can be applied to
      [names](#highlight.tags.name) to indicate that they belong to
      the language's standard environment.
      */
      standard: Tag.defineModifier("standard"),
      /**
      [Modifier](#highlight.Tag^defineModifier) that indicates a given
      [names](#highlight.tags.name) is local to some scope.
      */
      local: Tag.defineModifier("local"),
      /**
      A generic variant [modifier](#highlight.Tag^defineModifier) that
      can be used to tag language-specific alternative variants of
      some common tag. It is recommended for themes to define special
      forms of at least the [string](#highlight.tags.string) and
      [variable name](#highlight.tags.variableName) tags, since those
      come up a lot.
      */
      special: Tag.defineModifier("special")
    };
    for (let name2 in tags) {
      let val = tags[name2];
      if (val instanceof Tag)
        val.name = name2;
    }
    tagHighlighter([
      { tag: tags.link, class: "tok-link" },
      { tag: tags.heading, class: "tok-heading" },
      { tag: tags.emphasis, class: "tok-emphasis" },
      { tag: tags.strong, class: "tok-strong" },
      { tag: tags.keyword, class: "tok-keyword" },
      { tag: tags.atom, class: "tok-atom" },
      { tag: tags.bool, class: "tok-bool" },
      { tag: tags.url, class: "tok-url" },
      { tag: tags.labelName, class: "tok-labelName" },
      { tag: tags.inserted, class: "tok-inserted" },
      { tag: tags.deleted, class: "tok-deleted" },
      { tag: tags.literal, class: "tok-literal" },
      { tag: tags.string, class: "tok-string" },
      { tag: tags.number, class: "tok-number" },
      { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
      { tag: tags.variableName, class: "tok-variableName" },
      { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
      { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
      { tag: tags.special(tags.variableName), class: "tok-variableName2" },
      { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
      { tag: tags.typeName, class: "tok-typeName" },
      { tag: tags.namespace, class: "tok-namespace" },
      { tag: tags.className, class: "tok-className" },
      { tag: tags.macroName, class: "tok-macroName" },
      { tag: tags.propertyName, class: "tok-propertyName" },
      { tag: tags.operator, class: "tok-operator" },
      { tag: tags.comment, class: "tok-comment" },
      { tag: tags.meta, class: "tok-meta" },
      { tag: tags.invalid, class: "tok-invalid" },
      { tag: tags.punctuation, class: "tok-punctuation" }
    ]);
    var _a$1;
    const languageDataProp = /* @__PURE__ */ new NodeProp();
    function defineLanguageFacet(baseData) {
      return Facet.define({
        combine: baseData ? (values) => values.concat(baseData) : void 0
      });
    }
    const sublanguageProp = /* @__PURE__ */ new NodeProp();
    class Language {
      /**
      Construct a language object. If you need to invoke this
      directly, first define a data facet with
      [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
      configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
      to the language's outer syntax node.
      */
      constructor(data, parser2, extraExtensions = [], name2 = "") {
        this.data = data;
        this.name = name2;
        if (!EditorState.prototype.hasOwnProperty("tree"))
          Object.defineProperty(EditorState.prototype, "tree", { get() {
            return syntaxTree(this);
          } });
        this.parser = parser2;
        this.extension = [
          language$1.of(this),
          EditorState.languageData.of((state, pos2, side) => {
            let top2 = topNodeAt(state, pos2, side), data2 = top2.type.prop(languageDataProp);
            if (!data2)
              return [];
            let base2 = state.facet(data2), sub = top2.type.prop(sublanguageProp);
            if (sub) {
              let innerNode = top2.resolve(pos2 - top2.from, side);
              for (let sublang of sub)
                if (sublang.test(innerNode, state)) {
                  let data3 = state.facet(sublang.facet);
                  return sublang.type == "replace" ? data3 : data3.concat(base2);
                }
            }
            return base2;
          })
        ].concat(extraExtensions);
      }
      /**
      Query whether this language is active at the given position.
      */
      isActiveAt(state, pos2, side = -1) {
        return topNodeAt(state, pos2, side).type.prop(languageDataProp) == this.data;
      }
      /**
      Find the document regions that were parsed using this language.
      The returned regions will _include_ any nested languages rooted
      in this language, when those exist.
      */
      findRegions(state) {
        let lang = state.facet(language$1);
        if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
          return [{ from: 0, to: state.doc.length }];
        if (!lang || !lang.allowsNesting)
          return [];
        let result2 = [];
        let explore = (tree, from) => {
          if (tree.prop(languageDataProp) == this.data) {
            result2.push({ from, to: from + tree.length });
            return;
          }
          let mount2 = tree.prop(NodeProp.mounted);
          if (mount2) {
            if (mount2.tree.prop(languageDataProp) == this.data) {
              if (mount2.overlay)
                for (let r2 of mount2.overlay)
                  result2.push({ from: r2.from + from, to: r2.to + from });
              else
                result2.push({ from, to: from + tree.length });
              return;
            } else if (mount2.overlay) {
              let size = result2.length;
              explore(mount2.tree, mount2.overlay[0].from + from);
              if (result2.length > size)
                return;
            }
          }
          for (let i2 = 0; i2 < tree.children.length; i2++) {
            let ch3 = tree.children[i2];
            if (ch3 instanceof Tree)
              explore(ch3, tree.positions[i2] + from);
          }
        };
        explore(syntaxTree(state), 0);
        return result2;
      }
      /**
      Indicates whether this language allows nested languages. The
      default implementation returns true.
      */
      get allowsNesting() {
        return true;
      }
    }
    Language.setState = /* @__PURE__ */ StateEffect.define();
    function topNodeAt(state, pos2, side) {
      let topLang = state.facet(language$1), tree = syntaxTree(state).topNode;
      if (!topLang || topLang.allowsNesting) {
        for (let node2 = tree; node2; node2 = node2.enter(pos2, side, IterMode.ExcludeBuffers))
          if (node2.type.isTop)
            tree = node2;
      }
      return tree;
    }
    function syntaxTree(state) {
      let field = state.field(Language.state, false);
      return field ? field.tree : Tree.empty;
    }
    class DocInput {
      /**
      Create an input object for the given document.
      */
      constructor(doc2) {
        this.doc = doc2;
        this.cursorPos = 0;
        this.string = "";
        this.cursor = doc2.iter();
      }
      get length() {
        return this.doc.length;
      }
      syncTo(pos2) {
        this.string = this.cursor.next(pos2 - this.cursorPos).value;
        this.cursorPos = pos2 + this.string.length;
        return this.cursorPos - this.string.length;
      }
      chunk(pos2) {
        this.syncTo(pos2);
        return this.string;
      }
      get lineChunks() {
        return true;
      }
      read(from, to2) {
        let stringStart = this.cursorPos - this.string.length;
        if (from < stringStart || to2 >= this.cursorPos)
          return this.doc.sliceString(from, to2);
        else
          return this.string.slice(from - stringStart, to2 - stringStart);
      }
    }
    let currentContext = null;
    class ParseContext {
      constructor(parser2, state, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) {
        this.parser = parser2;
        this.state = state;
        this.fragments = fragments;
        this.tree = tree;
        this.treeLen = treeLen;
        this.viewport = viewport;
        this.skipped = skipped;
        this.scheduleOn = scheduleOn;
        this.parse = null;
        this.tempSkipped = [];
      }
      /**
      @internal
      */
      static create(parser2, state, viewport) {
        return new ParseContext(parser2, state, [], Tree.empty, 0, viewport, [], null);
      }
      startParse() {
        return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
      }
      /**
      @internal
      */
      work(until, upto) {
        if (upto != null && upto >= this.state.doc.length)
          upto = void 0;
        if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
          this.takeTree();
          return true;
        }
        return this.withContext(() => {
          var _a2;
          if (typeof until == "number") {
            let endTime = Date.now() + until;
            until = () => Date.now() > endTime;
          }
          if (!this.parse)
            this.parse = this.startParse();
          if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length)
            this.parse.stopAt(upto);
          for (; ; ) {
            let done = this.parse.advance();
            if (done) {
              this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
              this.treeLen = (_a2 = this.parse.stoppedAt) !== null && _a2 !== void 0 ? _a2 : this.state.doc.length;
              this.tree = done;
              this.parse = null;
              if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
                this.parse = this.startParse();
              else
                return true;
            }
            if (until())
              return false;
          }
        });
      }
      /**
      @internal
      */
      takeTree() {
        let pos2, tree;
        if (this.parse && (pos2 = this.parse.parsedPos) >= this.treeLen) {
          if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos2)
            this.parse.stopAt(pos2);
          this.withContext(() => {
            while (!(tree = this.parse.advance())) {
            }
          });
          this.treeLen = pos2;
          this.tree = tree;
          this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
          this.parse = null;
        }
      }
      withContext(f) {
        let prev = currentContext;
        currentContext = this;
        try {
          return f();
        } finally {
          currentContext = prev;
        }
      }
      withoutTempSkipped(fragments) {
        for (let r2; r2 = this.tempSkipped.pop(); )
          fragments = cutFragments(fragments, r2.from, r2.to);
        return fragments;
      }
      /**
      @internal
      */
      changes(changes, newState) {
        let { fragments, tree, treeLen, viewport, skipped } = this;
        this.takeTree();
        if (!changes.empty) {
          let ranges = [];
          changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
          fragments = TreeFragment.applyChanges(fragments, ranges);
          tree = Tree.empty;
          treeLen = 0;
          viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
          if (this.skipped.length) {
            skipped = [];
            for (let r2 of this.skipped) {
              let from = changes.mapPos(r2.from, 1), to2 = changes.mapPos(r2.to, -1);
              if (from < to2)
                skipped.push({ from, to: to2 });
            }
          }
        }
        return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
      }
      /**
      @internal
      */
      updateViewport(viewport) {
        if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
          return false;
        this.viewport = viewport;
        let startLen = this.skipped.length;
        for (let i2 = 0; i2 < this.skipped.length; i2++) {
          let { from, to: to2 } = this.skipped[i2];
          if (from < viewport.to && to2 > viewport.from) {
            this.fragments = cutFragments(this.fragments, from, to2);
            this.skipped.splice(i2--, 1);
          }
        }
        if (this.skipped.length >= startLen)
          return false;
        this.reset();
        return true;
      }
      /**
      @internal
      */
      reset() {
        if (this.parse) {
          this.takeTree();
          this.parse = null;
        }
      }
      /**
      Notify the parse scheduler that the given region was skipped
      because it wasn't in view, and the parse should be restarted
      when it comes into view.
      */
      skipUntilInView(from, to2) {
        this.skipped.push({ from, to: to2 });
      }
      /**
      Returns a parser intended to be used as placeholder when
      asynchronously loading a nested parser. It'll skip its input and
      mark it as not-really-parsed, so that the next update will parse
      it again.
      
      When `until` is given, a reparse will be scheduled when that
      promise resolves.
      */
      static getSkippingParser(until) {
        return new class extends Parser {
          createParse(input2, fragments, ranges) {
            let from = ranges[0].from, to2 = ranges[ranges.length - 1].to;
            let parser2 = {
              parsedPos: from,
              advance() {
                let cx = currentContext;
                if (cx) {
                  for (let r2 of ranges)
                    cx.tempSkipped.push(r2);
                  if (until)
                    cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
                }
                this.parsedPos = to2;
                return new Tree(NodeType.none, [], [], to2 - from);
              },
              stoppedAt: null,
              stopAt() {
              }
            };
            return parser2;
          }
        }();
      }
      /**
      @internal
      */
      isDone(upto) {
        upto = Math.min(upto, this.state.doc.length);
        let frags = this.fragments;
        return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
      }
      /**
      Get the context for the current parse, or `null` if no editor
      parse is in progress.
      */
      static get() {
        return currentContext;
      }
    }
    function cutFragments(fragments, from, to2) {
      return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to2, fromB: from, toB: to2 }]);
    }
    class LanguageState {
      constructor(context) {
        this.context = context;
        this.tree = context.tree;
      }
      apply(tr2) {
        if (!tr2.docChanged && this.tree == this.context.tree)
          return this;
        let newCx = this.context.changes(tr2.changes, tr2.state);
        let upto = this.context.treeLen == tr2.startState.doc.length ? void 0 : Math.max(tr2.changes.mapPos(this.context.treeLen), newCx.viewport.to);
        if (!newCx.work(20, upto))
          newCx.takeTree();
        return new LanguageState(newCx);
      }
      static init(state) {
        let vpTo = Math.min(3e3, state.doc.length);
        let parseState2 = ParseContext.create(state.facet(language$1).parser, state, { from: 0, to: vpTo });
        if (!parseState2.work(20, vpTo))
          parseState2.takeTree();
        return new LanguageState(parseState2);
      }
    }
    Language.state = /* @__PURE__ */ StateField.define({
      create: LanguageState.init,
      update(value2, tr2) {
        for (let e of tr2.effects)
          if (e.is(Language.setState))
            return e.value;
        if (tr2.startState.facet(language$1) != tr2.state.facet(language$1))
          return LanguageState.init(tr2.state);
        return value2.apply(tr2);
      }
    });
    let requestIdle = (callback) => {
      let timeout = setTimeout(
        () => callback(),
        500
        /* Work.MaxPause */
      );
      return () => clearTimeout(timeout);
    };
    if (typeof requestIdleCallback != "undefined")
      requestIdle = (callback) => {
        let idle = -1, timeout = setTimeout(
          () => {
            idle = requestIdleCallback(callback, {
              timeout: 500 - 100
              /* Work.MinPause */
            });
          },
          100
          /* Work.MinPause */
        );
        return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
      };
    const isInputPending = typeof navigator != "undefined" && ((_a$1 = navigator.scheduling) === null || _a$1 === void 0 ? void 0 : _a$1.isInputPending) ? () => navigator.scheduling.isInputPending() : null;
    const parseWorker = /* @__PURE__ */ ViewPlugin.fromClass(class ParseWorker {
      constructor(view) {
        this.view = view;
        this.working = null;
        this.workScheduled = 0;
        this.chunkEnd = -1;
        this.chunkBudget = -1;
        this.work = this.work.bind(this);
        this.scheduleWork();
      }
      update(update) {
        let cx = this.view.state.field(Language.state).context;
        if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen)
          this.scheduleWork();
        if (update.docChanged || update.selectionSet) {
          if (this.view.hasFocus)
            this.chunkBudget += 50;
          this.scheduleWork();
        }
        this.checkAsyncSchedule(cx);
      }
      scheduleWork() {
        if (this.working)
          return;
        let { state } = this.view, field = state.field(Language.state);
        if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
          this.working = requestIdle(this.work);
      }
      work(deadline) {
        this.working = null;
        let now2 = Date.now();
        if (this.chunkEnd < now2 && (this.chunkEnd < 0 || this.view.hasFocus)) {
          this.chunkEnd = now2 + 3e4;
          this.chunkBudget = 3e3;
        }
        if (this.chunkBudget <= 0)
          return;
        let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
        if (field.tree == field.context.tree && field.context.isDone(
          vpTo + 1e5
          /* Work.MaxParseAhead */
        ))
          return;
        let endTime = Date.now() + Math.min(this.chunkBudget, 100, deadline && !isInputPending ? Math.max(25, deadline.timeRemaining() - 5) : 1e9);
        let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1e3;
        let done = field.context.work(() => {
          return isInputPending && isInputPending() || Date.now() > endTime;
        }, vpTo + (viewportFirst ? 0 : 1e5));
        this.chunkBudget -= Date.now() - now2;
        if (done || this.chunkBudget <= 0) {
          field.context.takeTree();
          this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
        }
        if (this.chunkBudget > 0 && !(done && !viewportFirst))
          this.scheduleWork();
        this.checkAsyncSchedule(field.context);
      }
      checkAsyncSchedule(cx) {
        if (cx.scheduleOn) {
          this.workScheduled++;
          cx.scheduleOn.then(() => this.scheduleWork()).catch((err2) => logException(this.view.state, err2)).then(() => this.workScheduled--);
          cx.scheduleOn = null;
        }
      }
      destroy() {
        if (this.working)
          this.working();
      }
      isWorking() {
        return !!(this.working || this.workScheduled > 0);
      }
    }, {
      eventHandlers: { focus() {
        this.scheduleWork();
      } }
    });
    const language$1 = /* @__PURE__ */ Facet.define({
      combine(languages) {
        return languages.length ? languages[0] : null;
      },
      enables: (language2) => [
        Language.state,
        parseWorker,
        EditorView.contentAttributes.compute([language2], (state) => {
          let lang = state.facet(language2);
          return lang && lang.name ? { "data-language": lang.name } : {};
        })
      ]
    });
    const indentService = /* @__PURE__ */ Facet.define();
    const indentUnit = /* @__PURE__ */ Facet.define({
      combine: (values) => {
        if (!values.length)
          return "  ";
        let unit = values[0];
        if (!unit || /\S/.test(unit) || Array.from(unit).some((e) => e != unit[0]))
          throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
        return unit;
      }
    });
    function getIndentUnit(state) {
      let unit = state.facet(indentUnit);
      return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
    }
    function indentString(state, cols) {
      let result2 = "", ts = state.tabSize, ch3 = state.facet(indentUnit)[0];
      if (ch3 == "	") {
        while (cols >= ts) {
          result2 += "	";
          cols -= ts;
        }
        ch3 = " ";
      }
      for (let i2 = 0; i2 < cols; i2++)
        result2 += ch3;
      return result2;
    }
    function getIndentation(context, pos2) {
      if (context instanceof EditorState)
        context = new IndentContext(context);
      for (let service of context.state.facet(indentService)) {
        let result2 = service(context, pos2);
        if (result2 !== void 0)
          return result2;
      }
      let tree = syntaxTree(context.state);
      return tree.length >= pos2 ? syntaxIndentation(context, tree, pos2) : null;
    }
    class IndentContext {
      /**
      Create an indent context.
      */
      constructor(state, options2 = {}) {
        this.state = state;
        this.options = options2;
        this.unit = getIndentUnit(state);
      }
      /**
      Get a description of the line at the given position, taking
      [simulated line
      breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
      into account. If there is such a break at `pos`, the `bias`
      argument determines whether the part of the line line before or
      after the break is used.
      */
      lineAt(pos2, bias = 1) {
        let line2 = this.state.doc.lineAt(pos2);
        let { simulateBreak, simulateDoubleBreak } = this.options;
        if (simulateBreak != null && simulateBreak >= line2.from && simulateBreak <= line2.to) {
          if (simulateDoubleBreak && simulateBreak == pos2)
            return { text: "", from: pos2 };
          else if (bias < 0 ? simulateBreak < pos2 : simulateBreak <= pos2)
            return { text: line2.text.slice(simulateBreak - line2.from), from: simulateBreak };
          else
            return { text: line2.text.slice(0, simulateBreak - line2.from), from: line2.from };
        }
        return line2;
      }
      /**
      Get the text directly after `pos`, either the entire line
      or the next 100 characters, whichever is shorter.
      */
      textAfterPos(pos2, bias = 1) {
        if (this.options.simulateDoubleBreak && pos2 == this.options.simulateBreak)
          return "";
        let { text: text2, from } = this.lineAt(pos2, bias);
        return text2.slice(pos2 - from, Math.min(text2.length, pos2 + 100 - from));
      }
      /**
      Find the column for the given position.
      */
      column(pos2, bias = 1) {
        let { text: text2, from } = this.lineAt(pos2, bias);
        let result2 = this.countColumn(text2, pos2 - from);
        let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
        if (override > -1)
          result2 += override - this.countColumn(text2, text2.search(/\S|$/));
        return result2;
      }
      /**
      Find the column position (taking tabs into account) of the given
      position in the given string.
      */
      countColumn(line2, pos2 = line2.length) {
        return countColumn(line2, this.state.tabSize, pos2);
      }
      /**
      Find the indentation column of the line at the given point.
      */
      lineIndent(pos2, bias = 1) {
        let { text: text2, from } = this.lineAt(pos2, bias);
        let override = this.options.overrideIndentation;
        if (override) {
          let overriden = override(from);
          if (overriden > -1)
            return overriden;
        }
        return this.countColumn(text2, text2.search(/\S|$/));
      }
      /**
      Returns the [simulated line
      break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
      for this context, if any.
      */
      get simulatedBreak() {
        return this.options.simulateBreak || null;
      }
    }
    const indentNodeProp = /* @__PURE__ */ new NodeProp();
    function syntaxIndentation(cx, ast, pos2) {
      let stack2 = ast.resolveStack(pos2);
      let inner = ast.resolveInner(pos2, -1).resolve(pos2, 0).enterUnfinishedNodesBefore(pos2);
      if (inner != stack2.node) {
        let add2 = [];
        for (let cur2 = inner; cur2 && !(cur2.from == stack2.node.from && cur2.type == stack2.node.type); cur2 = cur2.parent)
          add2.push(cur2);
        for (let i2 = add2.length - 1; i2 >= 0; i2--)
          stack2 = { node: add2[i2], next: stack2 };
      }
      return indentFor(stack2, cx, pos2);
    }
    function indentFor(stack2, cx, pos2) {
      for (let cur2 = stack2; cur2; cur2 = cur2.next) {
        let strategy = indentStrategy(cur2.node);
        if (strategy)
          return strategy(TreeIndentContext.create(cx, pos2, cur2));
      }
      return 0;
    }
    function ignoreClosed(cx) {
      return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
    }
    function indentStrategy(tree) {
      let strategy = tree.type.prop(indentNodeProp);
      if (strategy)
        return strategy;
      let first2 = tree.firstChild, close2;
      if (first2 && (close2 = first2.type.prop(NodeProp.closedBy))) {
        let last = tree.lastChild, closed = last && close2.indexOf(last.name) > -1;
        return (cx) => delimitedStrategy(cx, true, 1, void 0, closed && !ignoreClosed(cx) ? last.from : void 0);
      }
      return tree.parent == null ? topIndent : null;
    }
    function topIndent() {
      return 0;
    }
    class TreeIndentContext extends IndentContext {
      constructor(base2, pos2, context) {
        super(base2.state, base2.options);
        this.base = base2;
        this.pos = pos2;
        this.context = context;
      }
      /**
      The syntax tree node to which the indentation strategy
      applies.
      */
      get node() {
        return this.context.node;
      }
      /**
      @internal
      */
      static create(base2, pos2, context) {
        return new TreeIndentContext(base2, pos2, context);
      }
      /**
      Get the text directly after `this.pos`, either the entire line
      or the next 100 characters, whichever is shorter.
      */
      get textAfter() {
        return this.textAfterPos(this.pos);
      }
      /**
      Get the indentation at the reference line for `this.node`, which
      is the line on which it starts, unless there is a node that is
      _not_ a parent of this node covering the start of that line. If
      so, the line at the start of that node is tried, again skipping
      on if it is covered by another such node.
      */
      get baseIndent() {
        return this.baseIndentFor(this.node);
      }
      /**
      Get the indentation for the reference line of the given node
      (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
      */
      baseIndentFor(node2) {
        let line2 = this.state.doc.lineAt(node2.from);
        for (; ; ) {
          let atBreak = node2.resolve(line2.from);
          while (atBreak.parent && atBreak.parent.from == atBreak.from)
            atBreak = atBreak.parent;
          if (isParent(atBreak, node2))
            break;
          line2 = this.state.doc.lineAt(atBreak.from);
        }
        return this.lineIndent(line2.from);
      }
      /**
      Continue looking for indentations in the node's parent nodes,
      and return the result of that.
      */
      continue() {
        return indentFor(this.context.next, this.base, this.pos);
      }
    }
    function isParent(parent, of) {
      for (let cur2 = of; cur2; cur2 = cur2.parent)
        if (parent == cur2)
          return true;
      return false;
    }
    function bracketedAligned(context) {
      let tree = context.node;
      let openToken = tree.childAfter(tree.from), last = tree.lastChild;
      if (!openToken)
        return null;
      let sim = context.options.simulateBreak;
      let openLine = context.state.doc.lineAt(openToken.from);
      let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
      for (let pos2 = openToken.to; ; ) {
        let next = tree.childAfter(pos2);
        if (!next || next == last)
          return null;
        if (!next.type.isSkipped) {
          if (next.from >= lineEnd)
            return null;
          let space = /^ */.exec(openLine.text.slice(openToken.to - openLine.from))[0].length;
          return { from: openToken.from, to: openToken.to + space };
        }
        pos2 = next.to;
      }
    }
    function delimitedStrategy(context, align, units, closing, closedAt) {
      let after = context.textAfter, space = after.match(/^\s*/)[0].length;
      let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
      let aligned = bracketedAligned(context);
      if (aligned)
        return closed ? context.column(aligned.from) : context.column(aligned.to);
      return context.baseIndent + (closed ? 0 : context.unit * units);
    }
    class HighlightStyle {
      constructor(specs, options2) {
        this.specs = specs;
        let modSpec;
        function def(spec) {
          let cls = StyleModule.newName();
          (modSpec || (modSpec = /* @__PURE__ */ Object.create(null)))["." + cls] = spec;
          return cls;
        }
        const all2 = typeof options2.all == "string" ? options2.all : options2.all ? def(options2.all) : void 0;
        const scopeOpt = options2.scope;
        this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? (type) => type == scopeOpt : void 0;
        this.style = tagHighlighter(specs.map((style2) => ({
          tag: style2.tag,
          class: style2.class || def(Object.assign({}, style2, { tag: null }))
        })), {
          all: all2
        }).style;
        this.module = modSpec ? new StyleModule(modSpec) : null;
        this.themeType = options2.themeType;
      }
      /**
      Create a highlighter style that associates the given styles to
      the given tags. The specs must be objects that hold a style tag
      or array of tags in their `tag` property, and either a single
      `class` property providing a static CSS class (for highlighter
      that rely on external styling), or a
      [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
      set of CSS properties (which define the styling for those tags).
      
      The CSS rules created for a highlighter will be emitted in the
      order of the spec's properties. That means that for elements that
      have multiple tags associated with them, styles defined further
      down in the list will have a higher CSS precedence than styles
      defined earlier.
      */
      static define(specs, options2) {
        return new HighlightStyle(specs, options2 || {});
      }
    }
    const highlighterFacet = /* @__PURE__ */ Facet.define();
    const fallbackHighlighter = /* @__PURE__ */ Facet.define({
      combine(values) {
        return values.length ? [values[0]] : null;
      }
    });
    function getHighlighters(state) {
      let main = state.facet(highlighterFacet);
      return main.length ? main : state.facet(fallbackHighlighter);
    }
    function syntaxHighlighting(highlighter, options2) {
      let ext = [treeHighlighter], themeType;
      if (highlighter instanceof HighlightStyle) {
        if (highlighter.module)
          ext.push(EditorView.styleModule.of(highlighter.module));
        themeType = highlighter.themeType;
      }
      if (options2 === null || options2 === void 0 ? void 0 : options2.fallback)
        ext.push(fallbackHighlighter.of(highlighter));
      else if (themeType)
        ext.push(highlighterFacet.computeN([EditorView.darkTheme], (state) => {
          return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
        }));
      else
        ext.push(highlighterFacet.of(highlighter));
      return ext;
    }
    class TreeHighlighter {
      constructor(view) {
        this.markCache = /* @__PURE__ */ Object.create(null);
        this.tree = syntaxTree(view.state);
        this.decorations = this.buildDeco(view, getHighlighters(view.state));
        this.decoratedTo = view.viewport.to;
      }
      update(update) {
        let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state);
        let styleChange = highlighters != getHighlighters(update.startState);
        let { viewport } = update.view, decoratedToMapped = update.changes.mapPos(this.decoratedTo, 1);
        if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
          this.decorations = this.decorations.map(update.changes);
          this.decoratedTo = decoratedToMapped;
        } else if (tree != this.tree || update.viewportChanged || styleChange) {
          this.tree = tree;
          this.decorations = this.buildDeco(update.view, highlighters);
          this.decoratedTo = viewport.to;
        }
      }
      buildDeco(view, highlighters) {
        if (!highlighters || !this.tree.length)
          return Decoration.none;
        let builder = new RangeSetBuilder();
        for (let { from, to: to2 } of view.visibleRanges) {
          highlightTree(this.tree, highlighters, (from2, to3, style2) => {
            builder.add(from2, to3, this.markCache[style2] || (this.markCache[style2] = Decoration.mark({ class: style2 })));
          }, from, to2);
        }
        return builder.finish();
      }
    }
    const treeHighlighter = /* @__PURE__ */ Prec.high(/* @__PURE__ */ ViewPlugin.fromClass(TreeHighlighter, {
      decorations: (v) => v.decorations
    }));
    const defaultHighlightStyle = /* @__PURE__ */ HighlightStyle.define([
      {
        tag: tags.meta,
        color: "#404740"
      },
      {
        tag: tags.link,
        textDecoration: "underline"
      },
      {
        tag: tags.heading,
        textDecoration: "underline",
        fontWeight: "bold"
      },
      {
        tag: tags.emphasis,
        fontStyle: "italic"
      },
      {
        tag: tags.strong,
        fontWeight: "bold"
      },
      {
        tag: tags.strikethrough,
        textDecoration: "line-through"
      },
      {
        tag: tags.keyword,
        color: "#708"
      },
      {
        tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
        color: "#219"
      },
      {
        tag: [tags.literal, tags.inserted],
        color: "#164"
      },
      {
        tag: [tags.string, tags.deleted],
        color: "#a11"
      },
      {
        tag: [tags.regexp, tags.escape, /* @__PURE__ */ tags.special(tags.string)],
        color: "#e40"
      },
      {
        tag: /* @__PURE__ */ tags.definition(tags.variableName),
        color: "#00f"
      },
      {
        tag: /* @__PURE__ */ tags.local(tags.variableName),
        color: "#30a"
      },
      {
        tag: [tags.typeName, tags.namespace],
        color: "#085"
      },
      {
        tag: tags.className,
        color: "#167"
      },
      {
        tag: [/* @__PURE__ */ tags.special(tags.variableName), tags.macroName],
        color: "#256"
      },
      {
        tag: /* @__PURE__ */ tags.definition(tags.propertyName),
        color: "#00c"
      },
      {
        tag: tags.comment,
        color: "#940"
      },
      {
        tag: tags.invalid,
        color: "#f00"
      }
    ]);
    const baseTheme$2 = /* @__PURE__ */ EditorView.baseTheme({
      "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
      "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
    });
    const DefaultScanDist = 1e4, DefaultBrackets = "()[]{}";
    const bracketMatchingConfig = /* @__PURE__ */ Facet.define({
      combine(configs) {
        return combineConfig(configs, {
          afterCursor: true,
          brackets: DefaultBrackets,
          maxScanDistance: DefaultScanDist,
          renderMatch: defaultRenderMatch
        });
      }
    });
    const matchingMark = /* @__PURE__ */ Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /* @__PURE__ */ Decoration.mark({ class: "cm-nonmatchingBracket" });
    function defaultRenderMatch(match) {
      let decorations2 = [];
      let mark = match.matched ? matchingMark : nonmatchingMark;
      decorations2.push(mark.range(match.start.from, match.start.to));
      if (match.end)
        decorations2.push(mark.range(match.end.from, match.end.to));
      return decorations2;
    }
    const bracketMatchingState = /* @__PURE__ */ StateField.define({
      create() {
        return Decoration.none;
      },
      update(deco, tr2) {
        if (!tr2.docChanged && !tr2.selection)
          return deco;
        let decorations2 = [];
        let config2 = tr2.state.facet(bracketMatchingConfig);
        for (let range of tr2.state.selection.ranges) {
          if (!range.empty)
            continue;
          let match = matchBrackets(tr2.state, range.head, -1, config2) || range.head > 0 && matchBrackets(tr2.state, range.head - 1, 1, config2) || config2.afterCursor && (matchBrackets(tr2.state, range.head, 1, config2) || range.head < tr2.state.doc.length && matchBrackets(tr2.state, range.head + 1, -1, config2));
          if (match)
            decorations2 = decorations2.concat(config2.renderMatch(match, tr2.state));
        }
        return Decoration.set(decorations2, true);
      },
      provide: (f) => EditorView.decorations.from(f)
    });
    const bracketMatchingUnique = [
      bracketMatchingState,
      baseTheme$2
    ];
    function bracketMatching(config2 = {}) {
      return [bracketMatchingConfig.of(config2), bracketMatchingUnique];
    }
    const bracketMatchingHandle = /* @__PURE__ */ new NodeProp();
    function matchingNodes(node2, dir, brackets) {
      let byProp = node2.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
      if (byProp)
        return byProp;
      if (node2.name.length == 1) {
        let index2 = brackets.indexOf(node2.name);
        if (index2 > -1 && index2 % 2 == (dir < 0 ? 1 : 0))
          return [brackets[index2 + dir]];
      }
      return null;
    }
    function findHandle(node2) {
      let hasHandle = node2.type.prop(bracketMatchingHandle);
      return hasHandle ? hasHandle(node2.node) : node2;
    }
    function matchBrackets(state, pos2, dir, config2 = {}) {
      let maxScanDistance = config2.maxScanDistance || DefaultScanDist, brackets = config2.brackets || DefaultBrackets;
      let tree = syntaxTree(state), node2 = tree.resolveInner(pos2, dir);
      for (let cur2 = node2; cur2; cur2 = cur2.parent) {
        let matches = matchingNodes(cur2.type, dir, brackets);
        if (matches && cur2.from < cur2.to) {
          let handle = findHandle(cur2);
          if (handle && (dir > 0 ? pos2 >= handle.from && pos2 < handle.to : pos2 > handle.from && pos2 <= handle.to))
            return matchMarkedBrackets(state, pos2, dir, cur2, handle, matches, brackets);
        }
      }
      return matchPlainBrackets(state, pos2, dir, tree, node2.type, maxScanDistance, brackets);
    }
    function matchMarkedBrackets(_state, _pos, dir, token2, handle, matching, brackets) {
      let parent = token2.parent, firstToken = { from: handle.from, to: handle.to };
      let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
      if (cursor && (dir < 0 ? cursor.childBefore(token2.from) : cursor.childAfter(token2.to)))
        do {
          if (dir < 0 ? cursor.to <= token2.from : cursor.from >= token2.to) {
            if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
              let endHandle = findHandle(cursor);
              return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : void 0, matched: true };
            } else if (matchingNodes(cursor.type, dir, brackets)) {
              depth++;
            } else if (matchingNodes(cursor.type, -dir, brackets)) {
              if (depth == 0) {
                let endHandle = findHandle(cursor);
                return {
                  start: firstToken,
                  end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : void 0,
                  matched: false
                };
              }
              depth--;
            }
          }
        } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
      return { start: firstToken, matched: false };
    }
    function matchPlainBrackets(state, pos2, dir, tree, tokenType, maxScanDistance, brackets) {
      let startCh = dir < 0 ? state.sliceDoc(pos2 - 1, pos2) : state.sliceDoc(pos2, pos2 + 1);
      let bracket2 = brackets.indexOf(startCh);
      if (bracket2 < 0 || bracket2 % 2 == 0 != dir > 0)
        return null;
      let startToken = { from: dir < 0 ? pos2 - 1 : pos2, to: dir > 0 ? pos2 + 1 : pos2 };
      let iter = state.doc.iterRange(pos2, dir > 0 ? state.doc.length : 0), depth = 0;
      for (let distance = 0; !iter.next().done && distance <= maxScanDistance; ) {
        let text2 = iter.value;
        if (dir < 0)
          distance += text2.length;
        let basePos = pos2 + distance * dir;
        for (let pos3 = dir > 0 ? 0 : text2.length - 1, end = dir > 0 ? text2.length : -1; pos3 != end; pos3 += dir) {
          let found = brackets.indexOf(text2[pos3]);
          if (found < 0 || tree.resolveInner(basePos + pos3, 1).type != tokenType)
            continue;
          if (found % 2 == 0 == dir > 0) {
            depth++;
          } else if (depth == 1) {
            return { start: startToken, end: { from: basePos + pos3, to: basePos + pos3 + 1 }, matched: found >> 1 == bracket2 >> 1 };
          } else {
            depth--;
          }
        }
        if (dir > 0)
          distance += text2.length;
      }
      return iter.done ? { start: startToken, matched: false } : null;
    }
    function countCol(string2, end, tabSize, startIndex = 0, startValue = 0) {
      if (end == null) {
        end = string2.search(/[^\s\u00a0]/);
        if (end == -1)
          end = string2.length;
      }
      let n = startValue;
      for (let i2 = startIndex; i2 < end; i2++) {
        if (string2.charCodeAt(i2) == 9)
          n += tabSize - n % tabSize;
        else
          n++;
      }
      return n;
    }
    class StringStream {
      /**
      Create a stream.
      */
      constructor(string2, tabSize, indentUnit2, overrideIndent) {
        this.string = string2;
        this.tabSize = tabSize;
        this.indentUnit = indentUnit2;
        this.overrideIndent = overrideIndent;
        this.pos = 0;
        this.start = 0;
        this.lastColumnPos = 0;
        this.lastColumnValue = 0;
      }
      /**
      True if we are at the end of the line.
      */
      eol() {
        return this.pos >= this.string.length;
      }
      /**
      True if we are at the start of the line.
      */
      sol() {
        return this.pos == 0;
      }
      /**
      Get the next code unit after the current position, or undefined
      if we're at the end of the line.
      */
      peek() {
        return this.string.charAt(this.pos) || void 0;
      }
      /**
      Read the next code unit and advance `this.pos`.
      */
      next() {
        if (this.pos < this.string.length)
          return this.string.charAt(this.pos++);
      }
      /**
      Match the next character against the given string, regular
      expression, or predicate. Consume and return it if it matches.
      */
      eat(match) {
        let ch3 = this.string.charAt(this.pos);
        let ok;
        if (typeof match == "string")
          ok = ch3 == match;
        else
          ok = ch3 && (match instanceof RegExp ? match.test(ch3) : match(ch3));
        if (ok) {
          ++this.pos;
          return ch3;
        }
      }
      /**
      Continue matching characters that match the given string,
      regular expression, or predicate function. Return true if any
      characters were consumed.
      */
      eatWhile(match) {
        let start = this.pos;
        while (this.eat(match)) {
        }
        return this.pos > start;
      }
      /**
      Consume whitespace ahead of `this.pos`. Return true if any was
      found.
      */
      eatSpace() {
        let start = this.pos;
        while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
          ++this.pos;
        return this.pos > start;
      }
      /**
      Move to the end of the line.
      */
      skipToEnd() {
        this.pos = this.string.length;
      }
      /**
      Move to directly before the given character, if found on the
      current line.
      */
      skipTo(ch3) {
        let found = this.string.indexOf(ch3, this.pos);
        if (found > -1) {
          this.pos = found;
          return true;
        }
      }
      /**
      Move back `n` characters.
      */
      backUp(n) {
        this.pos -= n;
      }
      /**
      Get the column position at `this.pos`.
      */
      column() {
        if (this.lastColumnPos < this.start) {
          this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
          this.lastColumnPos = this.start;
        }
        return this.lastColumnValue;
      }
      /**
      Get the indentation column of the current line.
      */
      indentation() {
        var _a2;
        return (_a2 = this.overrideIndent) !== null && _a2 !== void 0 ? _a2 : countCol(this.string, null, this.tabSize);
      }
      /**
      Match the input against the given string or regular expression
      (which should start with a `^`). Return true or the regexp match
      if it matches.
      
      Unless `consume` is set to `false`, this will move `this.pos`
      past the matched text.
      
      When matching a string `caseInsensitive` can be set to true to
      make the match case-insensitive.
      */
      match(pattern, consume, caseInsensitive) {
        if (typeof pattern == "string") {
          let cased = (str2) => caseInsensitive ? str2.toLowerCase() : str2;
          let substr = this.string.substr(this.pos, pattern.length);
          if (cased(substr) == cased(pattern)) {
            if (consume !== false)
              this.pos += pattern.length;
            return true;
          } else
            return null;
        } else {
          let match = this.string.slice(this.pos).match(pattern);
          if (match && match.index > 0)
            return null;
          if (match && consume !== false)
            this.pos += match[0].length;
          return match;
        }
      }
      /**
      Get the current token.
      */
      current() {
        return this.string.slice(this.start, this.pos);
      }
    }
    function fullParser(spec) {
      return {
        name: spec.name || "",
        token: spec.token,
        blankLine: spec.blankLine || (() => {
        }),
        startState: spec.startState || (() => true),
        copyState: spec.copyState || defaultCopyState,
        indent: spec.indent || (() => null),
        languageData: spec.languageData || {},
        tokenTable: spec.tokenTable || noTokens,
        mergeTokens: spec.mergeTokens !== false
      };
    }
    function defaultCopyState(state) {
      if (typeof state != "object")
        return state;
      let newState = {};
      for (let prop in state) {
        let val = state[prop];
        newState[prop] = val instanceof Array ? val.slice() : val;
      }
      return newState;
    }
    const IndentedFrom = /* @__PURE__ */ new WeakMap();
    class StreamLanguage extends Language {
      constructor(parser2) {
        let data = defineLanguageFacet(parser2.languageData);
        let p = fullParser(parser2), self2;
        let impl = new class extends Parser {
          createParse(input2, fragments, ranges) {
            return new Parse(self2, input2, fragments, ranges);
          }
        }();
        super(data, impl, [], parser2.name);
        this.topNode = docID(data, this);
        self2 = this;
        this.streamParser = p;
        this.stateAfter = new NodeProp({ perNode: true });
        this.tokenTable = parser2.tokenTable ? new TokenTable$1(p.tokenTable) : defaultTokenTable;
      }
      /**
      Define a stream language.
      */
      static define(spec) {
        return new StreamLanguage(spec);
      }
      /**
      @internal
      */
      getIndent(cx) {
        let from = void 0;
        let { overrideIndentation } = cx.options;
        if (overrideIndentation) {
          from = IndentedFrom.get(cx.state);
          if (from != null && from < cx.pos - 1e4)
            from = void 0;
        }
        let start = findState(this, cx.node.tree, cx.node.from, cx.node.from, from !== null && from !== void 0 ? from : cx.pos), statePos, state;
        if (start) {
          state = start.state;
          statePos = start.pos + 1;
        } else {
          state = this.streamParser.startState(cx.unit);
          statePos = cx.node.from;
        }
        if (cx.pos - statePos > 1e4)
          return null;
        while (statePos < cx.pos) {
          let line3 = cx.state.doc.lineAt(statePos), end = Math.min(cx.pos, line3.to);
          if (line3.length) {
            let indentation = overrideIndentation ? overrideIndentation(line3.from) : -1;
            let stream = new StringStream(line3.text, cx.state.tabSize, cx.unit, indentation < 0 ? void 0 : indentation);
            while (stream.pos < end - line3.from)
              readToken(this.streamParser.token, stream, state);
          } else {
            this.streamParser.blankLine(state, cx.unit);
          }
          if (end == cx.pos)
            break;
          statePos = line3.to + 1;
        }
        let line2 = cx.lineAt(cx.pos);
        if (overrideIndentation && from == null)
          IndentedFrom.set(cx.state, line2.from);
        return this.streamParser.indent(state, /^\s*(.*)/.exec(line2.text)[1], cx);
      }
      get allowsNesting() {
        return false;
      }
    }
    function findState(lang, tree, off, startPos, before) {
      let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);
      if (state)
        return { state: lang.streamParser.copyState(state), pos: off + tree.length };
      for (let i2 = tree.children.length - 1; i2 >= 0; i2--) {
        let child = tree.children[i2], pos2 = off + tree.positions[i2];
        let found = child instanceof Tree && pos2 < before && findState(lang, child, pos2, startPos, before);
        if (found)
          return found;
      }
      return null;
    }
    function cutTree(lang, tree, from, to2, inside2) {
      if (inside2 && from <= 0 && to2 >= tree.length)
        return tree;
      if (!inside2 && from == 0 && tree.type == lang.topNode)
        inside2 = true;
      for (let i2 = tree.children.length - 1; i2 >= 0; i2--) {
        let pos2 = tree.positions[i2], child = tree.children[i2], inner;
        if (pos2 < to2 && child instanceof Tree) {
          if (!(inner = cutTree(lang, child, from - pos2, to2 - pos2, inside2)))
            break;
          return !inside2 ? inner : new Tree(tree.type, tree.children.slice(0, i2).concat(inner), tree.positions.slice(0, i2 + 1), pos2 + inner.length);
        }
      }
      return null;
    }
    function findStartInFragments(lang, fragments, startPos, endPos, editorState) {
      for (let f of fragments) {
        let from = f.from + (f.openStart ? 25 : 0), to2 = f.to - (f.openEnd ? 25 : 0);
        let found = from <= startPos && to2 > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to2), tree;
        if (found && found.pos <= endPos && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, false)))
          return { state: found.state, tree };
      }
      return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty };
    }
    class Parse {
      constructor(lang, input2, fragments, ranges) {
        this.lang = lang;
        this.input = input2;
        this.fragments = fragments;
        this.ranges = ranges;
        this.stoppedAt = null;
        this.chunks = [];
        this.chunkPos = [];
        this.chunk = [];
        this.chunkReused = void 0;
        this.rangeIndex = 0;
        this.to = ranges[ranges.length - 1].to;
        let context = ParseContext.get(), from = ranges[0].from;
        let { state, tree } = findStartInFragments(lang, fragments, from, this.to, context === null || context === void 0 ? void 0 : context.state);
        this.state = state;
        this.parsedPos = this.chunkStart = from + tree.length;
        for (let i2 = 0; i2 < tree.children.length; i2++) {
          this.chunks.push(tree.children[i2]);
          this.chunkPos.push(tree.positions[i2]);
        }
        if (context && this.parsedPos < context.viewport.from - 1e5 && ranges.some((r2) => r2.from <= context.viewport.from && r2.to >= context.viewport.from)) {
          this.state = this.lang.streamParser.startState(getIndentUnit(context.state));
          context.skipUntilInView(this.parsedPos, context.viewport.from);
          this.parsedPos = context.viewport.from;
        }
        this.moveRangeIndex();
      }
      advance() {
        let context = ParseContext.get();
        let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);
        let end = Math.min(
          parseEnd,
          this.chunkStart + 2048
          /* C.ChunkSize */
        );
        if (context)
          end = Math.min(end, context.viewport.to);
        while (this.parsedPos < end)
          this.parseLine(context);
        if (this.chunkStart < this.parsedPos)
          this.finishChunk();
        if (this.parsedPos >= parseEnd)
          return this.finish();
        if (context && this.parsedPos >= context.viewport.to) {
          context.skipUntilInView(this.parsedPos, parseEnd);
          return this.finish();
        }
        return null;
      }
      stopAt(pos2) {
        this.stoppedAt = pos2;
      }
      lineAfter(pos2) {
        let chunk = this.input.chunk(pos2);
        if (!this.input.lineChunks) {
          let eol = chunk.indexOf("\n");
          if (eol > -1)
            chunk = chunk.slice(0, eol);
        } else if (chunk == "\n") {
          chunk = "";
        }
        return pos2 + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos2);
      }
      nextLine() {
        let from = this.parsedPos, line2 = this.lineAfter(from), end = from + line2.length;
        for (let index2 = this.rangeIndex; ; ) {
          let rangeEnd2 = this.ranges[index2].to;
          if (rangeEnd2 >= end)
            break;
          line2 = line2.slice(0, rangeEnd2 - (end - line2.length));
          index2++;
          if (index2 == this.ranges.length)
            break;
          let rangeStart = this.ranges[index2].from;
          let after = this.lineAfter(rangeStart);
          line2 += after;
          end = rangeStart + after.length;
        }
        return { line: line2, end };
      }
      skipGapsTo(pos2, offset, side) {
        for (; ; ) {
          let end = this.ranges[this.rangeIndex].to, offPos = pos2 + offset;
          if (side > 0 ? end > offPos : end >= offPos)
            break;
          let start = this.ranges[++this.rangeIndex].from;
          offset += start - end;
        }
        return offset;
      }
      moveRangeIndex() {
        while (this.ranges[this.rangeIndex].to < this.parsedPos)
          this.rangeIndex++;
      }
      emitToken(id, from, to2, offset) {
        let size = 4;
        if (this.ranges.length > 1) {
          offset = this.skipGapsTo(from, offset, 1);
          from += offset;
          let len0 = this.chunk.length;
          offset = this.skipGapsTo(to2, offset, -1);
          to2 += offset;
          size += this.chunk.length - len0;
        }
        let last = this.chunk.length - 4;
        if (this.lang.streamParser.mergeTokens && size == 4 && last >= 0 && this.chunk[last] == id && this.chunk[last + 2] == from)
          this.chunk[last + 2] = to2;
        else
          this.chunk.push(id, from, to2, size);
        return offset;
      }
      parseLine(context) {
        let { line: line2, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
        let stream = new StringStream(line2, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2);
        if (stream.eol()) {
          streamParser.blankLine(this.state, stream.indentUnit);
        } else {
          while (!stream.eol()) {
            let token2 = readToken(streamParser.token, stream, this.state);
            if (token2)
              offset = this.emitToken(this.lang.tokenTable.resolve(token2), this.parsedPos + stream.start, this.parsedPos + stream.pos, offset);
            if (stream.start > 1e4)
              break;
          }
        }
        this.parsedPos = end;
        this.moveRangeIndex();
        if (this.parsedPos < this.to)
          this.parsedPos++;
      }
      finishChunk() {
        let tree = Tree.build({
          buffer: this.chunk,
          start: this.chunkStart,
          length: this.parsedPos - this.chunkStart,
          nodeSet,
          topID: 0,
          maxBufferLength: 2048,
          reused: this.chunkReused
        });
        tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]);
        this.chunks.push(tree);
        this.chunkPos.push(this.chunkStart - this.ranges[0].from);
        this.chunk = [];
        this.chunkReused = void 0;
        this.chunkStart = this.parsedPos;
      }
      finish() {
        return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance();
      }
    }
    function readToken(token2, stream, state) {
      stream.start = stream.pos;
      for (let i2 = 0; i2 < 10; i2++) {
        let result2 = token2(stream, state);
        if (stream.pos > stream.start)
          return result2;
      }
      throw new Error("Stream parser failed to advance stream.");
    }
    const noTokens = /* @__PURE__ */ Object.create(null);
    const typeArray = [NodeType.none];
    const nodeSet = /* @__PURE__ */ new NodeSet(typeArray);
    const warned = [];
    const byTag = /* @__PURE__ */ Object.create(null);
    const defaultTable = /* @__PURE__ */ Object.create(null);
    for (let [legacyName, name2] of [
      ["variable", "variableName"],
      ["variable-2", "variableName.special"],
      ["string-2", "string.special"],
      ["def", "variableName.definition"],
      ["tag", "tagName"],
      ["attribute", "attributeName"],
      ["type", "typeName"],
      ["builtin", "variableName.standard"],
      ["qualifier", "modifier"],
      ["error", "invalid"],
      ["header", "heading"],
      ["property", "propertyName"]
    ])
      defaultTable[legacyName] = /* @__PURE__ */ createTokenType(noTokens, name2);
    let TokenTable$1 = class TokenTable {
      constructor(extra) {
        this.extra = extra;
        this.table = Object.assign(/* @__PURE__ */ Object.create(null), defaultTable);
      }
      resolve(tag) {
        return !tag ? 0 : this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag));
      }
    };
    const defaultTokenTable = /* @__PURE__ */ new TokenTable$1(noTokens);
    function warnForPart(part, msg) {
      if (warned.indexOf(part) > -1)
        return;
      warned.push(part);
      console.warn(msg);
    }
    function createTokenType(extra, tagStr) {
      let tags$1 = [];
      for (let name3 of tagStr.split(" ")) {
        let found = [];
        for (let part of name3.split(".")) {
          let value2 = extra[part] || tags[part];
          if (!value2) {
            warnForPart(part, `Unknown highlighting tag ${part}`);
          } else if (typeof value2 == "function") {
            if (!found.length)
              warnForPart(part, `Modifier ${part} used at start of tag`);
            else
              found = found.map(value2);
          } else {
            if (found.length)
              warnForPart(part, `Tag ${part} used as modifier`);
            else
              found = Array.isArray(value2) ? value2 : [value2];
          }
        }
        for (let tag of found)
          tags$1.push(tag);
      }
      if (!tags$1.length)
        return 0;
      let name2 = tagStr.replace(/ /g, "_"), key2 = name2 + " " + tags$1.map((t2) => t2.id);
      let known = byTag[key2];
      if (known)
        return known.id;
      let type = byTag[key2] = NodeType.define({
        id: typeArray.length,
        name: name2,
        props: [styleTags({ [name2]: tags$1 })]
      });
      typeArray.push(type);
      return type.id;
    }
    function docID(data, lang) {
      let type = NodeType.define({ id: typeArray.length, name: "Document", props: [
        languageDataProp.add(() => data),
        indentNodeProp.add(() => (cx) => lang.getIndent(cx))
      ], top: true });
      typeArray.push(type);
      return type;
    }
    ({
      rtl: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "rtl" }, bidiIsolate: Direction.RTL }),
      ltr: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "ltr" }, bidiIsolate: Direction.LTR })
    });
    class CompletionContext {
      /**
      Create a new completion context. (Mostly useful for testing
      completion sources—in the editor, the extension will create
      these for you.)
      */
      constructor(state, pos2, explicit, view) {
        this.state = state;
        this.pos = pos2;
        this.explicit = explicit;
        this.view = view;
        this.abortListeners = [];
        this.abortOnDocChange = false;
      }
      /**
      Get the extent, content, and (if there is a token) type of the
      token before `this.pos`.
      */
      tokenBefore(types2) {
        let token2 = syntaxTree(this.state).resolveInner(this.pos, -1);
        while (token2 && types2.indexOf(token2.name) < 0)
          token2 = token2.parent;
        return token2 ? {
          from: token2.from,
          to: this.pos,
          text: this.state.sliceDoc(token2.from, this.pos),
          type: token2.type
        } : null;
      }
      /**
      Get the match of the given expression directly before the
      cursor.
      */
      matchBefore(expr) {
        let line2 = this.state.doc.lineAt(this.pos);
        let start = Math.max(line2.from, this.pos - 250);
        let str2 = line2.text.slice(start - line2.from, this.pos - line2.from);
        let found = str2.search(ensureAnchor(expr, false));
        return found < 0 ? null : { from: start + found, to: this.pos, text: str2.slice(found) };
      }
      /**
      Yields true when the query has been aborted. Can be useful in
      asynchronous queries to avoid doing work that will be ignored.
      */
      get aborted() {
        return this.abortListeners == null;
      }
      /**
      Allows you to register abort handlers, which will be called when
      the query is
      [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
      
      By default, running queries will not be aborted for regular
      typing or backspacing, on the assumption that they are likely to
      return a result with a
      [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
      allows the result to be used after all. Passing `onDocChange:
      true` will cause this query to be aborted for any document
      change.
      */
      addEventListener(type, listener, options2) {
        if (type == "abort" && this.abortListeners) {
          this.abortListeners.push(listener);
          if (options2 && options2.onDocChange)
            this.abortOnDocChange = true;
        }
      }
    }
    function toSet(chars) {
      let flat = Object.keys(chars).join("");
      let words = /\w/.test(flat);
      if (words)
        flat = flat.replace(/\w/g, "");
      return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
    }
    function prefixMatch(options2) {
      let first2 = /* @__PURE__ */ Object.create(null), rest = /* @__PURE__ */ Object.create(null);
      for (let { label: label2 } of options2) {
        first2[label2[0]] = true;
        for (let i2 = 1; i2 < label2.length; i2++)
          rest[label2[i2]] = true;
      }
      let source2 = toSet(first2) + toSet(rest) + "*$";
      return [new RegExp("^" + source2), new RegExp(source2)];
    }
    function completeFromList(list2) {
      let options2 = list2.map((o) => typeof o == "string" ? { label: o } : o);
      let [validFor, match] = options2.every((o) => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options2);
      return (context) => {
        let token2 = context.matchBefore(match);
        return token2 || context.explicit ? { from: token2 ? token2.from : context.pos, options: options2, validFor } : null;
      };
    }
    class Option {
      constructor(completion, source2, match, score2) {
        this.completion = completion;
        this.source = source2;
        this.match = match;
        this.score = score2;
      }
    }
    function cur(state) {
      return state.selection.main.from;
    }
    function ensureAnchor(expr, start) {
      var _a2;
      let { source: source2 } = expr;
      let addStart = start && source2[0] != "^", addEnd = source2[source2.length - 1] != "$";
      if (!addStart && !addEnd)
        return expr;
      return new RegExp(`${addStart ? "^" : ""}(?:${source2})${addEnd ? "$" : ""}`, (_a2 = expr.flags) !== null && _a2 !== void 0 ? _a2 : expr.ignoreCase ? "i" : "");
    }
    const pickedCompletion = /* @__PURE__ */ Annotation.define();
    function insertCompletionText(state, text2, from, to2) {
      let { main } = state.selection, fromOff = from - main.from, toOff = to2 - main.from;
      return Object.assign(Object.assign({}, state.changeByRange((range) => {
        if (range != main && from != to2 && state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to2))
          return { range };
        let lines = state.toText(text2);
        return {
          changes: { from: range.from + fromOff, to: to2 == main.from ? range.to : range.from + toOff, insert: lines },
          range: EditorSelection.cursor(range.from + fromOff + lines.length)
        };
      })), { scrollIntoView: true, userEvent: "input.complete" });
    }
    const SourceCache = /* @__PURE__ */ new WeakMap();
    function asSource(source2) {
      if (!Array.isArray(source2))
        return source2;
      let known = SourceCache.get(source2);
      if (!known)
        SourceCache.set(source2, known = completeFromList(source2));
      return known;
    }
    const startCompletionEffect = /* @__PURE__ */ StateEffect.define();
    const closeCompletionEffect = /* @__PURE__ */ StateEffect.define();
    class FuzzyMatcher {
      constructor(pattern) {
        this.pattern = pattern;
        this.chars = [];
        this.folded = [];
        this.any = [];
        this.precise = [];
        this.byWord = [];
        this.score = 0;
        this.matched = [];
        for (let p = 0; p < pattern.length; ) {
          let char = codePointAt(pattern, p), size = codePointSize(char);
          this.chars.push(char);
          let part = pattern.slice(p, p + size), upper = part.toUpperCase();
          this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
          p += size;
        }
        this.astral = pattern.length != this.chars.length;
      }
      ret(score2, matched) {
        this.score = score2;
        this.matched = matched;
        return this;
      }
      // Matches a given word (completion) against the pattern (input).
      // Will return a boolean indicating whether there was a match and,
      // on success, set `this.score` to the score, `this.matched` to an
      // array of `from, to` pairs indicating the matched parts of `word`.
      //
      // The score is a number that is more negative the worse the match
      // is. See `Penalty` above.
      match(word) {
        if (this.pattern.length == 0)
          return this.ret(-100, []);
        if (word.length < this.pattern.length)
          return null;
        let { chars, folded, any, precise, byWord } = this;
        if (chars.length == 1) {
          let first2 = codePointAt(word, 0), firstSize = codePointSize(first2);
          let score2 = firstSize == word.length ? 0 : -100;
          if (first2 == chars[0]) ;
          else if (first2 == folded[0])
            score2 += -200;
          else
            return null;
          return this.ret(score2, [0, firstSize]);
        }
        let direct = word.indexOf(this.pattern);
        if (direct == 0)
          return this.ret(word.length == this.pattern.length ? 0 : -100, [0, this.pattern.length]);
        let len = chars.length, anyTo = 0;
        if (direct < 0) {
          for (let i2 = 0, e = Math.min(word.length, 200); i2 < e && anyTo < len; ) {
            let next = codePointAt(word, i2);
            if (next == chars[anyTo] || next == folded[anyTo])
              any[anyTo++] = i2;
            i2 += codePointSize(next);
          }
          if (anyTo < len)
            return null;
        }
        let preciseTo = 0;
        let byWordTo = 0, byWordFolded = false;
        let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
        let hasLower = /[a-z]/.test(word), wordAdjacent = true;
        for (let i2 = 0, e = Math.min(word.length, 200), prevType = 0; i2 < e && byWordTo < len; ) {
          let next = codePointAt(word, i2);
          if (direct < 0) {
            if (preciseTo < len && next == chars[preciseTo])
              precise[preciseTo++] = i2;
            if (adjacentTo < len) {
              if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
                if (adjacentTo == 0)
                  adjacentStart = i2;
                adjacentEnd = i2 + 1;
                adjacentTo++;
              } else {
                adjacentTo = 0;
              }
            }
          }
          let ch3, type = next < 255 ? next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 : next >= 65 && next <= 90 ? 1 : 0 : (ch3 = fromCodePoint(next)) != ch3.toLowerCase() ? 1 : ch3 != ch3.toUpperCase() ? 2 : 0;
          if (!i2 || type == 1 && hasLower || prevType == 0 && type != 0) {
            if (chars[byWordTo] == next || folded[byWordTo] == next && (byWordFolded = true))
              byWord[byWordTo++] = i2;
            else if (byWord.length)
              wordAdjacent = false;
          }
          prevType = type;
          i2 += codePointSize(next);
        }
        if (byWordTo == len && byWord[0] == 0 && wordAdjacent)
          return this.result(-100 + (byWordFolded ? -200 : 0), byWord, word);
        if (adjacentTo == len && adjacentStart == 0)
          return this.ret(-200 - word.length + (adjacentEnd == word.length ? 0 : -100), [0, adjacentEnd]);
        if (direct > -1)
          return this.ret(-700 - word.length, [direct, direct + this.pattern.length]);
        if (adjacentTo == len)
          return this.ret(-200 + -700 - word.length, [adjacentStart, adjacentEnd]);
        if (byWordTo == len)
          return this.result(-100 + (byWordFolded ? -200 : 0) + -700 + (wordAdjacent ? 0 : -1100), byWord, word);
        return chars.length == 2 ? null : this.result((any[0] ? -700 : 0) + -200 + -1100, any, word);
      }
      result(score2, positions, word) {
        let result2 = [], i2 = 0;
        for (let pos2 of positions) {
          let to2 = pos2 + (this.astral ? codePointSize(codePointAt(word, pos2)) : 1);
          if (i2 && result2[i2 - 1] == pos2)
            result2[i2 - 1] = to2;
          else {
            result2[i2++] = pos2;
            result2[i2++] = to2;
          }
        }
        return this.ret(score2 - word.length, result2);
      }
    }
    class StrictMatcher {
      constructor(pattern) {
        this.pattern = pattern;
        this.matched = [];
        this.score = 0;
        this.folded = pattern.toLowerCase();
      }
      match(word) {
        if (word.length < this.pattern.length)
          return null;
        let start = word.slice(0, this.pattern.length);
        let match = start == this.pattern ? 0 : start.toLowerCase() == this.folded ? -200 : null;
        if (match == null)
          return null;
        this.matched = [0, start.length];
        this.score = match + (word.length == this.pattern.length ? 0 : -100);
        return this;
      }
    }
    const completionConfig = /* @__PURE__ */ Facet.define({
      combine(configs) {
        return combineConfig(configs, {
          activateOnTyping: true,
          activateOnCompletion: () => false,
          activateOnTypingDelay: 100,
          selectOnOpen: true,
          override: null,
          closeOnBlur: true,
          maxRenderedOptions: 100,
          defaultKeymap: true,
          tooltipClass: () => "",
          optionClass: () => "",
          aboveCursor: false,
          icons: true,
          addToOptions: [],
          positionInfo: defaultPositionInfo,
          filterStrict: false,
          compareCompletions: (a, b) => a.label.localeCompare(b.label),
          interactionDelay: 75,
          updateSyncTime: 100
        }, {
          defaultKeymap: (a, b) => a && b,
          closeOnBlur: (a, b) => a && b,
          icons: (a, b) => a && b,
          tooltipClass: (a, b) => (c2) => joinClass(a(c2), b(c2)),
          optionClass: (a, b) => (c2) => joinClass(a(c2), b(c2)),
          addToOptions: (a, b) => a.concat(b),
          filterStrict: (a, b) => a || b
        });
      }
    });
    function joinClass(a, b) {
      return a ? b ? a + " " + b : a : b;
    }
    function defaultPositionInfo(view, list2, option, info, space, tooltip) {
      let rtl = view.textDirection == Direction.RTL, left = rtl, narrow = false;
      let side = "top", offset, maxWidth;
      let spaceLeft = list2.left - space.left, spaceRight = space.right - list2.right;
      let infoWidth = info.right - info.left, infoHeight = info.bottom - info.top;
      if (left && spaceLeft < Math.min(infoWidth, spaceRight))
        left = false;
      else if (!left && spaceRight < Math.min(infoWidth, spaceLeft))
        left = true;
      if (infoWidth <= (left ? spaceLeft : spaceRight)) {
        offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list2.top;
        maxWidth = Math.min(400, left ? spaceLeft : spaceRight);
      } else {
        narrow = true;
        maxWidth = Math.min(
          400,
          (rtl ? list2.right : space.right - list2.left) - 30
          /* Info.Margin */
        );
        let spaceBelow = space.bottom - list2.bottom;
        if (spaceBelow >= infoHeight || spaceBelow > list2.top) {
          offset = option.bottom - list2.top;
        } else {
          side = "bottom";
          offset = list2.bottom - option.top;
        }
      }
      let scaleY = (list2.bottom - list2.top) / tooltip.offsetHeight;
      let scaleX = (list2.right - list2.left) / tooltip.offsetWidth;
      return {
        style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
        class: "cm-completionInfo-" + (narrow ? rtl ? "left-narrow" : "right-narrow" : left ? "left" : "right")
      };
    }
    function optionContent(config2) {
      let content2 = config2.addToOptions.slice();
      if (config2.icons)
        content2.push({
          render(completion) {
            let icon = document.createElement("div");
            icon.classList.add("cm-completionIcon");
            if (completion.type)
              icon.classList.add(...completion.type.split(/\s+/g).map((cls) => "cm-completionIcon-" + cls));
            icon.setAttribute("aria-hidden", "true");
            return icon;
          },
          position: 20
        });
      content2.push({
        render(completion, _s, _v, match) {
          let labelElt = document.createElement("span");
          labelElt.className = "cm-completionLabel";
          let label2 = completion.displayLabel || completion.label, off = 0;
          for (let j2 = 0; j2 < match.length; ) {
            let from = match[j2++], to2 = match[j2++];
            if (from > off)
              labelElt.appendChild(document.createTextNode(label2.slice(off, from)));
            let span = labelElt.appendChild(document.createElement("span"));
            span.appendChild(document.createTextNode(label2.slice(from, to2)));
            span.className = "cm-completionMatchedText";
            off = to2;
          }
          if (off < label2.length)
            labelElt.appendChild(document.createTextNode(label2.slice(off)));
          return labelElt;
        },
        position: 50
      }, {
        render(completion) {
          if (!completion.detail)
            return null;
          let detailElt = document.createElement("span");
          detailElt.className = "cm-completionDetail";
          detailElt.textContent = completion.detail;
          return detailElt;
        },
        position: 80
      });
      return content2.sort((a, b) => a.position - b.position).map((a) => a.render);
    }
    function rangeAroundSelected(total, selected2, max2) {
      if (total <= max2)
        return { from: 0, to: total };
      if (selected2 < 0)
        selected2 = 0;
      if (selected2 <= total >> 1) {
        let off2 = Math.floor(selected2 / max2);
        return { from: off2 * max2, to: (off2 + 1) * max2 };
      }
      let off = Math.floor((total - selected2) / max2);
      return { from: total - (off + 1) * max2, to: total - off * max2 };
    }
    class CompletionTooltip {
      constructor(view, stateField, applyCompletion2) {
        this.view = view;
        this.stateField = stateField;
        this.applyCompletion = applyCompletion2;
        this.info = null;
        this.infoDestroy = null;
        this.placeInfoReq = {
          read: () => this.measureInfo(),
          write: (pos2) => this.placeInfo(pos2),
          key: this
        };
        this.space = null;
        this.currentClass = "";
        let cState = view.state.field(stateField);
        let { options: options2, selected: selected2 } = cState.open;
        let config2 = view.state.facet(completionConfig);
        this.optionContent = optionContent(config2);
        this.optionClass = config2.optionClass;
        this.tooltipClass = config2.tooltipClass;
        this.range = rangeAroundSelected(options2.length, selected2, config2.maxRenderedOptions);
        this.dom = document.createElement("div");
        this.dom.className = "cm-tooltip-autocomplete";
        this.updateTooltipClass(view.state);
        this.dom.addEventListener("mousedown", (e) => {
          let { options: options3 } = view.state.field(stateField).open;
          for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
            if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options3.length) {
              this.applyCompletion(view, options3[+match[1]]);
              e.preventDefault();
              return;
            }
          }
        });
        this.dom.addEventListener("focusout", (e) => {
          let state = view.state.field(this.stateField, false);
          if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur && e.relatedTarget != view.contentDOM)
            view.dispatch({ effects: closeCompletionEffect.of(null) });
        });
        this.showOptions(options2, cState.id);
      }
      mount() {
        this.updateSel();
      }
      showOptions(options2, id) {
        if (this.list)
          this.list.remove();
        this.list = this.dom.appendChild(this.createListBox(options2, id, this.range));
        this.list.addEventListener("scroll", () => {
          if (this.info)
            this.view.requestMeasure(this.placeInfoReq);
        });
      }
      update(update) {
        var _a2;
        let cState = update.state.field(this.stateField);
        let prevState = update.startState.field(this.stateField);
        this.updateTooltipClass(update.state);
        if (cState != prevState) {
          let { options: options2, selected: selected2, disabled } = cState.open;
          if (!prevState.open || prevState.open.options != options2) {
            this.range = rangeAroundSelected(options2.length, selected2, update.state.facet(completionConfig).maxRenderedOptions);
            this.showOptions(options2, cState.id);
          }
          this.updateSel();
          if (disabled != ((_a2 = prevState.open) === null || _a2 === void 0 ? void 0 : _a2.disabled))
            this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
        }
      }
      updateTooltipClass(state) {
        let cls = this.tooltipClass(state);
        if (cls != this.currentClass) {
          for (let c2 of this.currentClass.split(" "))
            if (c2)
              this.dom.classList.remove(c2);
          for (let c2 of cls.split(" "))
            if (c2)
              this.dom.classList.add(c2);
          this.currentClass = cls;
        }
      }
      positioned(space) {
        this.space = space;
        if (this.info)
          this.view.requestMeasure(this.placeInfoReq);
      }
      updateSel() {
        let cState = this.view.state.field(this.stateField), open = cState.open;
        if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
          this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
          this.showOptions(open.options, cState.id);
        }
        if (this.updateSelectedOption(open.selected)) {
          this.destroyInfo();
          let { completion } = open.options[open.selected];
          let { info } = completion;
          if (!info)
            return;
          let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
          if (!infoResult)
            return;
          if ("then" in infoResult) {
            infoResult.then((obj) => {
              if (obj && this.view.state.field(this.stateField, false) == cState)
                this.addInfoPane(obj, completion);
            }).catch((e) => logException(this.view.state, e, "completion info"));
          } else {
            this.addInfoPane(infoResult, completion);
          }
        }
      }
      addInfoPane(content2, completion) {
        this.destroyInfo();
        let wrap2 = this.info = document.createElement("div");
        wrap2.className = "cm-tooltip cm-completionInfo";
        if (content2.nodeType != null) {
          wrap2.appendChild(content2);
          this.infoDestroy = null;
        } else {
          let { dom, destroy } = content2;
          wrap2.appendChild(dom);
          this.infoDestroy = destroy || null;
        }
        this.dom.appendChild(wrap2);
        this.view.requestMeasure(this.placeInfoReq);
      }
      updateSelectedOption(selected2) {
        let set = null;
        for (let opt = this.list.firstChild, i2 = this.range.from; opt; opt = opt.nextSibling, i2++) {
          if (opt.nodeName != "LI" || !opt.id) {
            i2--;
          } else if (i2 == selected2) {
            if (!opt.hasAttribute("aria-selected")) {
              opt.setAttribute("aria-selected", "true");
              set = opt;
            }
          } else {
            if (opt.hasAttribute("aria-selected"))
              opt.removeAttribute("aria-selected");
          }
        }
        if (set)
          scrollIntoView(this.list, set);
        return set;
      }
      measureInfo() {
        let sel = this.dom.querySelector("[aria-selected]");
        if (!sel || !this.info)
          return null;
        let listRect = this.dom.getBoundingClientRect();
        let infoRect = this.info.getBoundingClientRect();
        let selRect = sel.getBoundingClientRect();
        let space = this.space;
        if (!space) {
          let docElt = this.dom.ownerDocument.documentElement;
          space = { left: 0, top: 0, right: docElt.clientWidth, bottom: docElt.clientHeight };
        }
        if (selRect.top > Math.min(space.bottom, listRect.bottom) - 10 || selRect.bottom < Math.max(space.top, listRect.top) + 10)
          return null;
        return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space, this.dom);
      }
      placeInfo(pos2) {
        if (this.info) {
          if (pos2) {
            if (pos2.style)
              this.info.style.cssText = pos2.style;
            this.info.className = "cm-tooltip cm-completionInfo " + (pos2.class || "");
          } else {
            this.info.style.cssText = "top: -1e6px";
          }
        }
      }
      createListBox(options2, id, range) {
        const ul = document.createElement("ul");
        ul.id = id;
        ul.setAttribute("role", "listbox");
        ul.setAttribute("aria-expanded", "true");
        ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
        ul.addEventListener("mousedown", (e) => {
          if (e.target == ul)
            e.preventDefault();
        });
        let curSection = null;
        for (let i2 = range.from; i2 < range.to; i2++) {
          let { completion, match } = options2[i2], { section: section2 } = completion;
          if (section2) {
            let name2 = typeof section2 == "string" ? section2 : section2.name;
            if (name2 != curSection && (i2 > range.from || range.from == 0)) {
              curSection = name2;
              if (typeof section2 != "string" && section2.header) {
                ul.appendChild(section2.header(section2));
              } else {
                let header2 = ul.appendChild(document.createElement("completion-section"));
                header2.textContent = name2;
              }
            }
          }
          const li = ul.appendChild(document.createElement("li"));
          li.id = id + "-" + i2;
          li.setAttribute("role", "option");
          let cls = this.optionClass(completion);
          if (cls)
            li.className = cls;
          for (let source2 of this.optionContent) {
            let node2 = source2(completion, this.view.state, this.view, match);
            if (node2)
              li.appendChild(node2);
          }
        }
        if (range.from)
          ul.classList.add("cm-completionListIncompleteTop");
        if (range.to < options2.length)
          ul.classList.add("cm-completionListIncompleteBottom");
        return ul;
      }
      destroyInfo() {
        if (this.info) {
          if (this.infoDestroy)
            this.infoDestroy();
          this.info.remove();
          this.info = null;
        }
      }
      destroy() {
        this.destroyInfo();
      }
    }
    function completionTooltip(stateField, applyCompletion2) {
      return (view) => new CompletionTooltip(view, stateField, applyCompletion2);
    }
    function scrollIntoView(container2, element) {
      let parent = container2.getBoundingClientRect();
      let self2 = element.getBoundingClientRect();
      let scaleY = parent.height / container2.offsetHeight;
      if (self2.top < parent.top)
        container2.scrollTop -= (parent.top - self2.top) / scaleY;
      else if (self2.bottom > parent.bottom)
        container2.scrollTop += (self2.bottom - parent.bottom) / scaleY;
    }
    function score$1(option) {
      return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + (option.type ? 1 : 0);
    }
    function sortOptions(active2, state) {
      let options2 = [];
      let sections = null;
      let addOption = (option) => {
        options2.push(option);
        let { section: section2 } = option.completion;
        if (section2) {
          if (!sections)
            sections = [];
          let name2 = typeof section2 == "string" ? section2 : section2.name;
          if (!sections.some((s) => s.name == name2))
            sections.push(typeof section2 == "string" ? { name: name2 } : section2);
        }
      };
      let conf = state.facet(completionConfig);
      for (let a of active2)
        if (a.hasResult()) {
          let getMatch = a.result.getMatch;
          if (a.result.filter === false) {
            for (let option of a.result.options) {
              addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options2.length));
            }
          } else {
            let pattern = state.sliceDoc(a.from, a.to), match;
            let matcher = conf.filterStrict ? new StrictMatcher(pattern) : new FuzzyMatcher(pattern);
            for (let option of a.result.options)
              if (match = matcher.match(option.label)) {
                let matched = !option.displayLabel ? match.matched : getMatch ? getMatch(option, match.matched) : [];
                addOption(new Option(option, a.source, matched, match.score + (option.boost || 0)));
              }
          }
        }
      if (sections) {
        let sectionOrder = /* @__PURE__ */ Object.create(null), pos2 = 0;
        let cmp = (a, b) => {
          var _a2, _b2;
          return ((_a2 = a.rank) !== null && _a2 !== void 0 ? _a2 : 1e9) - ((_b2 = b.rank) !== null && _b2 !== void 0 ? _b2 : 1e9) || (a.name < b.name ? -1 : 1);
        };
        for (let s of sections.sort(cmp)) {
          pos2 -= 1e5;
          sectionOrder[s.name] = pos2;
        }
        for (let option of options2) {
          let { section: section2 } = option.completion;
          if (section2)
            option.score += sectionOrder[typeof section2 == "string" ? section2 : section2.name];
        }
      }
      let result2 = [], prev = null;
      let compare2 = conf.compareCompletions;
      for (let opt of options2.sort((a, b) => b.score - a.score || compare2(a.completion, b.completion))) {
        let cur2 = opt.completion;
        if (!prev || prev.label != cur2.label || prev.detail != cur2.detail || prev.type != null && cur2.type != null && prev.type != cur2.type || prev.apply != cur2.apply || prev.boost != cur2.boost)
          result2.push(opt);
        else if (score$1(opt.completion) > score$1(prev))
          result2[result2.length - 1] = opt;
        prev = opt.completion;
      }
      return result2;
    }
    class CompletionDialog {
      constructor(options2, attrs, tooltip, timestamp, selected2, disabled) {
        this.options = options2;
        this.attrs = attrs;
        this.tooltip = tooltip;
        this.timestamp = timestamp;
        this.selected = selected2;
        this.disabled = disabled;
      }
      setSelected(selected2, id) {
        return selected2 == this.selected || selected2 >= this.options.length ? this : new CompletionDialog(this.options, makeAttrs(id, selected2), this.tooltip, this.timestamp, selected2, this.disabled);
      }
      static build(active2, state, id, prev, conf, didSetActive) {
        if (prev && !didSetActive && active2.some((s) => s.isPending))
          return prev.setDisabled();
        let options2 = sortOptions(active2, state);
        if (!options2.length)
          return prev && active2.some((a) => a.isPending) ? prev.setDisabled() : null;
        let selected2 = state.facet(completionConfig).selectOnOpen ? 0 : -1;
        if (prev && prev.selected != selected2 && prev.selected != -1) {
          let selectedValue = prev.options[prev.selected].completion;
          for (let i2 = 0; i2 < options2.length; i2++)
            if (options2[i2].completion == selectedValue) {
              selected2 = i2;
              break;
            }
        }
        return new CompletionDialog(options2, makeAttrs(id, selected2), {
          pos: active2.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
          create: createTooltip,
          above: conf.aboveCursor
        }, prev ? prev.timestamp : Date.now(), selected2, false);
      }
      map(changes) {
        return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected, this.disabled);
      }
      setDisabled() {
        return new CompletionDialog(this.options, this.attrs, this.tooltip, this.timestamp, this.selected, true);
      }
    }
    class CompletionState {
      constructor(active2, id, open) {
        this.active = active2;
        this.id = id;
        this.open = open;
      }
      static start() {
        return new CompletionState(none$1, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
      }
      update(tr2) {
        let { state } = tr2, conf = state.facet(completionConfig);
        let sources = conf.override || state.languageDataAt("autocomplete", cur(state)).map(asSource);
        let active2 = sources.map((source2) => {
          let value2 = this.active.find((s) => s.source == source2) || new ActiveSource(
            source2,
            this.active.some(
              (a) => a.state != 0
              /* State.Inactive */
            ) ? 1 : 0
            /* State.Inactive */
          );
          return value2.update(tr2, conf);
        });
        if (active2.length == this.active.length && active2.every((a, i2) => a == this.active[i2]))
          active2 = this.active;
        let open = this.open, didSet = tr2.effects.some((e) => e.is(setActiveEffect));
        if (open && tr2.docChanged)
          open = open.map(tr2.changes);
        if (tr2.selection || active2.some((a) => a.hasResult() && tr2.changes.touchesRange(a.from, a.to)) || !sameResults(active2, this.active) || didSet)
          open = CompletionDialog.build(active2, state, this.id, open, conf, didSet);
        else if (open && open.disabled && !active2.some((a) => a.isPending))
          open = null;
        if (!open && active2.every((a) => !a.isPending) && active2.some((a) => a.hasResult()))
          active2 = active2.map((a) => a.hasResult() ? new ActiveSource(
            a.source,
            0
            /* State.Inactive */
          ) : a);
        for (let effect of tr2.effects)
          if (effect.is(setSelectedEffect))
            open = open && open.setSelected(effect.value, this.id);
        return active2 == this.active && open == this.open ? this : new CompletionState(active2, this.id, open);
      }
      get tooltip() {
        return this.open ? this.open.tooltip : null;
      }
      get attrs() {
        return this.open ? this.open.attrs : this.active.length ? baseAttrs : noAttrs;
      }
    }
    function sameResults(a, b) {
      if (a == b)
        return true;
      for (let iA = 0, iB = 0; ; ) {
        while (iA < a.length && !a[iA].hasResult())
          iA++;
        while (iB < b.length && !b[iB].hasResult())
          iB++;
        let endA = iA == a.length, endB = iB == b.length;
        if (endA || endB)
          return endA == endB;
        if (a[iA++].result != b[iB++].result)
          return false;
      }
    }
    const baseAttrs = {
      "aria-autocomplete": "list"
    };
    const noAttrs = {};
    function makeAttrs(id, selected2) {
      let result2 = {
        "aria-autocomplete": "list",
        "aria-haspopup": "listbox",
        "aria-controls": id
      };
      if (selected2 > -1)
        result2["aria-activedescendant"] = id + "-" + selected2;
      return result2;
    }
    const none$1 = [];
    function getUpdateType(tr2, conf) {
      if (tr2.isUserEvent("input.complete")) {
        let completion = tr2.annotation(pickedCompletion);
        if (completion && conf.activateOnCompletion(completion))
          return 4 | 8;
      }
      let typing = tr2.isUserEvent("input.type");
      return typing && conf.activateOnTyping ? 4 | 1 : typing ? 1 : tr2.isUserEvent("delete.backward") ? 2 : tr2.selection ? 8 : tr2.docChanged ? 16 : 0;
    }
    class ActiveSource {
      constructor(source2, state, explicit = false) {
        this.source = source2;
        this.state = state;
        this.explicit = explicit;
      }
      hasResult() {
        return false;
      }
      get isPending() {
        return this.state == 1;
      }
      update(tr2, conf) {
        let type = getUpdateType(tr2, conf), value2 = this;
        if (type & 8 || type & 16 && this.touches(tr2))
          value2 = new ActiveSource(
            value2.source,
            0
            /* State.Inactive */
          );
        if (type & 4 && value2.state == 0)
          value2 = new ActiveSource(
            this.source,
            1
            /* State.Pending */
          );
        value2 = value2.updateFor(tr2, type);
        for (let effect of tr2.effects) {
          if (effect.is(startCompletionEffect))
            value2 = new ActiveSource(value2.source, 1, effect.value);
          else if (effect.is(closeCompletionEffect))
            value2 = new ActiveSource(
              value2.source,
              0
              /* State.Inactive */
            );
          else if (effect.is(setActiveEffect)) {
            for (let active2 of effect.value)
              if (active2.source == value2.source)
                value2 = active2;
          }
        }
        return value2;
      }
      updateFor(tr2, type) {
        return this.map(tr2.changes);
      }
      map(changes) {
        return this;
      }
      touches(tr2) {
        return tr2.changes.touchesRange(cur(tr2.state));
      }
    }
    class ActiveResult extends ActiveSource {
      constructor(source2, explicit, limit, result2, from, to2) {
        super(source2, 3, explicit);
        this.limit = limit;
        this.result = result2;
        this.from = from;
        this.to = to2;
      }
      hasResult() {
        return true;
      }
      updateFor(tr2, type) {
        var _a2;
        if (!(type & 3))
          return this.map(tr2.changes);
        let result2 = this.result;
        if (result2.map && !tr2.changes.empty)
          result2 = result2.map(result2, tr2.changes);
        let from = tr2.changes.mapPos(this.from), to2 = tr2.changes.mapPos(this.to, 1);
        let pos2 = cur(tr2.state);
        if (pos2 > to2 || !result2 || type & 2 && (cur(tr2.startState) == this.from || pos2 < this.limit))
          return new ActiveSource(
            this.source,
            type & 4 ? 1 : 0
            /* State.Inactive */
          );
        let limit = tr2.changes.mapPos(this.limit);
        if (checkValid(result2.validFor, tr2.state, from, to2))
          return new ActiveResult(this.source, this.explicit, limit, result2, from, to2);
        if (result2.update && (result2 = result2.update(result2, from, to2, new CompletionContext(tr2.state, pos2, false))))
          return new ActiveResult(this.source, this.explicit, limit, result2, result2.from, (_a2 = result2.to) !== null && _a2 !== void 0 ? _a2 : cur(tr2.state));
        return new ActiveSource(this.source, 1, this.explicit);
      }
      map(mapping) {
        if (mapping.empty)
          return this;
        let result2 = this.result.map ? this.result.map(this.result, mapping) : this.result;
        if (!result2)
          return new ActiveSource(
            this.source,
            0
            /* State.Inactive */
          );
        return new ActiveResult(this.source, this.explicit, mapping.mapPos(this.limit), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
      }
      touches(tr2) {
        return tr2.changes.touchesRange(this.from, this.to);
      }
    }
    function checkValid(validFor, state, from, to2) {
      if (!validFor)
        return false;
      let text2 = state.sliceDoc(from, to2);
      return typeof validFor == "function" ? validFor(text2, from, to2, state) : ensureAnchor(validFor, true).test(text2);
    }
    const setActiveEffect = /* @__PURE__ */ StateEffect.define({
      map(sources, mapping) {
        return sources.map((s) => s.map(mapping));
      }
    });
    const setSelectedEffect = /* @__PURE__ */ StateEffect.define();
    const completionState = /* @__PURE__ */ StateField.define({
      create() {
        return CompletionState.start();
      },
      update(value2, tr2) {
        return value2.update(tr2);
      },
      provide: (f) => [
        showTooltip.from(f, (val) => val.tooltip),
        EditorView.contentAttributes.from(f, (state) => state.attrs)
      ]
    });
    function applyCompletion(view, option) {
      const apply = option.completion.apply || option.completion.label;
      let result2 = view.state.field(completionState).active.find((a) => a.source == option.source);
      if (!(result2 instanceof ActiveResult))
        return false;
      if (typeof apply == "string")
        view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result2.from, result2.to)), { annotations: pickedCompletion.of(option.completion) }));
      else
        apply(view, option.completion, result2.from, result2.to);
      return true;
    }
    const createTooltip = /* @__PURE__ */ completionTooltip(completionState, applyCompletion);
    function moveCompletionSelection(forward, by = "option") {
      return (view) => {
        let cState = view.state.field(completionState, false);
        if (!cState || !cState.open || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
          return false;
        let step = 1, tooltip;
        if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip)))
          step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / tooltip.dom.querySelector("li").offsetHeight) - 1);
        let { length } = cState.open.options;
        let selected2 = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
        if (selected2 < 0)
          selected2 = by == "page" ? 0 : length - 1;
        else if (selected2 >= length)
          selected2 = by == "page" ? length - 1 : 0;
        view.dispatch({ effects: setSelectedEffect.of(selected2) });
        return true;
      };
    }
    const acceptCompletion = (view) => {
      let cState = view.state.field(completionState, false);
      if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
        return false;
      return applyCompletion(view, cState.open.options[cState.open.selected]);
    };
    const startCompletion = (view) => {
      let cState = view.state.field(completionState, false);
      if (!cState)
        return false;
      view.dispatch({ effects: startCompletionEffect.of(true) });
      return true;
    };
    const closeCompletion = (view) => {
      let cState = view.state.field(completionState, false);
      if (!cState || !cState.active.some(
        (a) => a.state != 0
        /* State.Inactive */
      ))
        return false;
      view.dispatch({ effects: closeCompletionEffect.of(null) });
      return true;
    };
    class RunningQuery {
      constructor(active2, context) {
        this.active = active2;
        this.context = context;
        this.time = Date.now();
        this.updates = [];
        this.done = void 0;
      }
    }
    const MaxUpdateCount = 50, MinAbortTime = 1e3;
    const completionPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
      constructor(view) {
        this.view = view;
        this.debounceUpdate = -1;
        this.running = [];
        this.debounceAccept = -1;
        this.pendingStart = false;
        this.composing = 0;
        for (let active2 of view.state.field(completionState).active)
          if (active2.isPending)
            this.startQuery(active2);
      }
      update(update) {
        let cState = update.state.field(completionState);
        let conf = update.state.facet(completionConfig);
        if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState)
          return;
        let doesReset = update.transactions.some((tr2) => {
          let type = getUpdateType(tr2, conf);
          return type & 8 || (tr2.selection || tr2.docChanged) && !(type & 3);
        });
        for (let i2 = 0; i2 < this.running.length; i2++) {
          let query2 = this.running[i2];
          if (doesReset || query2.context.abortOnDocChange && update.docChanged || query2.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query2.time > MinAbortTime) {
            for (let handler of query2.context.abortListeners) {
              try {
                handler();
              } catch (e) {
                logException(this.view.state, e);
              }
            }
            query2.context.abortListeners = null;
            this.running.splice(i2--, 1);
          } else {
            query2.updates.push(...update.transactions);
          }
        }
        if (this.debounceUpdate > -1)
          clearTimeout(this.debounceUpdate);
        if (update.transactions.some((tr2) => tr2.effects.some((e) => e.is(startCompletionEffect))))
          this.pendingStart = true;
        let delay = this.pendingStart ? 50 : conf.activateOnTypingDelay;
        this.debounceUpdate = cState.active.some((a) => a.isPending && !this.running.some((q) => q.active.source == a.source)) ? setTimeout(() => this.startUpdate(), delay) : -1;
        if (this.composing != 0)
          for (let tr2 of update.transactions) {
            if (tr2.isUserEvent("input.type"))
              this.composing = 2;
            else if (this.composing == 2 && tr2.selection)
              this.composing = 3;
          }
      }
      startUpdate() {
        this.debounceUpdate = -1;
        this.pendingStart = false;
        let { state } = this.view, cState = state.field(completionState);
        for (let active2 of cState.active) {
          if (active2.isPending && !this.running.some((r2) => r2.active.source == active2.source))
            this.startQuery(active2);
        }
        if (this.running.length && cState.open && cState.open.disabled)
          this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
      }
      startQuery(active2) {
        let { state } = this.view, pos2 = cur(state);
        let context = new CompletionContext(state, pos2, active2.explicit, this.view);
        let pending = new RunningQuery(active2, context);
        this.running.push(pending);
        Promise.resolve(active2.source(context)).then((result2) => {
          if (!pending.context.aborted) {
            pending.done = result2 || null;
            this.scheduleAccept();
          }
        }, (err2) => {
          this.view.dispatch({ effects: closeCompletionEffect.of(null) });
          logException(this.view.state, err2);
        });
      }
      scheduleAccept() {
        if (this.running.every((q) => q.done !== void 0))
          this.accept();
        else if (this.debounceAccept < 0)
          this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
      }
      // For each finished query in this.running, try to create a result
      // or, if appropriate, restart the query.
      accept() {
        var _a2;
        if (this.debounceAccept > -1)
          clearTimeout(this.debounceAccept);
        this.debounceAccept = -1;
        let updated = [];
        let conf = this.view.state.facet(completionConfig), cState = this.view.state.field(completionState);
        for (let i2 = 0; i2 < this.running.length; i2++) {
          let query2 = this.running[i2];
          if (query2.done === void 0)
            continue;
          this.running.splice(i2--, 1);
          if (query2.done) {
            let pos2 = cur(query2.updates.length ? query2.updates[0].startState : this.view.state);
            let limit = Math.min(pos2, query2.done.from + (query2.active.explicit ? 0 : 1));
            let active2 = new ActiveResult(query2.active.source, query2.active.explicit, limit, query2.done, query2.done.from, (_a2 = query2.done.to) !== null && _a2 !== void 0 ? _a2 : pos2);
            for (let tr2 of query2.updates)
              active2 = active2.update(tr2, conf);
            if (active2.hasResult()) {
              updated.push(active2);
              continue;
            }
          }
          let current = cState.active.find((a) => a.source == query2.active.source);
          if (current && current.isPending) {
            if (query2.done == null) {
              let active2 = new ActiveSource(
                query2.active.source,
                0
                /* State.Inactive */
              );
              for (let tr2 of query2.updates)
                active2 = active2.update(tr2, conf);
              if (!active2.isPending)
                updated.push(active2);
            } else {
              this.startQuery(current);
            }
          }
        }
        if (updated.length || cState.open && cState.open.disabled)
          this.view.dispatch({ effects: setActiveEffect.of(updated) });
      }
    }, {
      eventHandlers: {
        blur(event) {
          let state = this.view.state.field(completionState, false);
          if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
            let dialog = state.open && getTooltip(this.view, state.open.tooltip);
            if (!dialog || !dialog.dom.contains(event.relatedTarget))
              setTimeout(() => this.view.dispatch({ effects: closeCompletionEffect.of(null) }), 10);
          }
        },
        compositionstart() {
          this.composing = 1;
        },
        compositionend() {
          if (this.composing == 3) {
            setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
          }
          this.composing = 0;
        }
      }
    });
    const windows = typeof navigator == "object" && /* @__PURE__ */ /Win/.test(navigator.platform);
    const commitCharacters = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.domEventHandlers({
      keydown(event, view) {
        let field = view.state.field(completionState, false);
        if (!field || !field.open || field.open.disabled || field.open.selected < 0 || event.key.length > 1 || event.ctrlKey && !(windows && event.altKey) || event.metaKey)
          return false;
        let option = field.open.options[field.open.selected];
        let result2 = field.active.find((a) => a.source == option.source);
        let commitChars = option.completion.commitCharacters || result2.result.commitCharacters;
        if (commitChars && commitChars.indexOf(event.key) > -1)
          applyCompletion(view, option);
        return false;
      }
    }));
    const baseTheme$1 = /* @__PURE__ */ EditorView.baseTheme({
      ".cm-tooltip.cm-tooltip-autocomplete": {
        "& > ul": {
          fontFamily: "monospace",
          whiteSpace: "nowrap",
          overflow: "hidden auto",
          maxWidth_fallback: "700px",
          maxWidth: "min(700px, 95vw)",
          minWidth: "250px",
          maxHeight: "10em",
          height: "100%",
          listStyle: "none",
          margin: 0,
          padding: 0,
          "& > li, & > completion-section": {
            padding: "1px 3px",
            lineHeight: 1.2
          },
          "& > li": {
            overflowX: "hidden",
            textOverflow: "ellipsis",
            cursor: "pointer"
          },
          "& > completion-section": {
            display: "list-item",
            borderBottom: "1px solid silver",
            paddingLeft: "0.5em",
            opacity: 0.7
          }
        }
      },
      "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
        background: "#17c",
        color: "white"
      },
      "&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
        background: "#777"
      },
      "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
        background: "#347",
        color: "white"
      },
      "&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
        background: "#444"
      },
      ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
        content: '"···"',
        opacity: 0.5,
        display: "block",
        textAlign: "center"
      },
      ".cm-tooltip.cm-completionInfo": {
        position: "absolute",
        padding: "3px 9px",
        width: "max-content",
        maxWidth: `${400}px`,
        boxSizing: "border-box",
        whiteSpace: "pre-line"
      },
      ".cm-completionInfo.cm-completionInfo-left": { right: "100%" },
      ".cm-completionInfo.cm-completionInfo-right": { left: "100%" },
      ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30}px` },
      ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30}px` },
      "&light .cm-snippetField": { backgroundColor: "#00000022" },
      "&dark .cm-snippetField": { backgroundColor: "#ffffff22" },
      ".cm-snippetFieldPosition": {
        verticalAlign: "text-top",
        width: 0,
        height: "1.15em",
        display: "inline-block",
        margin: "0 -0.7px -.7em",
        borderLeft: "1.4px dotted #888"
      },
      ".cm-completionMatchedText": {
        textDecoration: "underline"
      },
      ".cm-completionDetail": {
        marginLeft: "0.5em",
        fontStyle: "italic"
      },
      ".cm-completionIcon": {
        fontSize: "90%",
        width: ".8em",
        display: "inline-block",
        textAlign: "center",
        paddingRight: ".6em",
        opacity: "0.6",
        boxSizing: "content-box"
      },
      ".cm-completionIcon-function, .cm-completionIcon-method": {
        "&:after": { content: "'ƒ'" }
      },
      ".cm-completionIcon-class": {
        "&:after": { content: "'○'" }
      },
      ".cm-completionIcon-interface": {
        "&:after": { content: "'◌'" }
      },
      ".cm-completionIcon-variable": {
        "&:after": { content: "'𝑥'" }
      },
      ".cm-completionIcon-constant": {
        "&:after": { content: "'𝐶'" }
      },
      ".cm-completionIcon-type": {
        "&:after": { content: "'𝑡'" }
      },
      ".cm-completionIcon-enum": {
        "&:after": { content: "'∪'" }
      },
      ".cm-completionIcon-property": {
        "&:after": { content: "'□'" }
      },
      ".cm-completionIcon-keyword": {
        "&:after": { content: "'🔑︎'" }
        // Disable emoji rendering
      },
      ".cm-completionIcon-namespace": {
        "&:after": { content: "'▢'" }
      },
      ".cm-completionIcon-text": {
        "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
      }
    });
    const closedBracket = /* @__PURE__ */ new class extends RangeValue {
    }();
    closedBracket.startSide = 1;
    closedBracket.endSide = -1;
    function autocompletion(config2 = {}) {
      return [
        commitCharacters,
        completionState,
        completionConfig.of(config2),
        completionPlugin,
        completionKeymapExt,
        baseTheme$1
      ];
    }
    const completionKeymap = [
      { key: "Ctrl-Space", run: startCompletion },
      { mac: "Alt-`", run: startCompletion },
      { key: "Escape", run: closeCompletion },
      { key: "ArrowDown", run: /* @__PURE__ */ moveCompletionSelection(true) },
      { key: "ArrowUp", run: /* @__PURE__ */ moveCompletionSelection(false) },
      { key: "PageDown", run: /* @__PURE__ */ moveCompletionSelection(true, "page") },
      { key: "PageUp", run: /* @__PURE__ */ moveCompletionSelection(false, "page") },
      { key: "Enter", run: acceptCompletion }
    ];
    const completionKeymapExt = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ keymap.computeN([completionConfig], (state) => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
    function crelt() {
      var elt = arguments[0];
      if (typeof elt == "string") elt = document.createElement(elt);
      var i2 = 1, next = arguments[1];
      if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
        for (var name2 in next) if (Object.prototype.hasOwnProperty.call(next, name2)) {
          var value2 = next[name2];
          if (typeof value2 == "string") elt.setAttribute(name2, value2);
          else if (value2 != null) elt[name2] = value2;
        }
        i2++;
      }
      for (; i2 < arguments.length; i2++) add(elt, arguments[i2]);
      return elt;
    }
    function add(elt, child) {
      if (typeof child == "string") {
        elt.appendChild(document.createTextNode(child));
      } else if (child == null) ;
      else if (child.nodeType != null) {
        elt.appendChild(child);
      } else if (Array.isArray(child)) {
        for (var i2 = 0; i2 < child.length; i2++) add(elt, child[i2]);
      } else {
        throw new RangeError("Unsupported child node: " + child);
      }
    }
    class SelectedDiagnostic {
      constructor(from, to2, diagnostic) {
        this.from = from;
        this.to = to2;
        this.diagnostic = diagnostic;
      }
    }
    class LintState {
      constructor(diagnostics, panel2, selected2) {
        this.diagnostics = diagnostics;
        this.panel = panel2;
        this.selected = selected2;
      }
      static init(diagnostics, panel2, state) {
        let markedDiagnostics = diagnostics;
        let diagnosticFilter = state.facet(lintConfig).markerFilter;
        if (diagnosticFilter)
          markedDiagnostics = diagnosticFilter(markedDiagnostics, state);
        let sorted = diagnostics.slice().sort((a, b) => a.from - b.from || a.to - b.to);
        let deco = new RangeSetBuilder(), active2 = [], pos2 = 0;
        for (let i2 = 0; ; ) {
          let next = i2 == sorted.length ? null : sorted[i2];
          if (!next && !active2.length)
            break;
          let from, to2;
          if (active2.length) {
            from = pos2;
            to2 = active2.reduce((p, d) => Math.min(p, d.to), next && next.from > from ? next.from : 1e8);
          } else {
            from = next.from;
            to2 = next.to;
            active2.push(next);
            i2++;
          }
          while (i2 < sorted.length) {
            let next2 = sorted[i2];
            if (next2.from == from && (next2.to > next2.from || next2.to == from)) {
              active2.push(next2);
              i2++;
              to2 = Math.min(next2.to, to2);
            } else {
              to2 = Math.min(next2.from, to2);
              break;
            }
          }
          let sev = maxSeverity(active2);
          if (active2.some((d) => d.from == d.to || d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from)) {
            deco.add(from, from, Decoration.widget({
              widget: new DiagnosticWidget(sev),
              diagnostics: active2.slice()
            }));
          } else {
            let markClass = active2.reduce((c2, d) => d.markClass ? c2 + " " + d.markClass : c2, "");
            deco.add(from, to2, Decoration.mark({
              class: "cm-lintRange cm-lintRange-" + sev + markClass,
              diagnostics: active2.slice(),
              inclusiveEnd: active2.some((a) => a.to > to2)
            }));
          }
          pos2 = to2;
          for (let i3 = 0; i3 < active2.length; i3++)
            if (active2[i3].to <= pos2)
              active2.splice(i3--, 1);
        }
        let set = deco.finish();
        return new LintState(set, panel2, findDiagnostic(set));
      }
    }
    function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
      let found = null;
      diagnostics.between(after, 1e9, (from, to2, { spec }) => {
        if (diagnostic && spec.diagnostics.indexOf(diagnostic) < 0)
          return;
        if (!found)
          found = new SelectedDiagnostic(from, to2, diagnostic || spec.diagnostics[0]);
        else if (spec.diagnostics.indexOf(found.diagnostic) < 0)
          return false;
        else
          found = new SelectedDiagnostic(found.from, to2, found.diagnostic);
      });
      return found;
    }
    function hideTooltip(tr2, tooltip) {
      let from = tooltip.pos, to2 = tooltip.end || from;
      let result2 = tr2.state.facet(lintConfig).hideOn(tr2, from, to2);
      if (result2 != null)
        return result2;
      let line2 = tr2.startState.doc.lineAt(tooltip.pos);
      return !!(tr2.effects.some((e) => e.is(setDiagnosticsEffect)) || tr2.changes.touchesRange(line2.from, Math.max(line2.to, to2)));
    }
    function maybeEnableLint(state, effects) {
      return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of(lintExtensions));
    }
    function setDiagnostics(state, diagnostics) {
      return {
        effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)])
      };
    }
    const setDiagnosticsEffect = /* @__PURE__ */ StateEffect.define();
    const togglePanel = /* @__PURE__ */ StateEffect.define();
    const movePanelSelection = /* @__PURE__ */ StateEffect.define();
    const lintState = /* @__PURE__ */ StateField.define({
      create() {
        return new LintState(Decoration.none, null, null);
      },
      update(value2, tr2) {
        if (tr2.docChanged && value2.diagnostics.size) {
          let mapped = value2.diagnostics.map(tr2.changes), selected2 = null, panel2 = value2.panel;
          if (value2.selected) {
            let selPos = tr2.changes.mapPos(value2.selected.from, 1);
            selected2 = findDiagnostic(mapped, value2.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
          }
          if (!mapped.size && panel2 && tr2.state.facet(lintConfig).autoPanel)
            panel2 = null;
          value2 = new LintState(mapped, panel2, selected2);
        }
        for (let effect of tr2.effects) {
          if (effect.is(setDiagnosticsEffect)) {
            let panel2 = !tr2.state.facet(lintConfig).autoPanel ? value2.panel : effect.value.length ? LintPanel.open : null;
            value2 = LintState.init(effect.value, panel2, tr2.state);
          } else if (effect.is(togglePanel)) {
            value2 = new LintState(value2.diagnostics, effect.value ? LintPanel.open : null, value2.selected);
          } else if (effect.is(movePanelSelection)) {
            value2 = new LintState(value2.diagnostics, value2.panel, effect.value);
          }
        }
        return value2;
      },
      provide: (f) => [
        showPanel.from(f, (val) => val.panel),
        EditorView.decorations.from(f, (s) => s.diagnostics)
      ]
    });
    const activeMark = /* @__PURE__ */ Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
    function lintTooltip(view, pos2, side) {
      let { diagnostics } = view.state.field(lintState);
      let found, start = -1, end = -1;
      diagnostics.between(pos2 - (side < 0 ? 1 : 0), pos2 + (side > 0 ? 1 : 0), (from, to2, { spec }) => {
        if (pos2 >= from && pos2 <= to2 && (from == to2 || (pos2 > from || side > 0) && (pos2 < to2 || side < 0))) {
          found = spec.diagnostics;
          start = from;
          end = to2;
          return false;
        }
      });
      let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
      if (found && diagnosticFilter)
        found = diagnosticFilter(found, view.state);
      if (!found)
        return null;
      return {
        pos: start,
        end,
        above: view.state.doc.lineAt(start).to < end,
        create() {
          return { dom: diagnosticsTooltip(view, found) };
        }
      };
    }
    function diagnosticsTooltip(view, diagnostics) {
      return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map((d) => renderDiagnostic(view, d, false)));
    }
    const closeLintPanel = (view) => {
      let field = view.state.field(lintState, false);
      if (!field || !field.panel)
        return false;
      view.dispatch({ effects: togglePanel.of(false) });
      return true;
    };
    const lintPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
      constructor(view) {
        this.view = view;
        this.timeout = -1;
        this.set = true;
        let { delay } = view.state.facet(lintConfig);
        this.lintTime = Date.now() + delay;
        this.run = this.run.bind(this);
        this.timeout = setTimeout(this.run, delay);
      }
      run() {
        clearTimeout(this.timeout);
        let now2 = Date.now();
        if (now2 < this.lintTime - 10) {
          this.timeout = setTimeout(this.run, this.lintTime - now2);
        } else {
          this.set = false;
          let { state } = this.view, { sources } = state.facet(lintConfig);
          if (sources.length)
            batchResults(sources.map((s) => Promise.resolve(s(this.view))), (annotations) => {
              if (this.view.state.doc == state.doc)
                this.view.dispatch(setDiagnostics(this.view.state, annotations.reduce((a, b) => a.concat(b))));
            }, (error2) => {
              logException(this.view.state, error2);
            });
        }
      }
      update(update) {
        let config2 = update.state.facet(lintConfig);
        if (update.docChanged || config2 != update.startState.facet(lintConfig) || config2.needsRefresh && config2.needsRefresh(update)) {
          this.lintTime = Date.now() + config2.delay;
          if (!this.set) {
            this.set = true;
            this.timeout = setTimeout(this.run, config2.delay);
          }
        }
      }
      force() {
        if (this.set) {
          this.lintTime = Date.now();
          this.run();
        }
      }
      destroy() {
        clearTimeout(this.timeout);
      }
    });
    function batchResults(promises, sink, error2) {
      let collected = [], timeout = -1;
      for (let p of promises)
        p.then((value2) => {
          collected.push(value2);
          clearTimeout(timeout);
          if (collected.length == promises.length)
            sink(collected);
          else
            timeout = setTimeout(() => sink(collected), 200);
        }, error2);
    }
    const lintConfig = /* @__PURE__ */ Facet.define({
      combine(input2) {
        return Object.assign({ sources: input2.map((i2) => i2.source).filter((x2) => x2 != null) }, combineConfig(input2.map((i2) => i2.config), {
          delay: 750,
          markerFilter: null,
          tooltipFilter: null,
          needsRefresh: null,
          hideOn: () => null
        }, {
          needsRefresh: (a, b) => !a ? b : !b ? a : (u) => a(u) || b(u)
        }));
      }
    });
    function linter(source2, config2 = {}) {
      return [
        lintConfig.of({ source: source2, config: config2 }),
        lintPlugin,
        lintExtensions
      ];
    }
    function assignKeys(actions) {
      let assigned = [];
      if (actions)
        actions: for (let { name: name2 } of actions) {
          for (let i2 = 0; i2 < name2.length; i2++) {
            let ch3 = name2[i2];
            if (/[a-zA-Z]/.test(ch3) && !assigned.some((c2) => c2.toLowerCase() == ch3.toLowerCase())) {
              assigned.push(ch3);
              continue actions;
            }
          }
          assigned.push("");
        }
      return assigned;
    }
    function renderDiagnostic(view, diagnostic, inPanel) {
      var _a2;
      let keys = inPanel ? assignKeys(diagnostic.actions) : [];
      return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage(view) : diagnostic.message), (_a2 = diagnostic.actions) === null || _a2 === void 0 ? void 0 : _a2.map((action, i2) => {
        let fired = false, click = (e) => {
          e.preventDefault();
          if (fired)
            return;
          fired = true;
          let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
          if (found)
            action.apply(view, found.from, found.to);
        };
        let { name: name2 } = action, keyIndex = keys[i2] ? name2.indexOf(keys[i2]) : -1;
        let nameElt = keyIndex < 0 ? name2 : [
          name2.slice(0, keyIndex),
          crelt("u", name2.slice(keyIndex, keyIndex + 1)),
          name2.slice(keyIndex + 1)
        ];
        return crelt("button", {
          type: "button",
          class: "cm-diagnosticAction",
          onclick: click,
          onmousedown: click,
          "aria-label": ` Action: ${name2}${keyIndex < 0 ? "" : ` (access key "${keys[i2]})"`}.`
        }, nameElt);
      }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source));
    }
    class DiagnosticWidget extends WidgetType {
      constructor(sev) {
        super();
        this.sev = sev;
      }
      eq(other) {
        return other.sev == this.sev;
      }
      toDOM() {
        return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.sev });
      }
    }
    class PanelItem {
      constructor(view, diagnostic) {
        this.diagnostic = diagnostic;
        this.id = "item_" + Math.floor(Math.random() * 4294967295).toString(16);
        this.dom = renderDiagnostic(view, diagnostic, true);
        this.dom.id = this.id;
        this.dom.setAttribute("role", "option");
      }
    }
    class LintPanel {
      constructor(view) {
        this.view = view;
        this.items = [];
        let onkeydown = (event) => {
          if (event.keyCode == 27) {
            closeLintPanel(this.view);
            this.view.focus();
          } else if (event.keyCode == 38 || event.keyCode == 33) {
            this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
          } else if (event.keyCode == 40 || event.keyCode == 34) {
            this.moveSelection((this.selectedIndex + 1) % this.items.length);
          } else if (event.keyCode == 36) {
            this.moveSelection(0);
          } else if (event.keyCode == 35) {
            this.moveSelection(this.items.length - 1);
          } else if (event.keyCode == 13) {
            this.view.focus();
          } else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) {
            let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions);
            for (let i2 = 0; i2 < keys.length; i2++)
              if (keys[i2].toUpperCase().charCodeAt(0) == event.keyCode) {
                let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
                if (found)
                  diagnostic.actions[i2].apply(view, found.from, found.to);
              }
          } else {
            return;
          }
          event.preventDefault();
        };
        let onclick = (event) => {
          for (let i2 = 0; i2 < this.items.length; i2++) {
            if (this.items[i2].dom.contains(event.target))
              this.moveSelection(i2);
          }
        };
        this.list = crelt("ul", {
          tabIndex: 0,
          role: "listbox",
          "aria-label": this.view.state.phrase("Diagnostics"),
          onkeydown,
          onclick
        });
        this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", {
          type: "button",
          name: "close",
          "aria-label": this.view.state.phrase("close"),
          onclick: () => closeLintPanel(this.view)
        }, "×"));
        this.update();
      }
      get selectedIndex() {
        let selected2 = this.view.state.field(lintState).selected;
        if (!selected2)
          return -1;
        for (let i2 = 0; i2 < this.items.length; i2++)
          if (this.items[i2].diagnostic == selected2.diagnostic)
            return i2;
        return -1;
      }
      update() {
        let { diagnostics, selected: selected2 } = this.view.state.field(lintState);
        let i2 = 0, needsSync = false, newSelectedItem = null;
        let seen = /* @__PURE__ */ new Set();
        diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
          for (let diagnostic of spec.diagnostics) {
            if (seen.has(diagnostic))
              continue;
            seen.add(diagnostic);
            let found = -1, item2;
            for (let j2 = i2; j2 < this.items.length; j2++)
              if (this.items[j2].diagnostic == diagnostic) {
                found = j2;
                break;
              }
            if (found < 0) {
              item2 = new PanelItem(this.view, diagnostic);
              this.items.splice(i2, 0, item2);
              needsSync = true;
            } else {
              item2 = this.items[found];
              if (found > i2) {
                this.items.splice(i2, found - i2);
                needsSync = true;
              }
            }
            if (selected2 && item2.diagnostic == selected2.diagnostic) {
              if (!item2.dom.hasAttribute("aria-selected")) {
                item2.dom.setAttribute("aria-selected", "true");
                newSelectedItem = item2;
              }
            } else if (item2.dom.hasAttribute("aria-selected")) {
              item2.dom.removeAttribute("aria-selected");
            }
            i2++;
          }
        });
        while (i2 < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
          needsSync = true;
          this.items.pop();
        }
        if (this.items.length == 0) {
          this.items.push(new PanelItem(this.view, {
            from: -1,
            to: -1,
            severity: "info",
            message: this.view.state.phrase("No diagnostics")
          }));
          needsSync = true;
        }
        if (newSelectedItem) {
          this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
          this.view.requestMeasure({
            key: this,
            read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
            write: ({ sel, panel: panel2 }) => {
              let scaleY = panel2.height / this.list.offsetHeight;
              if (sel.top < panel2.top)
                this.list.scrollTop -= (panel2.top - sel.top) / scaleY;
              else if (sel.bottom > panel2.bottom)
                this.list.scrollTop += (sel.bottom - panel2.bottom) / scaleY;
            }
          });
        } else if (this.selectedIndex < 0) {
          this.list.removeAttribute("aria-activedescendant");
        }
        if (needsSync)
          this.sync();
      }
      sync() {
        let domPos = this.list.firstChild;
        function rm2() {
          let prev = domPos;
          domPos = prev.nextSibling;
          prev.remove();
        }
        for (let item2 of this.items) {
          if (item2.dom.parentNode == this.list) {
            while (domPos != item2.dom)
              rm2();
            domPos = item2.dom.nextSibling;
          } else {
            this.list.insertBefore(item2.dom, domPos);
          }
        }
        while (domPos)
          rm2();
      }
      moveSelection(selectedIndex) {
        if (this.selectedIndex < 0)
          return;
        let field = this.view.state.field(lintState);
        let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
        if (!selection)
          return;
        this.view.dispatch({
          selection: { anchor: selection.from, head: selection.to },
          scrollIntoView: true,
          effects: movePanelSelection.of(selection)
        });
      }
      static open(view) {
        return new LintPanel(view);
      }
    }
    function svg(content2, attrs = `viewBox="0 0 40 40"`) {
      return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content2)}</svg>')`;
    }
    function underline(color) {
      return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
    }
    const baseTheme = /* @__PURE__ */ EditorView.baseTheme({
      ".cm-diagnostic": {
        padding: "3px 6px 3px 8px",
        marginLeft: "-1px",
        display: "block",
        whiteSpace: "pre-wrap"
      },
      ".cm-diagnostic-error": { borderLeft: "5px solid #d11" },
      ".cm-diagnostic-warning": { borderLeft: "5px solid orange" },
      ".cm-diagnostic-info": { borderLeft: "5px solid #999" },
      ".cm-diagnostic-hint": { borderLeft: "5px solid #66d" },
      ".cm-diagnosticAction": {
        font: "inherit",
        border: "none",
        padding: "2px 4px",
        backgroundColor: "#444",
        color: "white",
        borderRadius: "3px",
        marginLeft: "8px",
        cursor: "pointer"
      },
      ".cm-diagnosticSource": {
        fontSize: "70%",
        opacity: 0.7
      },
      ".cm-lintRange": {
        backgroundPosition: "left bottom",
        backgroundRepeat: "repeat-x",
        paddingBottom: "0.7px"
      },
      ".cm-lintRange-error": { backgroundImage: /* @__PURE__ */ underline("#d11") },
      ".cm-lintRange-warning": { backgroundImage: /* @__PURE__ */ underline("orange") },
      ".cm-lintRange-info": { backgroundImage: /* @__PURE__ */ underline("#999") },
      ".cm-lintRange-hint": { backgroundImage: /* @__PURE__ */ underline("#66d") },
      ".cm-lintRange-active": { backgroundColor: "#ffdd9980" },
      ".cm-tooltip-lint": {
        padding: 0,
        margin: 0
      },
      ".cm-lintPoint": {
        position: "relative",
        "&:after": {
          content: '""',
          position: "absolute",
          bottom: 0,
          left: "-2px",
          borderLeft: "3px solid transparent",
          borderRight: "3px solid transparent",
          borderBottom: "4px solid #d11"
        }
      },
      ".cm-lintPoint-warning": {
        "&:after": { borderBottomColor: "orange" }
      },
      ".cm-lintPoint-info": {
        "&:after": { borderBottomColor: "#999" }
      },
      ".cm-lintPoint-hint": {
        "&:after": { borderBottomColor: "#66d" }
      },
      ".cm-panel.cm-panel-lint": {
        position: "relative",
        "& ul": {
          maxHeight: "100px",
          overflowY: "auto",
          "& [aria-selected]": {
            backgroundColor: "#ddd",
            "& u": { textDecoration: "underline" }
          },
          "&:focus [aria-selected]": {
            background_fallback: "#bdf",
            backgroundColor: "Highlight",
            color_fallback: "white",
            color: "HighlightText"
          },
          "& u": { textDecoration: "none" },
          padding: 0,
          margin: 0
        },
        "& [name=close]": {
          position: "absolute",
          top: "0",
          right: "2px",
          background: "inherit",
          border: "none",
          font: "inherit",
          padding: 0,
          margin: 0
        }
      }
    });
    function severityWeight(sev) {
      return sev == "error" ? 4 : sev == "warning" ? 3 : sev == "info" ? 2 : 1;
    }
    function maxSeverity(diagnostics) {
      let sev = "hint", weight = 1;
      for (let d of diagnostics) {
        let w2 = severityWeight(d.severity);
        if (w2 > weight) {
          weight = w2;
          sev = d.severity;
        }
      }
      return sev;
    }
    const lintExtensions = [
      lintState,
      /* @__PURE__ */ EditorView.decorations.compute([lintState], (state) => {
        let { selected: selected2, panel: panel2 } = state.field(lintState);
        return !selected2 || !panel2 || selected2.from == selected2.to ? Decoration.none : Decoration.set([
          activeMark.range(selected2.from, selected2.to)
        ]);
      }),
      /* @__PURE__ */ hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
      baseTheme
    ];
    const toggleComment = (target2) => {
      let { state } = target2, line2 = state.doc.lineAt(state.selection.main.from), config2 = getConfig(target2.state, line2.from);
      return config2.line ? toggleLineComment(target2) : config2.block ? toggleBlockCommentByLine(target2) : false;
    };
    function command(f, option) {
      return ({ state, dispatch }) => {
        if (state.readOnly)
          return false;
        let tr2 = f(option, state);
        if (!tr2)
          return false;
        dispatch(state.update(tr2));
        return true;
      };
    }
    const toggleLineComment = /* @__PURE__ */ command(
      changeLineComment,
      0
      /* CommentOption.Toggle */
    );
    const toggleBlockComment = /* @__PURE__ */ command(
      changeBlockComment,
      0
      /* CommentOption.Toggle */
    );
    const toggleBlockCommentByLine = /* @__PURE__ */ command(
      (o, s) => changeBlockComment(o, s, selectedLineRanges(s)),
      0
      /* CommentOption.Toggle */
    );
    function getConfig(state, pos2) {
      let data = state.languageDataAt("commentTokens", pos2);
      return data.length ? data[0] : {};
    }
    const SearchMargin = 50;
    function findBlockComment(state, { open, close: close2 }, from, to2) {
      let textBefore = state.sliceDoc(from - SearchMargin, from);
      let textAfter = state.sliceDoc(to2, to2 + SearchMargin);
      let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
      let beforeOff = textBefore.length - spaceBefore;
      if (textBefore.slice(beforeOff - open.length, beforeOff) == open && textAfter.slice(spaceAfter, spaceAfter + close2.length) == close2) {
        return {
          open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
          close: { pos: to2 + spaceAfter, margin: spaceAfter && 1 }
        };
      }
      let startText2, endText;
      if (to2 - from <= 2 * SearchMargin) {
        startText2 = endText = state.sliceDoc(from, to2);
      } else {
        startText2 = state.sliceDoc(from, from + SearchMargin);
        endText = state.sliceDoc(to2 - SearchMargin, to2);
      }
      let startSpace = /^\s*/.exec(startText2)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
      let endOff = endText.length - endSpace - close2.length;
      if (startText2.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close2.length) == close2) {
        return {
          open: {
            pos: from + startSpace + open.length,
            margin: /\s/.test(startText2.charAt(startSpace + open.length)) ? 1 : 0
          },
          close: {
            pos: to2 - endSpace - close2.length,
            margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0
          }
        };
      }
      return null;
    }
    function selectedLineRanges(state) {
      let ranges = [];
      for (let r2 of state.selection.ranges) {
        let fromLine = state.doc.lineAt(r2.from);
        let toLine = r2.to <= fromLine.to ? fromLine : state.doc.lineAt(r2.to);
        if (toLine.from > fromLine.from && toLine.from == r2.to)
          toLine = r2.to == fromLine.to + 1 ? fromLine : state.doc.lineAt(r2.to - 1);
        let last = ranges.length - 1;
        if (last >= 0 && ranges[last].to > fromLine.from)
          ranges[last].to = toLine.to;
        else
          ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to });
      }
      return ranges;
    }
    function changeBlockComment(option, state, ranges = state.selection.ranges) {
      let tokens = ranges.map((r2) => getConfig(state, r2.from).block);
      if (!tokens.every((c2) => c2))
        return null;
      let comments = ranges.map((r2, i2) => findBlockComment(state, tokens[i2], r2.from, r2.to));
      if (option != 2 && !comments.every((c2) => c2)) {
        return { changes: state.changes(ranges.map((range, i2) => {
          if (comments[i2])
            return [];
          return [{ from: range.from, insert: tokens[i2].open + " " }, { from: range.to, insert: " " + tokens[i2].close }];
        })) };
      } else if (option != 1 && comments.some((c2) => c2)) {
        let changes = [];
        for (let i2 = 0, comment2; i2 < comments.length; i2++)
          if (comment2 = comments[i2]) {
            let token2 = tokens[i2], { open, close: close2 } = comment2;
            changes.push({ from: open.pos - token2.open.length, to: open.pos + open.margin }, { from: close2.pos - close2.margin, to: close2.pos + token2.close.length });
          }
        return { changes };
      }
      return null;
    }
    function changeLineComment(option, state, ranges = state.selection.ranges) {
      let lines = [];
      let prevLine = -1;
      for (let { from, to: to2 } of ranges) {
        let startI = lines.length, minIndent = 1e9;
        let token2 = getConfig(state, from).line;
        if (!token2)
          continue;
        for (let pos2 = from; pos2 <= to2; ) {
          let line2 = state.doc.lineAt(pos2);
          if (line2.from > prevLine && (from == to2 || to2 > line2.from)) {
            prevLine = line2.from;
            let indent = /^\s*/.exec(line2.text)[0].length;
            let empty = indent == line2.length;
            let comment2 = line2.text.slice(indent, indent + token2.length) == token2 ? indent : -1;
            if (indent < line2.text.length && indent < minIndent)
              minIndent = indent;
            lines.push({ line: line2, comment: comment2, token: token2, indent, empty, single: false });
          }
          pos2 = line2.to + 1;
        }
        if (minIndent < 1e9) {
          for (let i2 = startI; i2 < lines.length; i2++)
            if (lines[i2].indent < lines[i2].line.text.length)
              lines[i2].indent = minIndent;
        }
        if (lines.length == startI + 1)
          lines[startI].single = true;
      }
      if (option != 2 && lines.some((l) => l.comment < 0 && (!l.empty || l.single))) {
        let changes = [];
        for (let { line: line2, token: token2, indent, empty, single } of lines)
          if (single || !empty)
            changes.push({ from: line2.from + indent, insert: token2 + " " });
        let changeSet = state.changes(changes);
        return { changes: changeSet, selection: state.selection.map(changeSet, 1) };
      } else if (option != 1 && lines.some((l) => l.comment >= 0)) {
        let changes = [];
        for (let { line: line2, comment: comment2, token: token2 } of lines)
          if (comment2 >= 0) {
            let from = line2.from + comment2, to2 = from + token2.length;
            if (line2.text[to2 - line2.from] == " ")
              to2++;
            changes.push({ from, to: to2 });
          }
        return { changes };
      }
      return null;
    }
    const fromHistory = /* @__PURE__ */ Annotation.define();
    const isolateHistory = /* @__PURE__ */ Annotation.define();
    const invertedEffects = /* @__PURE__ */ Facet.define();
    const historyConfig = /* @__PURE__ */ Facet.define({
      combine(configs) {
        return combineConfig(configs, {
          minDepth: 100,
          newGroupDelay: 500,
          joinToEvent: (_t2, isAdjacent2) => isAdjacent2
        }, {
          minDepth: Math.max,
          newGroupDelay: Math.min,
          joinToEvent: (a, b) => (tr2, adj) => a(tr2, adj) || b(tr2, adj)
        });
      }
    });
    const historyField_ = /* @__PURE__ */ StateField.define({
      create() {
        return HistoryState.empty;
      },
      update(state, tr2) {
        let config2 = tr2.state.facet(historyConfig);
        let fromHist = tr2.annotation(fromHistory);
        if (fromHist) {
          let item2 = HistEvent.fromTransaction(tr2, fromHist.selection), from = fromHist.side;
          let other = from == 0 ? state.undone : state.done;
          if (item2)
            other = updateBranch(other, other.length, config2.minDepth, item2);
          else
            other = addSelection(other, tr2.startState.selection);
          return new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest);
        }
        let isolate = tr2.annotation(isolateHistory);
        if (isolate == "full" || isolate == "before")
          state = state.isolate();
        if (tr2.annotation(Transaction.addToHistory) === false)
          return !tr2.changes.empty ? state.addMapping(tr2.changes.desc) : state;
        let event = HistEvent.fromTransaction(tr2);
        let time = tr2.annotation(Transaction.time), userEvent = tr2.annotation(Transaction.userEvent);
        if (event)
          state = state.addChanges(event, time, userEvent, config2, tr2);
        else if (tr2.selection)
          state = state.addSelection(tr2.startState.selection, time, userEvent, config2.newGroupDelay);
        if (isolate == "full" || isolate == "after")
          state = state.isolate();
        return state;
      },
      toJSON(value2) {
        return { done: value2.done.map((e) => e.toJSON()), undone: value2.undone.map((e) => e.toJSON()) };
      },
      fromJSON(json) {
        return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));
      }
    });
    function history(config2 = {}) {
      return [
        historyField_,
        historyConfig.of(config2),
        EditorView.domEventHandlers({
          beforeinput(e, view) {
            let command2 = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
            if (!command2)
              return false;
            e.preventDefault();
            return command2(view);
          }
        })
      ];
    }
    function cmd(side, selection) {
      return function({ state, dispatch }) {
        if (!selection && state.readOnly)
          return false;
        let historyState = state.field(historyField_, false);
        if (!historyState)
          return false;
        let tr2 = historyState.pop(side, state, selection);
        if (!tr2)
          return false;
        dispatch(tr2);
        return true;
      };
    }
    const undo = /* @__PURE__ */ cmd(0, false);
    const redo = /* @__PURE__ */ cmd(1, false);
    const undoSelection = /* @__PURE__ */ cmd(0, true);
    const redoSelection = /* @__PURE__ */ cmd(1, true);
    class HistEvent {
      constructor(changes, effects, mapped, startSelection, selectionsAfter) {
        this.changes = changes;
        this.effects = effects;
        this.mapped = mapped;
        this.startSelection = startSelection;
        this.selectionsAfter = selectionsAfter;
      }
      setSelAfter(after) {
        return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
      }
      toJSON() {
        var _a2, _b2, _c;
        return {
          changes: (_a2 = this.changes) === null || _a2 === void 0 ? void 0 : _a2.toJSON(),
          mapped: (_b2 = this.mapped) === null || _b2 === void 0 ? void 0 : _b2.toJSON(),
          startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
          selectionsAfter: this.selectionsAfter.map((s) => s.toJSON())
        };
      }
      static fromJSON(json) {
        return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON));
      }
      // This does not check `addToHistory` and such, it assumes the
      // transaction needs to be converted to an item. Returns null when
      // there are no changes or effects in the transaction.
      static fromTransaction(tr2, selection) {
        let effects = none;
        for (let invert of tr2.startState.facet(invertedEffects)) {
          let result2 = invert(tr2);
          if (result2.length)
            effects = effects.concat(result2);
        }
        if (!effects.length && tr2.changes.empty)
          return null;
        return new HistEvent(tr2.changes.invert(tr2.startState.doc), effects, void 0, selection || tr2.startState.selection, none);
      }
      static selection(selections) {
        return new HistEvent(void 0, none, void 0, void 0, selections);
      }
    }
    function updateBranch(branch, to2, maxLen, newEvent) {
      let start = to2 + 1 > maxLen + 20 ? to2 - maxLen - 1 : 0;
      let newBranch = branch.slice(start, to2);
      newBranch.push(newEvent);
      return newBranch;
    }
    function isAdjacent(a, b) {
      let ranges = [], isAdjacent2 = false;
      a.iterChangedRanges((f, t2) => ranges.push(f, t2));
      b.iterChangedRanges((_f, _t2, f, t2) => {
        for (let i2 = 0; i2 < ranges.length; ) {
          let from = ranges[i2++], to2 = ranges[i2++];
          if (t2 >= from && f <= to2)
            isAdjacent2 = true;
        }
      });
      return isAdjacent2;
    }
    function eqSelectionShape(a, b) {
      return a.ranges.length == b.ranges.length && a.ranges.filter((r2, i2) => r2.empty != b.ranges[i2].empty).length === 0;
    }
    function conc(a, b) {
      return !a.length ? b : !b.length ? a : a.concat(b);
    }
    const none = [];
    const MaxSelectionsPerEvent = 200;
    function addSelection(branch, selection) {
      if (!branch.length) {
        return [HistEvent.selection([selection])];
      } else {
        let lastEvent = branch[branch.length - 1];
        let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
        if (sels.length && sels[sels.length - 1].eq(selection))
          return branch;
        sels.push(selection);
        return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
      }
    }
    function popSelection(branch) {
      let last = branch[branch.length - 1];
      let newBranch = branch.slice();
      newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
      return newBranch;
    }
    function addMappingToBranch(branch, mapping) {
      if (!branch.length)
        return branch;
      let length = branch.length, selections = none;
      while (length) {
        let event = mapEvent(branch[length - 1], mapping, selections);
        if (event.changes && !event.changes.empty || event.effects.length) {
          let result2 = branch.slice(0, length);
          result2[length - 1] = event;
          return result2;
        } else {
          mapping = event.mapped;
          length--;
          selections = event.selectionsAfter;
        }
      }
      return selections.length ? [HistEvent.selection(selections)] : none;
    }
    function mapEvent(event, mapping, extraSelections) {
      let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map((s) => s.map(mapping)) : none, extraSelections);
      if (!event.changes)
        return HistEvent.selection(selections);
      let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
      let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
      return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
    }
    const joinableUserEvent = /^(input\.type|delete)($|\.)/;
    class HistoryState {
      constructor(done, undone, prevTime = 0, prevUserEvent = void 0) {
        this.done = done;
        this.undone = undone;
        this.prevTime = prevTime;
        this.prevUserEvent = prevUserEvent;
      }
      isolate() {
        return this.prevTime ? new HistoryState(this.done, this.undone) : this;
      }
      addChanges(event, time, userEvent, config2, tr2) {
        let done = this.done, lastEvent = done[done.length - 1];
        if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < config2.newGroupDelay && config2.joinToEvent(tr2, isAdjacent(lastEvent.changes, event.changes)) || // For compose (but not compose.start) events, always join with previous event
        userEvent == "input.type.compose")) {
          done = updateBranch(done, done.length - 1, config2.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(StateEffect.mapEffects(event.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none));
        } else {
          done = updateBranch(done, done.length, config2.minDepth, event);
        }
        return new HistoryState(done, none, time, userEvent);
      }
      addSelection(selection, time, userEvent, newGroupDelay) {
        let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none;
        if (last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection))
          return this;
        return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
      }
      addMapping(mapping) {
        return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
      }
      pop(side, state, onlySelection) {
        let branch = side == 0 ? this.done : this.undone;
        if (branch.length == 0)
          return null;
        let event = branch[branch.length - 1], selection = event.selectionsAfter[0] || state.selection;
        if (onlySelection && event.selectionsAfter.length) {
          return state.update({
            selection: event.selectionsAfter[event.selectionsAfter.length - 1],
            annotations: fromHistory.of({ side, rest: popSelection(branch), selection }),
            userEvent: side == 0 ? "select.undo" : "select.redo",
            scrollIntoView: true
          });
        } else if (!event.changes) {
          return null;
        } else {
          let rest = branch.length == 1 ? none : branch.slice(0, branch.length - 1);
          if (event.mapped)
            rest = addMappingToBranch(rest, event.mapped);
          return state.update({
            changes: event.changes,
            selection: event.startSelection,
            effects: event.effects,
            annotations: fromHistory.of({ side, rest, selection }),
            filter: false,
            userEvent: side == 0 ? "undo" : "redo",
            scrollIntoView: true
          });
        }
      }
    }
    HistoryState.empty = /* @__PURE__ */ new HistoryState(none, none);
    const historyKeymap = [
      { key: "Mod-z", run: undo, preventDefault: true },
      { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
      { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
      { key: "Mod-u", run: undoSelection, preventDefault: true },
      { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
    ];
    function updateSel(sel, by) {
      return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
    }
    function setSel(state, selection) {
      return state.update({ selection, scrollIntoView: true, userEvent: "select" });
    }
    function moveSel({ state, dispatch }, how) {
      let selection = updateSel(state.selection, how);
      if (selection.eq(state.selection, true))
        return false;
      dispatch(setSel(state, selection));
      return true;
    }
    function rangeEnd(range, forward) {
      return EditorSelection.cursor(forward ? range.to : range.from);
    }
    function cursorByChar(view, forward) {
      return moveSel(view, (range) => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
    }
    function ltrAtCursor(view) {
      return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;
    }
    const cursorCharLeft = (view) => cursorByChar(view, !ltrAtCursor(view));
    const cursorCharRight = (view) => cursorByChar(view, ltrAtCursor(view));
    function cursorByGroup(view, forward) {
      return moveSel(view, (range) => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
    }
    const cursorGroupLeft = (view) => cursorByGroup(view, !ltrAtCursor(view));
    const cursorGroupRight = (view) => cursorByGroup(view, ltrAtCursor(view));
    function interestingNode(state, node2, bracketProp) {
      if (node2.type.prop(bracketProp))
        return true;
      let len = node2.to - node2.from;
      return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node2.from, node2.to))) || node2.firstChild;
    }
    function moveBySyntax(state, start, forward) {
      let pos2 = syntaxTree(state).resolveInner(start.head);
      let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
      for (let at2 = start.head; ; ) {
        let next = forward ? pos2.childAfter(at2) : pos2.childBefore(at2);
        if (!next)
          break;
        if (interestingNode(state, next, bracketProp))
          pos2 = next;
        else
          at2 = forward ? next.to : next.from;
      }
      let bracket2 = pos2.type.prop(bracketProp), match, newPos;
      if (bracket2 && (match = forward ? matchBrackets(state, pos2.from, 1) : matchBrackets(state, pos2.to, -1)) && match.matched)
        newPos = forward ? match.end.to : match.end.from;
      else
        newPos = forward ? pos2.to : pos2.from;
      return EditorSelection.cursor(newPos, forward ? -1 : 1);
    }
    const cursorSyntaxLeft = (view) => moveSel(view, (range) => moveBySyntax(view.state, range, !ltrAtCursor(view)));
    const cursorSyntaxRight = (view) => moveSel(view, (range) => moveBySyntax(view.state, range, ltrAtCursor(view)));
    function cursorByLine(view, forward) {
      return moveSel(view, (range) => {
        if (!range.empty)
          return rangeEnd(range, forward);
        let moved = view.moveVertically(range, forward);
        return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);
      });
    }
    const cursorLineUp = (view) => cursorByLine(view, false);
    const cursorLineDown = (view) => cursorByLine(view, true);
    function pageInfo(view) {
      let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
      let marginTop = 0, marginBottom = 0, height;
      if (selfScroll) {
        for (let source2 of view.state.facet(EditorView.scrollMargins)) {
          let margins = source2(view);
          if (margins === null || margins === void 0 ? void 0 : margins.top)
            marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
          if (margins === null || margins === void 0 ? void 0 : margins.bottom)
            marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
        }
        height = view.scrollDOM.clientHeight - marginTop - marginBottom;
      } else {
        height = (view.dom.ownerDocument.defaultView || window).innerHeight;
      }
      return {
        marginTop,
        marginBottom,
        selfScroll,
        height: Math.max(view.defaultLineHeight, height - 5)
      };
    }
    function cursorByPage(view, forward) {
      let page = pageInfo(view);
      let { state } = view, selection = updateSel(state.selection, (range) => {
        return range.empty ? view.moveVertically(range, forward, page.height) : rangeEnd(range, forward);
      });
      if (selection.eq(state.selection))
        return false;
      let effect;
      if (page.selfScroll) {
        let startPos = view.coordsAtPos(state.selection.main.head);
        let scrollRect = view.scrollDOM.getBoundingClientRect();
        let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;
        if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
          effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop });
      }
      view.dispatch(setSel(state, selection), { effects: effect });
      return true;
    }
    const cursorPageUp = (view) => cursorByPage(view, false);
    const cursorPageDown = (view) => cursorByPage(view, true);
    function moveByLineBoundary(view, start, forward) {
      let line2 = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);
      if (moved.head == start.head && moved.head != (forward ? line2.to : line2.from))
        moved = view.moveToLineBoundary(start, forward, false);
      if (!forward && moved.head == line2.from && line2.length) {
        let space = /^\s*/.exec(view.state.sliceDoc(line2.from, Math.min(line2.from + 100, line2.to)))[0].length;
        if (space && start.head != line2.from + space)
          moved = EditorSelection.cursor(line2.from + space);
      }
      return moved;
    }
    const cursorLineBoundaryForward = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, true));
    const cursorLineBoundaryBackward = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, false));
    const cursorLineBoundaryLeft = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, !ltrAtCursor(view)));
    const cursorLineBoundaryRight = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, ltrAtCursor(view)));
    const cursorLineStart = (view) => moveSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));
    const cursorLineEnd = (view) => moveSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));
    function toMatchingBracket(state, dispatch, extend) {
      let found = false, selection = updateSel(state.selection, (range) => {
        let matching = matchBrackets(state, range.head, -1) || matchBrackets(state, range.head, 1) || range.head > 0 && matchBrackets(state, range.head - 1, 1) || range.head < state.doc.length && matchBrackets(state, range.head + 1, -1);
        if (!matching || !matching.end)
          return range;
        found = true;
        let head = matching.start.from == range.head ? matching.end.to : matching.end.from;
        return EditorSelection.cursor(head);
      });
      if (!found)
        return false;
      dispatch(setSel(state, selection));
      return true;
    }
    const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch);
    function extendSel(target2, how) {
      let selection = updateSel(target2.state.selection, (range) => {
        let head = how(range);
        return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || void 0);
      });
      if (selection.eq(target2.state.selection))
        return false;
      target2.dispatch(setSel(target2.state, selection));
      return true;
    }
    function selectByChar(view, forward) {
      return extendSel(view, (range) => view.moveByChar(range, forward));
    }
    const selectCharLeft = (view) => selectByChar(view, !ltrAtCursor(view));
    const selectCharRight = (view) => selectByChar(view, ltrAtCursor(view));
    function selectByGroup(view, forward) {
      return extendSel(view, (range) => view.moveByGroup(range, forward));
    }
    const selectGroupLeft = (view) => selectByGroup(view, !ltrAtCursor(view));
    const selectGroupRight = (view) => selectByGroup(view, ltrAtCursor(view));
    const selectSyntaxLeft = (view) => extendSel(view, (range) => moveBySyntax(view.state, range, !ltrAtCursor(view)));
    const selectSyntaxRight = (view) => extendSel(view, (range) => moveBySyntax(view.state, range, ltrAtCursor(view)));
    function selectByLine(view, forward) {
      return extendSel(view, (range) => view.moveVertically(range, forward));
    }
    const selectLineUp = (view) => selectByLine(view, false);
    const selectLineDown = (view) => selectByLine(view, true);
    function selectByPage(view, forward) {
      return extendSel(view, (range) => view.moveVertically(range, forward, pageInfo(view).height));
    }
    const selectPageUp = (view) => selectByPage(view, false);
    const selectPageDown = (view) => selectByPage(view, true);
    const selectLineBoundaryForward = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, true));
    const selectLineBoundaryBackward = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, false));
    const selectLineBoundaryLeft = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, !ltrAtCursor(view)));
    const selectLineBoundaryRight = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, ltrAtCursor(view)));
    const selectLineStart = (view) => extendSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).from));
    const selectLineEnd = (view) => extendSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).to));
    const cursorDocStart = ({ state, dispatch }) => {
      dispatch(setSel(state, { anchor: 0 }));
      return true;
    };
    const cursorDocEnd = ({ state, dispatch }) => {
      dispatch(setSel(state, { anchor: state.doc.length }));
      return true;
    };
    const selectDocStart = ({ state, dispatch }) => {
      dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
      return true;
    };
    const selectDocEnd = ({ state, dispatch }) => {
      dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
      return true;
    };
    const selectAll = ({ state, dispatch }) => {
      dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" }));
      return true;
    };
    const selectLine = ({ state, dispatch }) => {
      let ranges = selectedLineBlocks(state).map(({ from, to: to2 }) => EditorSelection.range(from, Math.min(to2 + 1, state.doc.length)));
      dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
      return true;
    };
    const selectParentSyntax = ({ state, dispatch }) => {
      let selection = updateSel(state.selection, (range) => {
        let tree = syntaxTree(state), stack2 = tree.resolveStack(range.from, 1);
        if (range.empty) {
          let stackBefore = tree.resolveStack(range.from, -1);
          if (stackBefore.node.from >= stack2.node.from && stackBefore.node.to <= stack2.node.to)
            stack2 = stackBefore;
        }
        for (let cur2 = stack2; cur2; cur2 = cur2.next) {
          let { node: node2 } = cur2;
          if ((node2.from < range.from && node2.to >= range.to || node2.to > range.to && node2.from <= range.from) && cur2.next)
            return EditorSelection.range(node2.to, node2.from);
        }
        return range;
      });
      if (selection.eq(state.selection))
        return false;
      dispatch(setSel(state, selection));
      return true;
    };
    const simplifySelection = ({ state, dispatch }) => {
      let cur2 = state.selection, selection = null;
      if (cur2.ranges.length > 1)
        selection = EditorSelection.create([cur2.main]);
      else if (!cur2.main.empty)
        selection = EditorSelection.create([EditorSelection.cursor(cur2.main.head)]);
      if (!selection)
        return false;
      dispatch(setSel(state, selection));
      return true;
    };
    function deleteBy(target2, by) {
      if (target2.state.readOnly)
        return false;
      let event = "delete.selection", { state } = target2;
      let changes = state.changeByRange((range) => {
        let { from, to: to2 } = range;
        if (from == to2) {
          let towards = by(range);
          if (towards < from) {
            event = "delete.backward";
            towards = skipAtomic(target2, towards, false);
          } else if (towards > from) {
            event = "delete.forward";
            towards = skipAtomic(target2, towards, true);
          }
          from = Math.min(from, towards);
          to2 = Math.max(to2, towards);
        } else {
          from = skipAtomic(target2, from, false);
          to2 = skipAtomic(target2, to2, true);
        }
        return from == to2 ? { range } : { changes: { from, to: to2 }, range: EditorSelection.cursor(from, from < range.head ? -1 : 1) };
      });
      if (changes.changes.empty)
        return false;
      target2.dispatch(state.update(changes, {
        scrollIntoView: true,
        userEvent: event,
        effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : void 0
      }));
      return true;
    }
    function skipAtomic(target2, pos2, forward) {
      if (target2 instanceof EditorView)
        for (let ranges of target2.state.facet(EditorView.atomicRanges).map((f) => f(target2)))
          ranges.between(pos2, pos2, (from, to2) => {
            if (from < pos2 && to2 > pos2)
              pos2 = forward ? to2 : from;
          });
      return pos2;
    }
    const deleteByChar = (target2, forward, byIndentUnit) => deleteBy(target2, (range) => {
      let pos2 = range.from, { state } = target2, line2 = state.doc.lineAt(pos2), before, targetPos;
      if (byIndentUnit && !forward && pos2 > line2.from && pos2 < line2.from + 200 && !/[^ \t]/.test(before = line2.text.slice(0, pos2 - line2.from))) {
        if (before[before.length - 1] == "	")
          return pos2 - 1;
        let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);
        for (let i2 = 0; i2 < drop && before[before.length - 1 - i2] == " "; i2++)
          pos2--;
        targetPos = pos2;
      } else {
        targetPos = findClusterBreak(line2.text, pos2 - line2.from, forward, forward) + line2.from;
        if (targetPos == pos2 && line2.number != (forward ? state.doc.lines : 1))
          targetPos += forward ? 1 : -1;
        else if (!forward && /[\ufe00-\ufe0f]/.test(line2.text.slice(targetPos - line2.from, pos2 - line2.from)))
          targetPos = findClusterBreak(line2.text, targetPos - line2.from, false, false) + line2.from;
      }
      return targetPos;
    });
    const deleteCharBackward = (view) => deleteByChar(view, false, true);
    const deleteCharForward = (view) => deleteByChar(view, true, false);
    const deleteByGroup = (target2, forward) => deleteBy(target2, (range) => {
      let pos2 = range.head, { state } = target2, line2 = state.doc.lineAt(pos2);
      let categorize = state.charCategorizer(pos2);
      for (let cat = null; ; ) {
        if (pos2 == (forward ? line2.to : line2.from)) {
          if (pos2 == range.head && line2.number != (forward ? state.doc.lines : 1))
            pos2 += forward ? 1 : -1;
          break;
        }
        let next = findClusterBreak(line2.text, pos2 - line2.from, forward) + line2.from;
        let nextChar = line2.text.slice(Math.min(pos2, next) - line2.from, Math.max(pos2, next) - line2.from);
        let nextCat = categorize(nextChar);
        if (cat != null && nextCat != cat)
          break;
        if (nextChar != " " || pos2 != range.head)
          cat = nextCat;
        pos2 = next;
      }
      return pos2;
    });
    const deleteGroupBackward = (target2) => deleteByGroup(target2, false);
    const deleteGroupForward = (target2) => deleteByGroup(target2, true);
    const deleteToLineEnd = (view) => deleteBy(view, (range) => {
      let lineEnd = view.lineBlockAt(range.head).to;
      return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1);
    });
    const deleteLineBoundaryBackward = (view) => deleteBy(view, (range) => {
      let lineStart = view.moveToLineBoundary(range, false).head;
      return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);
    });
    const deleteLineBoundaryForward = (view) => deleteBy(view, (range) => {
      let lineStart = view.moveToLineBoundary(range, true).head;
      return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1);
    });
    const splitLine = ({ state, dispatch }) => {
      if (state.readOnly)
        return false;
      let changes = state.changeByRange((range) => {
        return {
          changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) },
          range: EditorSelection.cursor(range.from)
        };
      });
      dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
      return true;
    };
    const transposeChars = ({ state, dispatch }) => {
      if (state.readOnly)
        return false;
      let changes = state.changeByRange((range) => {
        if (!range.empty || range.from == 0 || range.from == state.doc.length)
          return { range };
        let pos2 = range.from, line2 = state.doc.lineAt(pos2);
        let from = pos2 == line2.from ? pos2 - 1 : findClusterBreak(line2.text, pos2 - line2.from, false) + line2.from;
        let to2 = pos2 == line2.to ? pos2 + 1 : findClusterBreak(line2.text, pos2 - line2.from, true) + line2.from;
        return {
          changes: { from, to: to2, insert: state.doc.slice(pos2, to2).append(state.doc.slice(from, pos2)) },
          range: EditorSelection.cursor(to2)
        };
      });
      if (changes.changes.empty)
        return false;
      dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
      return true;
    };
    function selectedLineBlocks(state) {
      let blocks = [], upto = -1;
      for (let range of state.selection.ranges) {
        let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to);
        if (!range.empty && range.to == endLine.from)
          endLine = state.doc.lineAt(range.to - 1);
        if (upto >= startLine.number) {
          let prev = blocks[blocks.length - 1];
          prev.to = endLine.to;
          prev.ranges.push(range);
        } else {
          blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] });
        }
        upto = endLine.number + 1;
      }
      return blocks;
    }
    function moveLine(state, dispatch, forward) {
      if (state.readOnly)
        return false;
      let changes = [], ranges = [];
      for (let block2 of selectedLineBlocks(state)) {
        if (forward ? block2.to == state.doc.length : block2.from == 0)
          continue;
        let nextLine = state.doc.lineAt(forward ? block2.to + 1 : block2.from - 1);
        let size = nextLine.length + 1;
        if (forward) {
          changes.push({ from: block2.to, to: nextLine.to }, { from: block2.from, insert: nextLine.text + state.lineBreak });
          for (let r2 of block2.ranges)
            ranges.push(EditorSelection.range(Math.min(state.doc.length, r2.anchor + size), Math.min(state.doc.length, r2.head + size)));
        } else {
          changes.push({ from: nextLine.from, to: block2.from }, { from: block2.to, insert: state.lineBreak + nextLine.text });
          for (let r2 of block2.ranges)
            ranges.push(EditorSelection.range(r2.anchor - size, r2.head - size));
        }
      }
      if (!changes.length)
        return false;
      dispatch(state.update({
        changes,
        scrollIntoView: true,
        selection: EditorSelection.create(ranges, state.selection.mainIndex),
        userEvent: "move.line"
      }));
      return true;
    }
    const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
    const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
    function copyLine(state, dispatch, forward) {
      if (state.readOnly)
        return false;
      let changes = [];
      for (let block2 of selectedLineBlocks(state)) {
        if (forward)
          changes.push({ from: block2.from, insert: state.doc.slice(block2.from, block2.to) + state.lineBreak });
        else
          changes.push({ from: block2.to, insert: state.lineBreak + state.doc.slice(block2.from, block2.to) });
      }
      dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" }));
      return true;
    }
    const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
    const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
    const deleteLine = (view) => {
      if (view.state.readOnly)
        return false;
      let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to: to2 }) => {
        if (from > 0)
          from--;
        else if (to2 < state.doc.length)
          to2++;
        return { from, to: to2 };
      }));
      let selection = updateSel(state.selection, (range) => {
        let dist2 = void 0;
        if (view.lineWrapping) {
          let block2 = view.lineBlockAt(range.head), pos2 = view.coordsAtPos(range.head, range.assoc || 1);
          if (pos2)
            dist2 = block2.bottom + view.documentTop - pos2.bottom + view.defaultLineHeight / 2;
        }
        return view.moveVertically(range, true, dist2);
      }).map(changes);
      view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" });
      return true;
    };
    function isBetweenBrackets(state, pos2) {
      if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos2 - 1, pos2 + 1)))
        return { from: pos2, to: pos2 };
      let context = syntaxTree(state).resolveInner(pos2);
      let before = context.childBefore(pos2), after = context.childAfter(pos2), closedBy;
      if (before && after && before.to <= pos2 && after.from >= pos2 && (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from && !/\S/.test(state.sliceDoc(before.to, after.from)))
        return { from: before.to, to: after.from };
      return null;
    }
    const insertNewlineAndIndent = /* @__PURE__ */ newlineAndIndent(false);
    const insertBlankLine = /* @__PURE__ */ newlineAndIndent(true);
    function newlineAndIndent(atEof) {
      return ({ state, dispatch }) => {
        if (state.readOnly)
          return false;
        let changes = state.changeByRange((range) => {
          let { from, to: to2 } = range, line2 = state.doc.lineAt(from);
          let explode = !atEof && from == to2 && isBetweenBrackets(state, from);
          if (atEof)
            from = to2 = (to2 <= line2.to ? line2 : state.doc.lineAt(to2)).to;
          let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });
          let indent = getIndentation(cx, from);
          if (indent == null)
            indent = countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);
          while (to2 < line2.to && /\s/.test(line2.text[to2 - line2.from]))
            to2++;
          if (explode)
            ({ from, to: to2 } = explode);
          else if (from > line2.from && from < line2.from + 100 && !/\S/.test(line2.text.slice(0, from)))
            from = line2.from;
          let insert2 = ["", indentString(state, indent)];
          if (explode)
            insert2.push(indentString(state, cx.lineIndent(line2.from, -1)));
          return {
            changes: { from, to: to2, insert: Text.of(insert2) },
            range: EditorSelection.cursor(from + 1 + insert2[1].length)
          };
        });
        dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
        return true;
      };
    }
    function changeBySelectedLine(state, f) {
      let atLine = -1;
      return state.changeByRange((range) => {
        let changes = [];
        for (let pos2 = range.from; pos2 <= range.to; ) {
          let line2 = state.doc.lineAt(pos2);
          if (line2.number > atLine && (range.empty || range.to > line2.from)) {
            f(line2, changes, range);
            atLine = line2.number;
          }
          pos2 = line2.to + 1;
        }
        let changeSet = state.changes(changes);
        return {
          changes,
          range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1))
        };
      });
    }
    const indentSelection = ({ state, dispatch }) => {
      if (state.readOnly)
        return false;
      let updated = /* @__PURE__ */ Object.create(null);
      let context = new IndentContext(state, { overrideIndentation: (start) => {
        let found = updated[start];
        return found == null ? -1 : found;
      } });
      let changes = changeBySelectedLine(state, (line2, changes2, range) => {
        let indent = getIndentation(context, line2.from);
        if (indent == null)
          return;
        if (!/\S/.test(line2.text))
          indent = 0;
        let cur2 = /^\s*/.exec(line2.text)[0];
        let norm = indentString(state, indent);
        if (cur2 != norm || range.from < line2.from + cur2.length) {
          updated[line2.from] = indent;
          changes2.push({ from: line2.from, to: line2.from + cur2.length, insert: norm });
        }
      });
      if (!changes.changes.empty)
        dispatch(state.update(changes, { userEvent: "indent" }));
      return true;
    };
    const indentMore = ({ state, dispatch }) => {
      if (state.readOnly)
        return false;
      dispatch(state.update(changeBySelectedLine(state, (line2, changes) => {
        changes.push({ from: line2.from, insert: state.facet(indentUnit) });
      }), { userEvent: "input.indent" }));
      return true;
    };
    const indentLess = ({ state, dispatch }) => {
      if (state.readOnly)
        return false;
      dispatch(state.update(changeBySelectedLine(state, (line2, changes) => {
        let space = /^\s*/.exec(line2.text)[0];
        if (!space)
          return;
        let col = countColumn(space, state.tabSize), keep = 0;
        let insert2 = indentString(state, Math.max(0, col - getIndentUnit(state)));
        while (keep < space.length && keep < insert2.length && space.charCodeAt(keep) == insert2.charCodeAt(keep))
          keep++;
        changes.push({ from: line2.from + keep, to: line2.from + space.length, insert: insert2.slice(keep) });
      }), { userEvent: "delete.dedent" }));
      return true;
    };
    const toggleTabFocusMode = (view) => {
      view.setTabFocusMode();
      return true;
    };
    const emacsStyleKeymap = [
      { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
      { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
      { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
      { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
      { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
      { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
      { key: "Ctrl-d", run: deleteCharForward },
      { key: "Ctrl-h", run: deleteCharBackward },
      { key: "Ctrl-k", run: deleteToLineEnd },
      { key: "Ctrl-Alt-h", run: deleteGroupBackward },
      { key: "Ctrl-o", run: splitLine },
      { key: "Ctrl-t", run: transposeChars },
      { key: "Ctrl-v", run: cursorPageDown }
    ];
    const standardKeymap = /* @__PURE__ */ [
      { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
      { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },
      { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },
      { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true },
      { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },
      { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },
      { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true },
      { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
      { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
      { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true },
      { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
      { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
      { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
      { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
      { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },
      { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
      { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },
      { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
      { key: "Enter", run: insertNewlineAndIndent, shift: insertNewlineAndIndent },
      { key: "Mod-a", run: selectAll },
      { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward },
      { key: "Delete", run: deleteCharForward },
      { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward },
      { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward },
      { mac: "Mod-Backspace", run: deleteLineBoundaryBackward },
      { mac: "Mod-Delete", run: deleteLineBoundaryForward }
    ].concat(/* @__PURE__ */ emacsStyleKeymap.map((b) => ({ mac: b.key, run: b.run, shift: b.shift })));
    const defaultKeymap = /* @__PURE__ */ [
      { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
      { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
      { key: "Alt-ArrowUp", run: moveLineUp },
      { key: "Shift-Alt-ArrowUp", run: copyLineUp },
      { key: "Alt-ArrowDown", run: moveLineDown },
      { key: "Shift-Alt-ArrowDown", run: copyLineDown },
      { key: "Escape", run: simplifySelection },
      { key: "Mod-Enter", run: insertBlankLine },
      { key: "Alt-l", mac: "Ctrl-l", run: selectLine },
      { key: "Mod-i", run: selectParentSyntax, preventDefault: true },
      { key: "Mod-[", run: indentLess },
      { key: "Mod-]", run: indentMore },
      { key: "Mod-Alt-\\", run: indentSelection },
      { key: "Shift-Mod-k", run: deleteLine },
      { key: "Shift-Mod-\\", run: cursorMatchingBracket },
      { key: "Mod-/", run: toggleComment },
      { key: "Alt-A", run: toggleBlockComment },
      { key: "Ctrl-m", mac: "Shift-Alt-m", run: toggleTabFocusMode }
    ].concat(standardKeymap);
    const minimalSetup = /* @__PURE__ */ (() => [
      highlightSpecialChars(),
      history(),
      drawSelection(),
      syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
      keymap.of([
        ...defaultKeymap,
        ...historyKeymap
      ])
    ])();
    const KEYWORDS = ["and", "or", "not", "in", "not in", "mod"];
    const MATH_FUNCTIONS = [
      ["min", "Minimum of two or more values"],
      ["max", "Maximum of two or more values"],
      ["abs", "Absolute value"],
      ["round", "Round to the nearest integer"],
      ["floor", "Round down to the nearest integer"],
      ["ceil", "Round up to the nearest integer"],
      ["sqrt", "Square root"],
      ["log", "Natural logarithm"],
      ["log2", "Base 2 logarithm"],
      ["log10", "Base 10 logarithm"]
    ];
    const SAMPLE_VARIABLES = [
      ["has_error", "Checks if the sample has an error"]
    ];
    const SAMPLE_FUNCTIONS = [
      ["input_contains", "Checks if input contains a regular expression"],
      ["target_contains", "Checks if target contains a regular expression"],
      ["error_contains", "Checks if error contains a regular expression"]
    ];
    const TOKEN_PATTERNS = {
      STRING: /^"[^"]*"/,
      UNTERMINATED_STRING: /^"[^"]*/,
      NUMBER: /^(-|\+)?\d+(\.\d+)?/,
      RELATION: /^(==|!=|<=|>=|<|>|~=)/,
      MISC_OPERATOR: /^(=|!|~)/,
      OPERATOR: /^(\+|-|\*|\/|\^|\(|\)|,|\.)/,
      VARIABLE: /^[a-zA-Z_][a-zA-Z0-9_]*/
    };
    const createWordRegex = (words) => new RegExp(`^(${words.join("|")})\\b`);
    const countSpaces = (word) => word.split(" ").length - 1;
    const mathFunctionsRegex = createWordRegex(
      MATH_FUNCTIONS.map(([label2]) => label2)
    );
    const sampleFunctionsRegex = createWordRegex(
      SAMPLE_FUNCTIONS.map(([label2]) => label2)
    );
    const keywordsRegex = createWordRegex(
      // Ensure 'not in' matches first
      KEYWORDS.sort((a, b) => countSpaces(b) - countSpaces(a))
    );
    function nextToken(stream) {
      if (stream.match(TOKEN_PATTERNS.STRING)) return "string";
      if (stream.match(TOKEN_PATTERNS.UNTERMINATED_STRING))
        return "unterminatedString";
      if (stream.match(TOKEN_PATTERNS.NUMBER)) return "number";
      if (stream.match(keywordsRegex)) return "keyword";
      if (stream.match(mathFunctionsRegex)) return "mathFunction";
      if (stream.match(sampleFunctionsRegex)) return "sampleFunction";
      if (stream.match(TOKEN_PATTERNS.VARIABLE)) return "variable";
      if (stream.match(TOKEN_PATTERNS.RELATION)) return "relation";
      if (stream.match(TOKEN_PATTERNS.MISC_OPERATOR)) return "miscOperator";
      if (stream.match(TOKEN_PATTERNS.OPERATOR)) return "miscOperator";
      stream.next();
      return null;
    }
    function tokenize(input2) {
      const tokens = [];
      const stream = new StringStream(input2, 0, 0);
      while (stream.pos < input2.length) {
        const from = stream.pos;
        const type = nextToken(stream);
        if (type) {
          tokens.push({
            type,
            text: input2.slice(from, stream.pos),
            from,
            to: stream.pos
          });
        }
      }
      return tokens;
    }
    const language = StreamLanguage.define({
      token: nextToken,
      tokenTable: {
        string: tags.string,
        unterminatedString: tags.string,
        number: tags.number,
        keyword: tags.keyword,
        mathFunction: tags.function(tags.variableName),
        sampleFunction: tags.function(tags.variableName),
        variable: tags.variableName,
        relation: tags.operator,
        miscOperator: tags.operator
      }
    });
    const isLiteral = (token2) => ["string", "unterminatedString", "number"].includes(token2 == null ? void 0 : token2.type);
    const isLogicalOp = (token2) => ["and", "or", "not"].includes(token2 == null ? void 0 : token2.text);
    const autocompleteImmediatelyAfter = (token2) => ["(", "."].includes(token2 == null ? void 0 : token2.text);
    const applyWithCall = (view, completion, from, to2) => {
      view.dispatch({
        changes: { from, to: to2, insert: `${completion.label}()` },
        selection: { anchor: from + completion.label.length + 1 }
      });
    };
    const makeKeywordCompletion = (k) => ({
      label: k,
      type: "keyword",
      boost: -20
    });
    const makeMathFunctionCompletion = ([label2, info]) => ({
      label: label2,
      type: "function",
      info,
      apply: applyWithCall,
      boost: -10
    });
    const makeSampleFunctionCompletion = ([label2, info]) => ({
      label: label2,
      type: "function",
      info,
      apply: applyWithCall,
      boost: 0
    });
    const makeSampleVariableCompletion = ([label2, info]) => ({
      label: label2,
      type: "variable",
      info,
      boost: 10
    });
    const makeLiteralCompletion = (k) => ({
      label: k,
      type: "text",
      boost: 20
    });
    const makeCanonicalNameCompletion = (item2, { autoSpaceIf = () => false } = {}) => ({
      label: item2.canonicalName + (autoSpaceIf(item2) ? " " : ""),
      type: "variable",
      info: item2.tooltip,
      boost: 30
    });
    const makeMemberAccessCompletion = (item2) => {
      var _a2;
      return {
        label: ((_a2 = item2.qualifiedName) == null ? void 0 : _a2.split(".")[1]) || "",
        type: "variable",
        info: item2.tooltip,
        boost: 40
      };
    };
    const getMemberScoreItems = (filterItems, scorer) => filterItems.filter((item2) => {
      var _a2;
      return (_a2 = item2 == null ? void 0 : item2.qualifiedName) == null ? void 0 : _a2.startsWith(`${scorer}.`);
    });
    function getCompletions(context, filterItems) {
      var _a2, _b2, _c, _d, _e2, _f, _g, _h, _i, _j, _k;
      const keywordCompletionItems = KEYWORDS.map(makeKeywordCompletion);
      const mathFunctionCompletionItems = MATH_FUNCTIONS.map(
        makeMathFunctionCompletion
      );
      const sampleFunctionCompletionItems = SAMPLE_FUNCTIONS.map(
        makeSampleFunctionCompletion
      );
      const sampleVariableCompletionItems = SAMPLE_VARIABLES.map(
        makeSampleVariableCompletion
      );
      const variableCompletionItems = filterItems.map(
        (item2) => makeCanonicalNameCompletion(item2)
      );
      const defaultCompletionItems = [
        ...keywordCompletionItems,
        ...mathFunctionCompletionItems,
        ...sampleFunctionCompletionItems,
        ...sampleVariableCompletionItems,
        ...variableCompletionItems
      ];
      const doc2 = context.state.doc;
      const input2 = doc2.toString().slice(0, context.pos);
      const tokens = tokenize(input2);
      const lastToken = tokens[tokens.length - 1];
      const isCompletionInsideToken = lastToken && context.pos === lastToken.to && !autocompleteImmediatelyAfter(lastToken);
      const currentTokenIndex = isCompletionInsideToken ? tokens.length - 1 : tokens.length;
      const prevToken = (index2) => tokens[currentTokenIndex - index2];
      const currentToken = prevToken(0);
      const completionStart = currentToken ? currentToken.from : context.pos;
      const completingAtEnd = context.pos === doc2.length;
      const findFilterItem = (endIndex) => {
        var _a3, _b3, _c2;
        if (((_a3 = prevToken(endIndex)) == null ? void 0 : _a3.type) !== "variable") return void 0;
        let name2 = prevToken(endIndex).text;
        let i2 = endIndex;
        while (((_b3 = prevToken(i2 + 1)) == null ? void 0 : _b3.text) === ".") {
          if (((_c2 = prevToken(i2 + 2)) == null ? void 0 : _c2.type) === "variable") {
            name2 = `${prevToken(i2 + 2).text}.${name2}`;
            i2 += 2;
          } else {
            break;
          }
        }
        return filterItems.find((item2) => item2.canonicalName === name2);
      };
      const makeCompletions = (priorityCompletions, {
        autocompleteInTheMiddle = false,
        enforceOrder = false,
        autoSpaceAfter = false,
        includeDefault = true
      } = {}) => {
        if (!autocompleteInTheMiddle && !completingAtEnd && !context.explicit) {
          return null;
        }
        const priorityCompletionsOrdered = enforceOrder ? priorityCompletions.map((c2, idx) => ({ ...c2, boost: -idx })) : priorityCompletions;
        const priorityCompletionsAdjusted = autoSpaceAfter ? priorityCompletionsOrdered.map(
          (c2) => !c2.apply && !c2.label.endsWith(" ") ? { ...c2, label: `${c2.label} ` } : c2
        ) : priorityCompletionsOrdered;
        if (!includeDefault) {
          return {
            from: completionStart,
            options: priorityCompletionsAdjusted
          };
        }
        const miscSection = {
          name: "misc",
          header: () => {
            const element = document.createElement("hr");
            element.style.display = "list-item";
            element.style.margin = "2px 0";
            return element;
          }
        };
        const priorityLabels = new Set(
          priorityCompletions.map((c2) => c2.label.trim())
        );
        const defaultCompletionsAdjusted = defaultCompletionItems.filter((c2) => !priorityLabels.has(c2.label.trim())).map((c2) => ({ ...c2, section: miscSection }));
        return {
          from: completionStart,
          options: [...priorityCompletionsAdjusted, ...defaultCompletionsAdjusted]
        };
      };
      const defaultCompletions = () => makeCompletions([]);
      const noCompletions = () => context.explicit ? defaultCompletions() : null;
      const newExpressionCompletions = () => makeCompletions([
        ...filterItems.map(
          (item2) => makeCanonicalNameCompletion(item2, {
            autoSpaceIf: (item22) => completingAtEnd && item22.scoreType !== kScoreTypeBoolean
          })
        ),
        ...sampleVariableCompletionItems,
        ...sampleFunctionCompletionItems
      ]);
      const variableCompletions = () => makeCompletions(variableCompletionItems);
      const memberAccessCompletions = (items) => makeCompletions(items.map(makeMemberAccessCompletion), {
        autocompleteInTheMiddle: true,
        includeDefault: false
      });
      const logicalOpCompletions = () => makeCompletions(["and", "or"].map(makeKeywordCompletion), {
        enforceOrder: true,
        autoSpaceAfter: completingAtEnd
      });
      const descreteRelationCompletions = () => makeCompletions(["==", "!=", "in", "not in"].map(makeKeywordCompletion), {
        enforceOrder: true,
        autoSpaceAfter: completingAtEnd
      });
      const continuousRelationCompletions = () => makeCompletions(
        ["<", "<=", ">", ">=", "==", "!="].map(makeKeywordCompletion),
        { enforceOrder: true, autoSpaceAfter: completingAtEnd }
      );
      const customRelationCompletions = () => makeCompletions(
        ["<", "<=", ">", ">=", "==", "!=", "~="].map(makeKeywordCompletion),
        { enforceOrder: true, autoSpaceAfter: completingAtEnd }
      );
      const rhsCompletions = (options2) => makeCompletions(options2.map(makeLiteralCompletion));
      if (!prevToken(1)) return newExpressionCompletions();
      if (((_a2 = prevToken(1)) == null ? void 0 : _a2.text) === ".") {
        const scorer = (_b2 = prevToken(2)) == null ? void 0 : _b2.text;
        if (scorer) {
          return memberAccessCompletions(getMemberScoreItems(filterItems, scorer));
        }
      }
      if (((_c = prevToken(1)) == null ? void 0 : _c.text) === "(") {
        if (((_d = prevToken(2)) == null ? void 0 : _d.type) === "mathFunction") return variableCompletions();
        if (((_e2 = prevToken(2)) == null ? void 0 : _e2.type) === "sampleFunction") return noCompletions();
        return newExpressionCompletions();
      }
      if (((_f = prevToken(1)) == null ? void 0 : _f.text) === ")") return noCompletions();
      if (((_g = prevToken(1)) == null ? void 0 : _g.type) === "variable") {
        const scoreType = ((_h = findFilterItem(1)) == null ? void 0 : _h.scoreType) || "";
        switch (scoreType) {
          case kScoreTypePassFail:
          case kScoreTypeCategorical:
            return descreteRelationCompletions();
          case kScoreTypeNumeric:
            return continuousRelationCompletions();
          case kScoreTypeOther:
            return customRelationCompletions();
          case kScoreTypeBoolean:
            return logicalOpCompletions();
          default:
            return noCompletions();
        }
      }
      if (((_i = prevToken(1)) == null ? void 0 : _i.type) === "relation") {
        const item2 = findFilterItem(2);
        if ((_j = item2 == null ? void 0 : item2.categories) == null ? void 0 : _j.length) {
          return rhsCompletions(item2.categories);
        }
        return variableCompletions();
      }
      if (isLiteral(prevToken(1)) && ((_k = prevToken(2)) == null ? void 0 : _k.type) === "relation") {
        return logicalOpCompletions();
      }
      if (isLogicalOp(prevToken(1))) return newExpressionCompletions();
      return noCompletions();
    }
    const label$3 = "_label_jbrqc_1";
    const input = "_input_jbrqc_7";
    const help = "_help_jbrqc_11";
    const styles$N = {
      label: label$3,
      input,
      help
    };
    const FILTER_TOOLTIP = `
Filter samples by:
  • Scores
  • Samples with errors: has_error
  • Input, target and error regex search: input_contains, target_contains, error_contains

Supported expressions:
  • Arithmetic: +, -, *, /, mod, ^
  • Comparison: <, <=, >, >=, ==, !=, including chain comparisons, e.g. "10 <= x < 20"
  • Boolean: and, or, not
  • Regex matching: ~= (case-sensitive)
  • Set operations: in, not in; e.g. "x in (2, 3, 5)"
  • Functions: min, max, abs, round, floor, ceil, sqrt, log, log2, log10
`.trim();
    const highlightStyle = HighlightStyle.define([
      { tag: tags.string, class: "token string" },
      { tag: tags.number, class: "token number" },
      { tag: tags.keyword, class: "token keyword" }
    ]);
    const editorTheme = EditorView.theme({
      "&": {
        fontSize: "inherit",
        color: "var(--inspect-input-foreground)",
        backgroundColor: "var(--inspect-input-background)",
        border: "1px solid var(--inspect-input-border)",
        borderRadius: "var(--bs-border-radius)"
      },
      ".cm-cursor.cm-cursor-primary": {
        borderLeftColor: "var(--bs-body-color)"
      },
      ".cm-selectionBackground": {
        backgroundColor: "var(--inspect-inactive-selection-background)"
      },
      "&.cm-focused > .cm-scroller > .cm-selectionLayer > .cm-selectionBackground": {
        backgroundColor: "var(--inspect-active-selection-background)"
      },
      "&.cm-focused": {
        outline: "none",
        borderColor: "var(--inspect-focus-border-color)",
        boxShadow: "var(--inspect-focus-border-shadow)"
      },
      ".filter-pending > &.cm-focused": {
        borderColor: "var(--inspect-focus-border-gray-color)",
        boxShadow: "var(--inspect-focus-border-gray-shadow)"
      },
      ".cm-tooltip": {
        backgroundColor: "var(--bs-light)",
        border: "1px solid var(--bs-border-color)",
        color: "var(--bs-body-color)"
      },
      ".cm-tooltip.cm-tooltip-autocomplete > ul > li": {
        color: "var(--bs-body-color)"
      },
      ".cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]": {
        backgroundColor: "var(--inspect-active-selection-background)",
        color: "var(--bs-body-color)"
      },
      ".cm-scroller": {
        overflow: "hidden"
      }
    });
    const getFilteringResult = (evalDescriptor, filterValue) => {
      const { result: result2, error: error2 } = filterSamples(
        evalDescriptor,
        evalDescriptor.samples,
        filterValue
      );
      return { numSamples: result2.length, error: error2 };
    };
    const ensureOneLine = (tr2) => {
      const newDoc = tr2.newDoc.toString();
      if (!newDoc.includes("\n")) return tr2;
      if (tr2.isUserEvent("input.paste")) {
        return {
          changes: {
            from: 0,
            to: tr2.startState.doc.length,
            insert: newDoc.replace(/\n/g, " ").trim()
          }
        };
      }
      return {};
    };
    const getLints = (view, filterError) => {
      if (!filterError) return [];
      return [
        {
          from: Math.min(filterError.from || 0, view.state.doc.length),
          to: Math.min(
            filterError.to || view.state.doc.length,
            view.state.doc.length
          ),
          severity: filterError.severity,
          message: filterError.message
        }
      ];
    };
    const SampleFilter = ({
      evalDescriptor,
      scoreFilter,
      setScoreFilter
    }) => {
      const editorRef = reactExports.useRef(null);
      const editorViewRef = reactExports.useRef(null);
      const linterCompartment = reactExports.useRef(new Compartment());
      const autocompletionCompartment = reactExports.useRef(new Compartment());
      const updateListenerCompartment = reactExports.useRef(new Compartment());
      const filterItems = reactExports.useMemo(
        () => scoreFilterItems(evalDescriptor),
        [evalDescriptor]
      );
      const [filteringResultInstant, setFilteringResultInstant] = reactExports.useState(null);
      const handleFocus = (event, view) => {
        if (event.isTrusted && view.state.doc.toString() === "") {
          setTimeout(() => startCompletion(view), 0);
        }
      };
      const makeAutocompletion = () => autocompletion({
        override: [(context) => getCompletions(context, filterItems)],
        activateOnCompletion: (c2) => c2.label.endsWith(" ")
      });
      const makeLinter = () => linter((view) => getLints(view, filteringResultInstant == null ? void 0 : filteringResultInstant.error));
      const makeUpdateListener = () => EditorView.updateListener.of((update) => {
        if (update.docChanged) {
          const newValue = update.state.doc.toString();
          const filteringResult = getFilteringResult(evalDescriptor, newValue);
          if (!filteringResult.error) {
            setScoreFilter({ value: newValue });
          }
          setFilteringResultInstant(filteringResult);
        }
      });
      reactExports.useEffect(() => {
        var _a2;
        (_a2 = editorViewRef.current) == null ? void 0 : _a2.destroy();
        editorViewRef.current = new EditorView({
          parent: editorRef.current ?? void 0,
          state: EditorState.create({
            doc: scoreFilter.value || "",
            extensions: [
              minimalSetup,
              bracketMatching(),
              editorTheme,
              EditorState.transactionFilter.of(ensureOneLine),
              updateListenerCompartment.current.of(makeUpdateListener()),
              EditorView.domEventHandlers({ focus: handleFocus }),
              language,
              syntaxHighlighting(highlightStyle),
              autocompletionCompartment.current.of(makeAutocompletion()),
              linterCompartment.current.of(makeLinter())
            ]
          })
        });
        return () => {
          var _a3;
          return (_a3 = editorViewRef.current) == null ? void 0 : _a3.destroy();
        };
      }, []);
      reactExports.useEffect(() => {
        if (!editorViewRef.current) return;
        const currentValue = editorViewRef.current.state.doc.toString();
        if (scoreFilter.value === currentValue) return;
        setFilteringResultInstant(
          getFilteringResult(evalDescriptor, scoreFilter.value || "")
        );
        editorViewRef.current.dispatch({
          changes: {
            from: 0,
            to: currentValue.length,
            insert: scoreFilter.value || ""
          }
        });
      }, [evalDescriptor, scoreFilter.value]);
      reactExports.useEffect(() => {
        var _a2;
        (_a2 = editorViewRef.current) == null ? void 0 : _a2.dispatch({
          effects: updateListenerCompartment.current.reconfigure(makeUpdateListener())
        });
      }, [evalDescriptor]);
      reactExports.useEffect(() => {
        var _a2;
        (_a2 = editorViewRef.current) == null ? void 0 : _a2.dispatch({
          effects: autocompletionCompartment.current.reconfigure(makeAutocompletion())
        });
      }, [filterItems]);
      reactExports.useEffect(() => {
        var _a2;
        (_a2 = editorViewRef.current) == null ? void 0 : _a2.dispatch({
          effects: linterCompartment.current.reconfigure(makeLinter())
        });
      }, [filteringResultInstant == null ? void 0 : filteringResultInstant.error]);
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { display: "flex" }, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: clsx(
              "sample-filter-label",
              "text-size-smaller",
              "text-style-label",
              "text-style-secondary",
              styles$N.label
            ),
            children: "Filter:"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            ref: editorRef,
            className: clsx(
              (filteringResultInstant == null ? void 0 : filteringResultInstant.error) && "filter-pending",
              styles$N.input
            )
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: clsx("bi", "bi-question-circle", styles$N.help),
            "data-tooltip": FILTER_TOOLTIP,
            "data-tooltip-position": "bottom-left"
          }
        )
      ] });
    };
    const flex = "_flex_anstf_1";
    const label$2 = "_label_anstf_5";
    const secondSel = "_secondSel_anstf_9";
    const secondLabel = "_secondLabel_anstf_13";
    const styles$M = {
      flex,
      label: label$2,
      secondSel,
      secondLabel
    };
    const SelectScorer = ({
      scores: scores2,
      score: score2,
      setScore
    }) => {
      const scorers = scores2.reduce((accum, scorer) => {
        if (!accum.find((sc) => {
          return scorer.scorer === sc.scorer;
        })) {
          accum.push(scorer);
        }
        return accum;
      }, []);
      if (scorers.length === 1) {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$M.flex, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: clsx(
                "select-scorer-label",
                "text-size-smaller",
                "text-style-label",
                "text-style-secondary",
                styles$M.label
              ),
              children: "Score:"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ScoreSelector,
            {
              scores: scores2,
              selectedIndex: scoreIndex(scores2, score2),
              setSelectedIndex: (index2) => {
                setScore(scores2[index2]);
              }
            }
          )
        ] });
      } else {
        const scorerScores = scores2.filter((sc) => {
          return score2 && sc.scorer === score2.scorer;
        });
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$M.flex, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: clsx(
                "select-scorer-label",
                "text-size-smaller",
                "text-style-label",
                "text-style-secondary",
                styles$M.label,
                styles$M.secondLabel
              ),
              children: "Scorer:"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ScorerSelector,
            {
              scorers,
              selectedIndex: scorerIndex(scorers, score2),
              setSelectedIndex: (index2) => {
                setScore(scorers[index2]);
              }
            }
          ),
          scorerScores.length > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            ScoreSelector,
            {
              className: clsx(styles$M.secondSel),
              scores: scorerScores,
              selectedIndex: scoreIndex(scorerScores, score2),
              setSelectedIndex: (index2) => {
                setScore(scorerScores[index2]);
              }
            }
          ) : void 0
        ] });
      }
    };
    const ScoreSelector = ({
      scores: scores2,
      selectedIndex,
      setSelectedIndex,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "select",
        {
          className: clsx(
            "form-select",
            "form-select-sm",
            "text-size-smaller",
            className2
          ),
          "aria-label": ".select-scorer-label",
          value: scores2[selectedIndex].name,
          onChange: (e) => {
            const sel = e.target;
            setSelectedIndex(sel.selectedIndex);
          },
          children: scores2.map((score2) => {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: score2.name, children: score2.name }, score2.name);
          })
        }
      );
    };
    const ScorerSelector = ({
      scorers,
      selectedIndex,
      setSelectedIndex
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "select",
        {
          className: clsx("form-select", "form-select-sm", "text-size-smaller"),
          "aria-label": ".epoch-filter-label",
          value: scorers[selectedIndex].scorer,
          onChange: (e) => {
            const sel = e.target;
            setSelectedIndex(sel.selectedIndex);
          },
          children: scorers.map((scorer) => {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: scorer.scorer, children: scorer.scorer }, scorer.scorer);
          })
        }
      );
    };
    const scoreIndex = (scores2, score2) => scores2.findIndex((sc) => {
      return score2 && sc.name === score2.name && sc.scorer === score2.scorer;
    });
    const scorerIndex = (scores2, score2) => scores2.findIndex((sc) => {
      return score2 && sc.scorer === score2.scorer;
    });
    const SampleTools = ({
      epoch,
      setEpoch,
      epochs,
      scoreFilter,
      setScoreFilter,
      sort,
      setSort,
      score: score2,
      setScore,
      scores: scores2,
      sampleDescriptor
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SampleFilter,
          {
            evalDescriptor: sampleDescriptor.evalDescriptor,
            scoreFilter,
            setScoreFilter
          }
        ),
        scores2.length > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(SelectScorer, { scores: scores2, score: score2, setScore }) : void 0,
        epochs > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(EpochFilter, { epoch, setEpoch, epochs }) : void 0,
        /* @__PURE__ */ jsxRuntimeExports.jsx(SortFilter, { sort, setSort, epochs })
      ] });
    };
    const filename = (path) => {
      const pathparts = path.split("/");
      const basename = pathparts.slice(-1)[0];
      const match = basename.match(/(.*)\.\S+$/);
      if (match) {
        return match[1];
      } else {
        return path;
      }
    };
    const dirname = (path) => {
      const pathparts = path.split("/");
      if (pathparts.length > 1) {
        pathparts.pop();
      }
      return pathparts.join("/");
    };
    const asyncJsonParse = async (text2) => {
      const encoder = new TextEncoder();
      const encodedText = encoder.encode(text2);
      const blob = new Blob([kWorkerCode], { type: "application/javascript" });
      const blobURL = URL.createObjectURL(blob);
      const worker = new Worker(blobURL);
      try {
        const result2 = new Promise((resolve, reject) => {
          worker.onmessage = function(e) {
            if (e.data.success) {
              resolve(e.data.result);
            } else {
              reject(new Error(e.data.error));
            }
          };
          worker.onerror = function(error2) {
            reject(new Error(error2.message));
          };
        });
        worker.postMessage({ scriptContent: kJson5ScriptBase64, encodedText }, [
          encodedText.buffer
        ]);
        return await result2;
      } finally {
        worker.terminate();
        URL.revokeObjectURL(blobURL);
      }
    };
    const kWorkerCode = `
self.onmessage = function (e) {
  eval(atob(e.data.scriptContent));
  const { encodedText } = e.data;
  const decoder = new TextDecoder();
  const text = decoder.decode(encodedText);
  try {
    const result = JSON.parse(text);
    postMessage({ success: true, result });
  } catch (err) {
    postMessage({ success: false, error: err.message });
  }
};`;
    const kJson5ScriptBase64 = ` `;
    async function download_file$1(filename2, filecontents) {
      const blob = new Blob([filecontents], { type: "text/plain" });
      const link2 = document.createElement("a");
      link2.href = URL.createObjectURL(blob);
      link2.download = filename2;
      document.body.appendChild(link2);
      link2.click();
      document.body.removeChild(link2);
    }
    function encodePathParts(url) {
      if (!url) return url;
      try {
        const fullUrl = new URL(url);
        fullUrl.pathname = fullUrl.pathname.split("/").map(
          (segment) => segment ? encodeURIComponent(decodeURIComponent(segment)) : ""
        ).join("/");
        return fullUrl.toString();
      } catch {
        return url.split("/").map(
          (segment) => segment ? encodeURIComponent(decodeURIComponent(segment)) : ""
        ).join("/");
      }
    }
    const loaded_time = Date.now();
    let last_eval_time = 0;
    async function client_events$1() {
      const params2 = new URLSearchParams();
      params2.append("loaded_time", String(loaded_time.valueOf()));
      params2.append("last_eval_time", String(last_eval_time.valueOf()));
      return (await api$2("GET", `/api/events?${params2.toString()}`)).parsed;
    }
    async function eval_logs$1() {
      const logs = await api$2("GET", `/api/logs`);
      last_eval_time = Date.now();
      return logs.parsed;
    }
    async function eval_log$1(file, headerOnly, _capabilities) {
      return await api$2(
        "GET",
        `/api/logs/${encodeURIComponent(file)}?header-only=${headerOnly}`
      );
    }
    async function eval_log_size$1(file) {
      return (await api$2("GET", `/api/log-size/${encodeURIComponent(file)}`)).parsed;
    }
    async function eval_log_bytes$1(file, start, end) {
      return await api_bytes(
        "GET",
        `/api/log-bytes/${encodeURIComponent(file)}?start=${start}&end=${end}`
      );
    }
    async function eval_log_headers$1(files) {
      const params2 = new URLSearchParams();
      for (const file of files) {
        params2.append("file", file);
      }
      return (await api$2("GET", `/api/log-headers?${params2.toString()}`)).parsed;
    }
    async function api$2(method, path, body2) {
      const headers = {
        Accept: "application/json",
        Pragma: "no-cache",
        Expires: "0",
        ["Cache-Control"]: "no-cache"
      };
      const response = await fetch(`${path}`, { method, headers, body: body2 });
      if (response.ok) {
        const text2 = await response.text();
        return {
          parsed: await asyncJsonParse(text2),
          raw: text2
        };
      } else if (response.status !== 200) {
        const message2 = await response.text() || response.statusText;
        const error2 = new Error(`Error: ${response.status}: ${message2})`);
        throw error2;
      } else {
        throw new Error(`${response.status} - ${response.statusText} `);
      }
    }
    async function api_bytes(method, path) {
      const headers = {
        Accept: "application/octet-stream",
        Pragma: "no-cache",
        Expires: "0",
        ["Cache-Control"]: "no-cache"
      };
      const response = await fetch(`${path}`, { method, headers });
      if (response.ok) {
        const buffer2 = await response.arrayBuffer();
        return new Uint8Array(buffer2);
      } else if (response.status !== 200) {
        const message2 = await response.text() || response.statusText;
        const error2 = new Error(`Error: ${response.status}: ${message2})`);
        throw error2;
      } else {
        throw new Error(`${response.status} - ${response.statusText} `);
      }
    }
    async function open_log_file$1() {
    }
    const browserApi = {
      client_events: client_events$1,
      eval_logs: eval_logs$1,
      eval_log: eval_log$1,
      eval_log_size: eval_log_size$1,
      eval_log_bytes: eval_log_bytes$1,
      eval_log_headers: eval_log_headers$1,
      download_file: download_file$1,
      open_log_file: open_log_file$1
    };
    var ch2 = {};
    var wk = function(c2, id, msg, transfer, cb) {
      var w2 = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([
        c2 + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'
      ], { type: "text/javascript" }))));
      w2.onmessage = function(e) {
        var d = e.data, ed = d.$e$;
        if (ed) {
          var err2 = new Error(ed[0]);
          err2["code"] = ed[1];
          err2.stack = ed[2];
          cb(err2, null);
        } else
          cb(null, d);
      };
      w2.postMessage(msg, transfer);
      return w2;
    };
    var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
    var fleb = new u8([
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      1,
      1,
      1,
      2,
      2,
      2,
      2,
      3,
      3,
      3,
      3,
      4,
      4,
      4,
      4,
      5,
      5,
      5,
      5,
      0,
      /* unused */
      0,
      0,
      /* impossible */
      0
    ]);
    var fdeb = new u8([
      0,
      0,
      0,
      0,
      1,
      1,
      2,
      2,
      3,
      3,
      4,
      4,
      5,
      5,
      6,
      6,
      7,
      7,
      8,
      8,
      9,
      9,
      10,
      10,
      11,
      11,
      12,
      12,
      13,
      13,
      /* unused */
      0,
      0
    ]);
    var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
    var freb = function(eb, start) {
      var b = new u16(31);
      for (var i2 = 0; i2 < 31; ++i2) {
        b[i2] = start += 1 << eb[i2 - 1];
      }
      var r2 = new i32(b[30]);
      for (var i2 = 1; i2 < 30; ++i2) {
        for (var j2 = b[i2]; j2 < b[i2 + 1]; ++j2) {
          r2[j2] = j2 - b[i2] << 5 | i2;
        }
      }
      return { b, r: r2 };
    };
    var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
    fl[28] = 258, revfl[258] = 28;
    var _b = freb(fdeb, 0), fd = _b.b;
    var rev = new u16(32768);
    for (var i = 0; i < 32768; ++i) {
      var x$1 = (i & 43690) >> 1 | (i & 21845) << 1;
      x$1 = (x$1 & 52428) >> 2 | (x$1 & 13107) << 2;
      x$1 = (x$1 & 61680) >> 4 | (x$1 & 3855) << 4;
      rev[i] = ((x$1 & 65280) >> 8 | (x$1 & 255) << 8) >> 1;
    }
    var hMap = function(cd, mb, r2) {
      var s = cd.length;
      var i2 = 0;
      var l = new u16(mb);
      for (; i2 < s; ++i2) {
        if (cd[i2])
          ++l[cd[i2] - 1];
      }
      var le2 = new u16(mb);
      for (i2 = 1; i2 < mb; ++i2) {
        le2[i2] = le2[i2 - 1] + l[i2 - 1] << 1;
      }
      var co2;
      if (r2) {
        co2 = new u16(1 << mb);
        var rvb = 15 - mb;
        for (i2 = 0; i2 < s; ++i2) {
          if (cd[i2]) {
            var sv = i2 << 4 | cd[i2];
            var r_1 = mb - cd[i2];
            var v = le2[cd[i2] - 1]++ << r_1;
            for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
              co2[rev[v] >> rvb] = sv;
            }
          }
        }
      } else {
        co2 = new u16(s);
        for (i2 = 0; i2 < s; ++i2) {
          if (cd[i2]) {
            co2[i2] = rev[le2[cd[i2] - 1]++] >> 15 - cd[i2];
          }
        }
      }
      return co2;
    };
    var flt = new u8(288);
    for (var i = 0; i < 144; ++i)
      flt[i] = 8;
    for (var i = 144; i < 256; ++i)
      flt[i] = 9;
    for (var i = 256; i < 280; ++i)
      flt[i] = 7;
    for (var i = 280; i < 288; ++i)
      flt[i] = 8;
    var fdt = new u8(32);
    for (var i = 0; i < 32; ++i)
      fdt[i] = 5;
    var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
    var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
    var max$1 = function(a) {
      var m = a[0];
      for (var i2 = 1; i2 < a.length; ++i2) {
        if (a[i2] > m)
          m = a[i2];
      }
      return m;
    };
    var bits = function(d, p, m) {
      var o = p / 8 | 0;
      return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
    };
    var bits16 = function(d, p) {
      var o = p / 8 | 0;
      return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
    };
    var shft = function(p) {
      return (p + 7) / 8 | 0;
    };
    var slc = function(v, s, e) {
      if (s == null || s < 0)
        s = 0;
      if (e == null || e > v.length)
        e = v.length;
      return new u8(v.subarray(s, e));
    };
    var ec = [
      "unexpected EOF",
      "invalid block type",
      "invalid length/literal",
      "invalid distance",
      "stream finished",
      "no stream handler",
      ,
      "no callback",
      "invalid UTF-8 data",
      "extra field too long",
      "date not in range 1980-2099",
      "filename too long",
      "stream finishing",
      "invalid zip data"
      // determined by unknown compression method
    ];
    var err = function(ind, msg, nt) {
      var e = new Error(msg || ec[ind]);
      e.code = ind;
      if (Error.captureStackTrace)
        Error.captureStackTrace(e, err);
      if (!nt)
        throw e;
      return e;
    };
    var inflt = function(dat, st, buf, dict) {
      var sl = dat.length, dl = dict ? dict.length : 0;
      if (!sl || st.f && !st.l)
        return buf || new u8(0);
      var noBuf = !buf;
      var resize = noBuf || st.i != 2;
      var noSt = st.i;
      if (noBuf)
        buf = new u8(sl * 3);
      var cbuf = function(l2) {
        var bl = buf.length;
        if (l2 > bl) {
          var nbuf = new u8(Math.max(bl * 2, l2));
          nbuf.set(buf);
          buf = nbuf;
        }
      };
      var final = st.f || 0, pos2 = st.p || 0, bt2 = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
      var tbts = sl * 8;
      do {
        if (!lm) {
          final = bits(dat, pos2, 1);
          var type = bits(dat, pos2 + 1, 3);
          pos2 += 3;
          if (!type) {
            var s = shft(pos2) + 4, l = dat[s - 4] | dat[s - 3] << 8, t2 = s + l;
            if (t2 > sl) {
              if (noSt)
                err(0);
              break;
            }
            if (resize)
              cbuf(bt2 + l);
            buf.set(dat.subarray(s, t2), bt2);
            st.b = bt2 += l, st.p = pos2 = t2 * 8, st.f = final;
            continue;
          } else if (type == 1)
            lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
          else if (type == 2) {
            var hLit = bits(dat, pos2, 31) + 257, hcLen = bits(dat, pos2 + 10, 15) + 4;
            var tl = hLit + bits(dat, pos2 + 5, 31) + 1;
            pos2 += 14;
            var ldt = new u8(tl);
            var clt = new u8(19);
            for (var i2 = 0; i2 < hcLen; ++i2) {
              clt[clim[i2]] = bits(dat, pos2 + i2 * 3, 7);
            }
            pos2 += hcLen * 3;
            var clb = max$1(clt), clbmsk = (1 << clb) - 1;
            var clm = hMap(clt, clb, 1);
            for (var i2 = 0; i2 < tl; ) {
              var r2 = clm[bits(dat, pos2, clbmsk)];
              pos2 += r2 & 15;
              var s = r2 >> 4;
              if (s < 16) {
                ldt[i2++] = s;
              } else {
                var c2 = 0, n = 0;
                if (s == 16)
                  n = 3 + bits(dat, pos2, 3), pos2 += 2, c2 = ldt[i2 - 1];
                else if (s == 17)
                  n = 3 + bits(dat, pos2, 7), pos2 += 3;
                else if (s == 18)
                  n = 11 + bits(dat, pos2, 127), pos2 += 7;
                while (n--)
                  ldt[i2++] = c2;
              }
            }
            var lt2 = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
            lbt = max$1(lt2);
            dbt = max$1(dt);
            lm = hMap(lt2, lbt, 1);
            dm = hMap(dt, dbt, 1);
          } else
            err(1);
          if (pos2 > tbts) {
            if (noSt)
              err(0);
            break;
          }
        }
        if (resize)
          cbuf(bt2 + 131072);
        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
        var lpos = pos2;
        for (; ; lpos = pos2) {
          var c2 = lm[bits16(dat, pos2) & lms], sym = c2 >> 4;
          pos2 += c2 & 15;
          if (pos2 > tbts) {
            if (noSt)
              err(0);
            break;
          }
          if (!c2)
            err(2);
          if (sym < 256)
            buf[bt2++] = sym;
          else if (sym == 256) {
            lpos = pos2, lm = null;
            break;
          } else {
            var add2 = sym - 254;
            if (sym > 264) {
              var i2 = sym - 257, b = fleb[i2];
              add2 = bits(dat, pos2, (1 << b) - 1) + fl[i2];
              pos2 += b;
            }
            var d = dm[bits16(dat, pos2) & dms], dsym = d >> 4;
            if (!d)
              err(3);
            pos2 += d & 15;
            var dt = fd[dsym];
            if (dsym > 3) {
              var b = fdeb[dsym];
              dt += bits16(dat, pos2) & (1 << b) - 1, pos2 += b;
            }
            if (pos2 > tbts) {
              if (noSt)
                err(0);
              break;
            }
            if (resize)
              cbuf(bt2 + 131072);
            var end = bt2 + add2;
            if (bt2 < dt) {
              var shift2 = dl - dt, dend = Math.min(dt, end);
              if (shift2 + bt2 < 0)
                err(3);
              for (; bt2 < dend; ++bt2)
                buf[bt2] = dict[shift2 + bt2];
            }
            for (; bt2 < end; ++bt2)
              buf[bt2] = buf[bt2 - dt];
          }
        }
        st.l = lm, st.p = lpos, st.b = bt2, st.f = final;
        if (lm)
          final = 1, st.m = lbt, st.d = dm, st.n = dbt;
      } while (!final);
      return bt2 != buf.length && noBuf ? slc(buf, 0, bt2) : buf.subarray(0, bt2);
    };
    var et$1 = /* @__PURE__ */ new u8(0);
    var mrg = function(a, b) {
      var o = {};
      for (var k in a)
        o[k] = a[k];
      for (var k in b)
        o[k] = b[k];
      return o;
    };
    var wcln = function(fn2, fnStr, td2) {
      var dt = fn2();
      var st = fn2.toString();
      var ks = st.slice(st.indexOf("[") + 1, st.lastIndexOf("]")).replace(/\s+/g, "").split(",");
      for (var i2 = 0; i2 < dt.length; ++i2) {
        var v = dt[i2], k = ks[i2];
        if (typeof v == "function") {
          fnStr += ";" + k + "=";
          var st_1 = v.toString();
          if (v.prototype) {
            if (st_1.indexOf("[native code]") != -1) {
              var spInd = st_1.indexOf(" ", 8) + 1;
              fnStr += st_1.slice(spInd, st_1.indexOf("(", spInd));
            } else {
              fnStr += st_1;
              for (var t2 in v.prototype)
                fnStr += ";" + k + ".prototype." + t2 + "=" + v.prototype[t2].toString();
            }
          } else
            fnStr += st_1;
        } else
          td2[k] = v;
      }
      return fnStr;
    };
    var ch = [];
    var cbfs = function(v) {
      var tl = [];
      for (var k in v) {
        if (v[k].buffer) {
          tl.push((v[k] = new v[k].constructor(v[k])).buffer);
        }
      }
      return tl;
    };
    var wrkr = function(fns, init, id, cb) {
      if (!ch[id]) {
        var fnStr = "", td_1 = {}, m = fns.length - 1;
        for (var i2 = 0; i2 < m; ++i2)
          fnStr = wcln(fns[i2], fnStr, td_1);
        ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };
      }
      var td2 = mrg({}, ch[id].e);
      return wk(ch[id].c + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + init.toString() + "}", id, td2, cbfs(td2), cb);
    };
    var bInflt = function() {
      return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max$1, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt];
    };
    var guze = function() {
      return [gzs, gzl];
    };
    var zule = function() {
      return [zls];
    };
    var pbf = function(msg) {
      return postMessage(msg, [msg.buffer]);
    };
    var gopt = function(o) {
      return o && {
        out: o.size && new u8(o.size),
        dictionary: o.dictionary
      };
    };
    var cbify = function(dat, opts, fns, init, id, cb) {
      var w2 = wrkr(fns, init, id, function(err2, dat2) {
        w2.terminate();
        cb(err2, dat2);
      });
      w2.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
      return function() {
        w2.terminate();
      };
    };
    var gzs = function(d) {
      if (d[0] != 31 || d[1] != 139 || d[2] != 8)
        err(6, "invalid gzip data");
      var flg = d[3];
      var st = 10;
      if (flg & 4)
        st += (d[10] | d[11] << 8) + 2;
      for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
        ;
      return st + (flg & 2);
    };
    var gzl = function(d) {
      var l = d.length;
      return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
    };
    var zls = function(d, dict) {
      if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31)
        err(6, "invalid zlib data");
      if ((d[1] >> 5 & 1) == +!dict)
        err(6, "invalid zlib data: " + (d[1] & 32 ? "need" : "unexpected") + " dictionary");
      return (d[1] >> 3 & 4) + 2;
    };
    function inflate(data, opts, cb) {
      if (!cb)
        cb = opts, opts = {};
      if (typeof cb != "function")
        err(7);
      return cbify(data, opts, [
        bInflt
      ], function(ev) {
        return pbf(inflateSync(ev.data[0], gopt(ev.data[1])));
      }, 1, cb);
    }
    function inflateSync(data, opts) {
      return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
    }
    function gunzip(data, opts, cb) {
      if (!cb)
        cb = opts, opts = {};
      if (typeof cb != "function")
        err(7);
      return cbify(data, opts, [
        bInflt,
        guze,
        function() {
          return [gunzipSync];
        }
      ], function(ev) {
        return pbf(gunzipSync(ev.data[0], ev.data[1]));
      }, 3, cb);
    }
    function gunzipSync(data, opts) {
      var st = gzs(data);
      if (st + 8 > data.length)
        err(6, "invalid gzip data");
      return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
    }
    function unzlib(data, opts, cb) {
      if (!cb)
        cb = opts, opts = {};
      if (typeof cb != "function")
        err(7);
      return cbify(data, opts, [
        bInflt,
        zule,
        function() {
          return [unzlibSync];
        }
      ], function(ev) {
        return pbf(unzlibSync(ev.data[0], gopt(ev.data[1])));
      }, 5, cb);
    }
    function unzlibSync(data, opts) {
      return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
    }
    function decompress(data, opts, cb) {
      if (!cb)
        cb = opts, opts = {};
      if (typeof cb != "function")
        err(7);
      return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzip(data, opts, cb) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflate(data, opts, cb) : unzlib(data, opts, cb);
    }
    var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
    var tds = 0;
    try {
      td.decode(et$1, { stream: true });
      tds = 1;
    } catch (e) {
    }
    class FileSizeLimitError extends Error {
      constructor(file, maxBytes) {
        super(
          `File "${file}" exceeds the maximum size (${maxBytes} bytes) and cannot be loaded.`
        );
        __publicField(this, "file");
        __publicField(this, "maxBytes");
        this.name = "FileSizeLimitError";
        this.file = file;
        this.maxBytes = maxBytes;
        Object.setPrototypeOf(this, FileSizeLimitError.prototype);
      }
    }
    const openRemoteZipFile = async (url, fetchContentLength = fetchSize, fetchBytes = fetchRange) => {
      const contentLength = await fetchContentLength(url);
      const eocdrBuffer = await fetchBytes(
        url,
        contentLength - 22,
        contentLength - 1
      );
      const eocdrView = new DataView(eocdrBuffer.buffer);
      if (eocdrView.getUint32(0, true) !== 101010256) {
        throw new Error("End of central directory record not found");
      }
      let centralDirOffset = eocdrView.getUint32(16, true);
      let centralDirSize = eocdrView.getUint32(12, true);
      const needsZip64 = centralDirOffset === 4294967295 || centralDirSize === 4294967295;
      if (needsZip64) {
        const locatorBuffer = await fetchBytes(
          url,
          contentLength - 22 - 20,
          contentLength - 23
        );
        const locatorView = new DataView(locatorBuffer.buffer);
        if (locatorView.getUint32(0, true) !== 117853008) {
          throw new Error("ZIP64 End of central directory locator not found");
        }
        const zip64EOCDOffset = Number(locatorView.getBigUint64(8, true));
        const zip64EOCDBuffer = await fetchBytes(
          url,
          zip64EOCDOffset,
          zip64EOCDOffset + 56
        );
        const zip64EOCDView = new DataView(zip64EOCDBuffer.buffer);
        if (zip64EOCDView.getUint32(0, true) !== 101075792) {
          throw new Error("ZIP64 End of central directory record not found");
        }
        centralDirSize = Number(zip64EOCDView.getBigUint64(40, true));
        centralDirOffset = Number(zip64EOCDView.getBigUint64(48, true));
      }
      const centralDirBuffer = await fetchBytes(
        url,
        centralDirOffset,
        centralDirOffset + centralDirSize - 1
      );
      const centralDirectory = parseCentralDirectory(centralDirBuffer);
      return {
        centralDirectory,
        readFile: async (file, maxBytes) => {
          const entry2 = centralDirectory.get(file);
          if (!entry2) {
            throw new Error(`File not found: ${file}`);
          }
          const headerSize = 30;
          const headerData = await fetchBytes(
            url,
            entry2.fileOffset,
            entry2.fileOffset + headerSize - 1
          );
          const filenameLength = headerData[26] + (headerData[27] << 8);
          const extraFieldLength = headerData[28] + (headerData[29] << 8);
          const totalSizeToFetch = headerSize + filenameLength + extraFieldLength + entry2.compressedSize;
          if (maxBytes && totalSizeToFetch > maxBytes) {
            throw new FileSizeLimitError(file, maxBytes);
          }
          const fileData = await fetchBytes(
            url,
            entry2.fileOffset,
            entry2.fileOffset + totalSizeToFetch - 1
          );
          const zipFileEntry = await parseZipFileEntry(file, fileData);
          if (zipFileEntry.compressionMethod === 0) {
            return zipFileEntry.data;
          } else if (zipFileEntry.compressionMethod === 8) {
            const results = await decompressAsync(zipFileEntry.data, {
              size: zipFileEntry.uncompressedSize
            });
            return results;
          } else {
            throw new Error(`Unsupported compression method for file ${file}`);
          }
        }
      };
    };
    const fetchSize = async (url) => {
      const response = await fetch(`${url}`, { method: "HEAD" });
      const contentLength = Number(response.headers.get("Content-Length"));
      return contentLength;
    };
    const fetchRange = async (url, start, end) => {
      const response = await fetch(`${url}`, {
        headers: { Range: `bytes=${start}-${end}` }
      });
      const arrayBuffer = await response.arrayBuffer();
      return new Uint8Array(arrayBuffer);
    };
    const decompressAsync = async (data, opts) => {
      return new Promise((resolve, reject) => {
        decompress(data, opts, (err2, result2) => {
          if (err2) {
            reject(err2);
          } else {
            resolve(result2);
          }
        });
      });
    };
    const parseZipFileEntry = async (file, rawData) => {
      const view = new DataView(rawData.buffer);
      let offset = 0;
      const signature = view.getUint32(offset, true);
      if (signature !== 67324752) {
        throw new Error(`Invalid ZIP entry signature for ${file}`);
      }
      offset += 4;
      const versionNeeded = view.getUint16(offset, true);
      offset += 2;
      const bitFlag = view.getUint16(offset, true);
      offset += 2;
      const compressionMethod = view.getUint16(offset, true);
      offset += 2;
      offset += 4;
      const crc32 = view.getUint32(offset, true);
      offset += 4;
      let compressedSize = view.getUint32(offset, true);
      offset += 4;
      let uncompressedSize = view.getUint32(offset, true);
      offset += 4;
      const filenameLength = view.getUint16(offset, true);
      offset += 2;
      const extraFieldLength = view.getUint16(offset, true);
      offset += 2;
      const headerOffset = offset;
      const needsZip64 = compressedSize === 4294967295 || uncompressedSize === 4294967295;
      if (needsZip64) {
        offset += filenameLength;
        const extraFieldEnd = offset + extraFieldLength;
        while (offset < extraFieldEnd) {
          const tag = view.getUint16(offset, true);
          const size = view.getUint16(offset + 2, true);
          if (tag === 1) {
            let zip64Offset = offset + 4;
            if (uncompressedSize === 4294967295 && zip64Offset + 8 <= extraFieldEnd) {
              uncompressedSize = Number(view.getBigUint64(zip64Offset, true));
              zip64Offset += 8;
            }
            if (compressedSize === 4294967295 && zip64Offset + 8 <= extraFieldEnd) {
              compressedSize = Number(view.getBigUint64(zip64Offset, true));
            }
            break;
          }
          offset += 4 + size;
        }
        offset = headerOffset;
      }
      offset += filenameLength + extraFieldLength;
      const data = rawData.subarray(offset, offset + compressedSize);
      return {
        versionNeeded,
        bitFlag,
        compressionMethod,
        crc32,
        compressedSize,
        uncompressedSize,
        filenameLength,
        extraFieldLength,
        data
      };
    };
    const kFileHeaderSize = 46;
    const parseCentralDirectory = (buffer2) => {
      let offset = 0;
      const view = new DataView(buffer2.buffer);
      const entries = /* @__PURE__ */ new Map();
      while (offset < buffer2.length) {
        if (view.getUint32(offset, true) !== 33639248) break;
        const filenameLength = view.getUint16(offset + 28, true);
        const extraFieldLength = view.getUint16(offset + 30, true);
        const fileCommentLength = view.getUint16(offset + 32, true);
        let compressedSize = view.getUint32(offset + 20, true);
        let uncompressedSize = view.getUint32(offset + 24, true);
        let fileOffset = view.getUint32(offset + 42, true);
        const filename2 = new TextDecoder().decode(
          buffer2.subarray(
            offset + kFileHeaderSize,
            offset + kFileHeaderSize + filenameLength
          )
        );
        const needsZip64 = fileOffset === 4294967295 || compressedSize === 4294967295 || uncompressedSize === 4294967295;
        if (needsZip64) {
          let extraOffset = offset + kFileHeaderSize + filenameLength;
          const extraEnd = extraOffset + extraFieldLength;
          while (extraOffset < extraEnd) {
            const tag = view.getUint16(extraOffset, true);
            const size = view.getUint16(extraOffset + 2, true);
            if (tag === 1) {
              let zip64Offset = extraOffset + 4;
              if (uncompressedSize === 4294967295 && zip64Offset + 8 <= extraEnd) {
                uncompressedSize = Number(view.getBigUint64(zip64Offset, true));
                zip64Offset += 8;
              }
              if (compressedSize === 4294967295 && zip64Offset + 8 <= extraEnd) {
                compressedSize = Number(view.getBigUint64(zip64Offset, true));
                zip64Offset += 8;
              }
              if (fileOffset === 4294967295 && zip64Offset + 8 <= extraEnd) {
                fileOffset = Number(view.getBigUint64(zip64Offset, true));
              }
              break;
            }
            extraOffset += 4 + size;
          }
        }
        const entry2 = {
          filename: filename2,
          compressionMethod: view.getUint16(offset + 10, true),
          compressedSize,
          uncompressedSize,
          fileOffset
        };
        entries.set(filename2, entry2);
        offset += kFileHeaderSize + filenameLength + extraFieldLength + fileCommentLength;
      }
      return entries;
    };
    function simpleHttpApi(log_dir, log_file) {
      const resolved_log_dir = log_dir == null ? void 0 : log_dir.replace(" ", "+");
      log_file ? log_file.replace(" ", "+") : void 0;
      return simpleHttpAPI({
        log_dir: resolved_log_dir
      });
    }
    function simpleHttpAPI(logInfo) {
      const log_dir = logInfo.log_dir;
      async function open_log_file2() {
      }
      return {
        client_events: async () => {
          return Promise.resolve([]);
        },
        eval_logs: async () => {
          if (log_dir) {
            const headers = await fetchLogHeaders(log_dir);
            if (headers) {
              const logRecord = headers.parsed;
              const logs = Object.keys(logRecord).map((key2) => {
                return {
                  name: joinURI(log_dir, key2),
                  task: logRecord[key2].eval.task,
                  task_id: logRecord[key2].eval.task_id
                };
              });
              return Promise.resolve({
                files: logs,
                log_dir
              });
            }
          }
          return void 0;
        },
        eval_log: async (log_file, _headerOnly, _capabilities) => {
          const response = await fetchLogFile(log_file);
          if (response) {
            return response;
          } else {
            throw new Error(`"Unable to load eval log ${log_file}`);
          }
        },
        eval_log_size: async (log_file) => {
          return await fetchSize(log_file);
        },
        eval_log_bytes: async (log_file, start, end) => {
          return await fetchRange(log_file, start, end);
        },
        eval_log_headers: async (files) => {
          if (files.length === 0) {
            return [];
          }
          if (log_dir) {
            const headers = await fetchLogHeaders(log_dir);
            if (headers) {
              const keys = Object.keys(headers.parsed);
              const result2 = [];
              files.forEach((file) => {
                const fileKey = keys.find((key2) => {
                  return file.endsWith(key2);
                });
                if (fileKey) {
                  result2.push(headers.parsed[fileKey]);
                }
              });
              return result2;
            }
          }
          throw new Error(
            `Failed to load a manifest files using the directory: ${log_dir}. Please be sure you have deployed a manifest file (logs.json).`
          );
        },
        download_file: download_file$1,
        open_log_file: open_log_file2
      };
    }
    async function fetchFile(url, parse2, handleError2) {
      const safe_url = encodePathParts(url);
      const response = await fetch(`${safe_url}`, { method: "GET" });
      if (response.ok) {
        const text2 = await response.text();
        return await parse2(text2);
      } else if (response.status !== 200) {
        if (handleError2 && handleError2(response)) {
          return void 0;
        }
        const message2 = await response.text() || response.statusText;
        const error2 = new Error(`${response.status}: ${message2})`);
        throw error2;
      } else {
        throw new Error(`${response.status} - ${response.statusText} `);
      }
    }
    const fetchLogFile = async (file) => {
      return fetchFile(file, async (text2) => {
        var _a2;
        const log2 = await asyncJsonParse(text2);
        if (log2.version === 1) {
          if (log2.results) {
            const untypedLog = log2;
            log2.results.scores = [];
            untypedLog.results.scorer.scorer = untypedLog.results.scorer.name;
            log2.results.scores.push(untypedLog.results.scorer);
            delete untypedLog.results.scorer;
            log2.results.scores[0].metrics = untypedLog.results.metrics;
            delete untypedLog.results.metrics;
            const scorerName = log2.results.scores[0].name;
            (_a2 = log2.samples) == null ? void 0 : _a2.forEach((sample2) => {
              const untypedSample = sample2;
              sample2.scores = { [scorerName]: untypedSample.score };
              delete untypedSample.score;
            });
          }
        }
        return {
          raw: text2,
          parsed: log2
        };
      });
    };
    const fetchLogHeaders = async (log_dir) => {
      const logs = await fetchFile(
        log_dir + "/logs.json",
        async (text2) => {
          const parsed = await asyncJsonParse(text2);
          return {
            raw: text2,
            parsed
          };
        },
        (response) => {
          if (response.status === 404) {
            return true;
          } else {
            return false;
          }
        }
      );
      return logs;
    };
    function joinURI(...segments) {
      return segments.map((segment) => segment.replace(/(^\/+|\/+$)/g, "")).join("/");
    }
    var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
    var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
    var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
    var unicode = {
      Space_Separator,
      ID_Start,
      ID_Continue
    };
    var util = {
      isSpaceSeparator(c2) {
        return typeof c2 === "string" && unicode.Space_Separator.test(c2);
      },
      isIdStartChar(c2) {
        return typeof c2 === "string" && (c2 >= "a" && c2 <= "z" || c2 >= "A" && c2 <= "Z" || c2 === "$" || c2 === "_" || unicode.ID_Start.test(c2));
      },
      isIdContinueChar(c2) {
        return typeof c2 === "string" && (c2 >= "a" && c2 <= "z" || c2 >= "A" && c2 <= "Z" || c2 >= "0" && c2 <= "9" || c2 === "$" || c2 === "_" || c2 === "‌" || c2 === "‍" || unicode.ID_Continue.test(c2));
      },
      isDigit(c2) {
        return typeof c2 === "string" && /[0-9]/.test(c2);
      },
      isHexDigit(c2) {
        return typeof c2 === "string" && /[0-9A-Fa-f]/.test(c2);
      }
    };
    let source;
    let parseState;
    let stack;
    let pos;
    let line;
    let column;
    let token;
    let key;
    let root$1;
    var parse$3 = function parse2(text2, reviver) {
      source = String(text2);
      parseState = "start";
      stack = [];
      pos = 0;
      line = 1;
      column = 0;
      token = void 0;
      key = void 0;
      root$1 = void 0;
      do {
        token = lex();
        parseStates[parseState]();
      } while (token.type !== "eof");
      if (typeof reviver === "function") {
        return internalize({ "": root$1 }, "", reviver);
      }
      return root$1;
    };
    function internalize(holder, name2, reviver) {
      const value2 = holder[name2];
      if (value2 != null && typeof value2 === "object") {
        if (Array.isArray(value2)) {
          for (let i2 = 0; i2 < value2.length; i2++) {
            const key2 = String(i2);
            const replacement = internalize(value2, key2, reviver);
            if (replacement === void 0) {
              delete value2[key2];
            } else {
              Object.defineProperty(value2, key2, {
                value: replacement,
                writable: true,
                enumerable: true,
                configurable: true
              });
            }
          }
        } else {
          for (const key2 in value2) {
            const replacement = internalize(value2, key2, reviver);
            if (replacement === void 0) {
              delete value2[key2];
            } else {
              Object.defineProperty(value2, key2, {
                value: replacement,
                writable: true,
                enumerable: true,
                configurable: true
              });
            }
          }
        }
      }
      return reviver.call(holder, name2, value2);
    }
    let lexState;
    let buffer$1;
    let doubleQuote;
    let sign;
    let c;
    function lex() {
      lexState = "default";
      buffer$1 = "";
      doubleQuote = false;
      sign = 1;
      for (; ; ) {
        c = peek();
        const token2 = lexStates[lexState]();
        if (token2) {
          return token2;
        }
      }
    }
    function peek() {
      if (source[pos]) {
        return String.fromCodePoint(source.codePointAt(pos));
      }
    }
    function read() {
      const c2 = peek();
      if (c2 === "\n") {
        line++;
        column = 0;
      } else if (c2) {
        column += c2.length;
      } else {
        column++;
      }
      if (c2) {
        pos += c2.length;
      }
      return c2;
    }
    const lexStates = {
      default() {
        switch (c) {
          case "	":
          case "\v":
          case "\f":
          case " ":
          case " ":
          case "\uFEFF":
          case "\n":
          case "\r":
          case "\u2028":
          case "\u2029":
            read();
            return;
          case "/":
            read();
            lexState = "comment";
            return;
          case void 0:
            read();
            return newToken("eof");
        }
        if (util.isSpaceSeparator(c)) {
          read();
          return;
        }
        return lexStates[parseState]();
      },
      comment() {
        switch (c) {
          case "*":
            read();
            lexState = "multiLineComment";
            return;
          case "/":
            read();
            lexState = "singleLineComment";
            return;
        }
        throw invalidChar(read());
      },
      multiLineComment() {
        switch (c) {
          case "*":
            read();
            lexState = "multiLineCommentAsterisk";
            return;
          case void 0:
            throw invalidChar(read());
        }
        read();
      },
      multiLineCommentAsterisk() {
        switch (c) {
          case "*":
            read();
            return;
          case "/":
            read();
            lexState = "default";
            return;
          case void 0:
            throw invalidChar(read());
        }
        read();
        lexState = "multiLineComment";
      },
      singleLineComment() {
        switch (c) {
          case "\n":
          case "\r":
          case "\u2028":
          case "\u2029":
            read();
            lexState = "default";
            return;
          case void 0:
            read();
            return newToken("eof");
        }
        read();
      },
      value() {
        switch (c) {
          case "{":
          case "[":
            return newToken("punctuator", read());
          case "n":
            read();
            literal("ull");
            return newToken("null", null);
          case "t":
            read();
            literal("rue");
            return newToken("boolean", true);
          case "f":
            read();
            literal("alse");
            return newToken("boolean", false);
          case "-":
          case "+":
            if (read() === "-") {
              sign = -1;
            }
            lexState = "sign";
            return;
          case ".":
            buffer$1 = read();
            lexState = "decimalPointLeading";
            return;
          case "0":
            buffer$1 = read();
            lexState = "zero";
            return;
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            buffer$1 = read();
            lexState = "decimalInteger";
            return;
          case "I":
            read();
            literal("nfinity");
            return newToken("numeric", Infinity);
          case "N":
            read();
            literal("aN");
            return newToken("numeric", NaN);
          case '"':
          case "'":
            doubleQuote = read() === '"';
            buffer$1 = "";
            lexState = "string";
            return;
        }
        throw invalidChar(read());
      },
      identifierNameStartEscape() {
        if (c !== "u") {
          throw invalidChar(read());
        }
        read();
        const u = unicodeEscape();
        switch (u) {
          case "$":
          case "_":
            break;
          default:
            if (!util.isIdStartChar(u)) {
              throw invalidIdentifier();
            }
            break;
        }
        buffer$1 += u;
        lexState = "identifierName";
      },
      identifierName() {
        switch (c) {
          case "$":
          case "_":
          case "‌":
          case "‍":
            buffer$1 += read();
            return;
          case "\\":
            read();
            lexState = "identifierNameEscape";
            return;
        }
        if (util.isIdContinueChar(c)) {
          buffer$1 += read();
          return;
        }
        return newToken("identifier", buffer$1);
      },
      identifierNameEscape() {
        if (c !== "u") {
          throw invalidChar(read());
        }
        read();
        const u = unicodeEscape();
        switch (u) {
          case "$":
          case "_":
          case "‌":
          case "‍":
            break;
          default:
            if (!util.isIdContinueChar(u)) {
              throw invalidIdentifier();
            }
            break;
        }
        buffer$1 += u;
        lexState = "identifierName";
      },
      sign() {
        switch (c) {
          case ".":
            buffer$1 = read();
            lexState = "decimalPointLeading";
            return;
          case "0":
            buffer$1 = read();
            lexState = "zero";
            return;
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            buffer$1 = read();
            lexState = "decimalInteger";
            return;
          case "I":
            read();
            literal("nfinity");
            return newToken("numeric", sign * Infinity);
          case "N":
            read();
            literal("aN");
            return newToken("numeric", NaN);
        }
        throw invalidChar(read());
      },
      zero() {
        switch (c) {
          case ".":
            buffer$1 += read();
            lexState = "decimalPoint";
            return;
          case "e":
          case "E":
            buffer$1 += read();
            lexState = "decimalExponent";
            return;
          case "x":
          case "X":
            buffer$1 += read();
            lexState = "hexadecimal";
            return;
        }
        return newToken("numeric", sign * 0);
      },
      decimalInteger() {
        switch (c) {
          case ".":
            buffer$1 += read();
            lexState = "decimalPoint";
            return;
          case "e":
          case "E":
            buffer$1 += read();
            lexState = "decimalExponent";
            return;
        }
        if (util.isDigit(c)) {
          buffer$1 += read();
          return;
        }
        return newToken("numeric", sign * Number(buffer$1));
      },
      decimalPointLeading() {
        if (util.isDigit(c)) {
          buffer$1 += read();
          lexState = "decimalFraction";
          return;
        }
        throw invalidChar(read());
      },
      decimalPoint() {
        switch (c) {
          case "e":
          case "E":
            buffer$1 += read();
            lexState = "decimalExponent";
            return;
        }
        if (util.isDigit(c)) {
          buffer$1 += read();
          lexState = "decimalFraction";
          return;
        }
        return newToken("numeric", sign * Number(buffer$1));
      },
      decimalFraction() {
        switch (c) {
          case "e":
          case "E":
            buffer$1 += read();
            lexState = "decimalExponent";
            return;
        }
        if (util.isDigit(c)) {
          buffer$1 += read();
          return;
        }
        return newToken("numeric", sign * Number(buffer$1));
      },
      decimalExponent() {
        switch (c) {
          case "+":
          case "-":
            buffer$1 += read();
            lexState = "decimalExponentSign";
            return;
        }
        if (util.isDigit(c)) {
          buffer$1 += read();
          lexState = "decimalExponentInteger";
          return;
        }
        throw invalidChar(read());
      },
      decimalExponentSign() {
        if (util.isDigit(c)) {
          buffer$1 += read();
          lexState = "decimalExponentInteger";
          return;
        }
        throw invalidChar(read());
      },
      decimalExponentInteger() {
        if (util.isDigit(c)) {
          buffer$1 += read();
          return;
        }
        return newToken("numeric", sign * Number(buffer$1));
      },
      hexadecimal() {
        if (util.isHexDigit(c)) {
          buffer$1 += read();
          lexState = "hexadecimalInteger";
          return;
        }
        throw invalidChar(read());
      },
      hexadecimalInteger() {
        if (util.isHexDigit(c)) {
          buffer$1 += read();
          return;
        }
        return newToken("numeric", sign * Number(buffer$1));
      },
      string() {
        switch (c) {
          case "\\":
            read();
            buffer$1 += escape();
            return;
          case '"':
            if (doubleQuote) {
              read();
              return newToken("string", buffer$1);
            }
            buffer$1 += read();
            return;
          case "'":
            if (!doubleQuote) {
              read();
              return newToken("string", buffer$1);
            }
            buffer$1 += read();
            return;
          case "\n":
          case "\r":
            throw invalidChar(read());
          case "\u2028":
          case "\u2029":
            separatorChar(c);
            break;
          case void 0:
            throw invalidChar(read());
        }
        buffer$1 += read();
      },
      start() {
        switch (c) {
          case "{":
          case "[":
            return newToken("punctuator", read());
        }
        lexState = "value";
      },
      beforePropertyName() {
        switch (c) {
          case "$":
          case "_":
            buffer$1 = read();
            lexState = "identifierName";
            return;
          case "\\":
            read();
            lexState = "identifierNameStartEscape";
            return;
          case "}":
            return newToken("punctuator", read());
          case '"':
          case "'":
            doubleQuote = read() === '"';
            lexState = "string";
            return;
        }
        if (util.isIdStartChar(c)) {
          buffer$1 += read();
          lexState = "identifierName";
          return;
        }
        throw invalidChar(read());
      },
      afterPropertyName() {
        if (c === ":") {
          return newToken("punctuator", read());
        }
        throw invalidChar(read());
      },
      beforePropertyValue() {
        lexState = "value";
      },
      afterPropertyValue() {
        switch (c) {
          case ",":
          case "}":
            return newToken("punctuator", read());
        }
        throw invalidChar(read());
      },
      beforeArrayValue() {
        if (c === "]") {
          return newToken("punctuator", read());
        }
        lexState = "value";
      },
      afterArrayValue() {
        switch (c) {
          case ",":
          case "]":
            return newToken("punctuator", read());
        }
        throw invalidChar(read());
      },
      end() {
        throw invalidChar(read());
      }
    };
    function newToken(type, value2) {
      return {
        type,
        value: value2,
        line,
        column
      };
    }
    function literal(s) {
      for (const c2 of s) {
        const p = peek();
        if (p !== c2) {
          throw invalidChar(read());
        }
        read();
      }
    }
    function escape() {
      const c2 = peek();
      switch (c2) {
        case "b":
          read();
          return "\b";
        case "f":
          read();
          return "\f";
        case "n":
          read();
          return "\n";
        case "r":
          read();
          return "\r";
        case "t":
          read();
          return "	";
        case "v":
          read();
          return "\v";
        case "0":
          read();
          if (util.isDigit(peek())) {
            throw invalidChar(read());
          }
          return "\0";
        case "x":
          read();
          return hexEscape();
        case "u":
          read();
          return unicodeEscape();
        case "\n":
        case "\u2028":
        case "\u2029":
          read();
          return "";
        case "\r":
          read();
          if (peek() === "\n") {
            read();
          }
          return "";
        case "1":
        case "2":
        case "3":
        case "4":
        case "5":
        case "6":
        case "7":
        case "8":
        case "9":
          throw invalidChar(read());
        case void 0:
          throw invalidChar(read());
      }
      return read();
    }
    function hexEscape() {
      let buffer2 = "";
      let c2 = peek();
      if (!util.isHexDigit(c2)) {
        throw invalidChar(read());
      }
      buffer2 += read();
      c2 = peek();
      if (!util.isHexDigit(c2)) {
        throw invalidChar(read());
      }
      buffer2 += read();
      return String.fromCodePoint(parseInt(buffer2, 16));
    }
    function unicodeEscape() {
      let buffer2 = "";
      let count = 4;
      while (count-- > 0) {
        const c2 = peek();
        if (!util.isHexDigit(c2)) {
          throw invalidChar(read());
        }
        buffer2 += read();
      }
      return String.fromCodePoint(parseInt(buffer2, 16));
    }
    const parseStates = {
      start() {
        if (token.type === "eof") {
          throw invalidEOF();
        }
        push();
      },
      beforePropertyName() {
        switch (token.type) {
          case "identifier":
          case "string":
            key = token.value;
            parseState = "afterPropertyName";
            return;
          case "punctuator":
            pop();
            return;
          case "eof":
            throw invalidEOF();
        }
      },
      afterPropertyName() {
        if (token.type === "eof") {
          throw invalidEOF();
        }
        parseState = "beforePropertyValue";
      },
      beforePropertyValue() {
        if (token.type === "eof") {
          throw invalidEOF();
        }
        push();
      },
      beforeArrayValue() {
        if (token.type === "eof") {
          throw invalidEOF();
        }
        if (token.type === "punctuator" && token.value === "]") {
          pop();
          return;
        }
        push();
      },
      afterPropertyValue() {
        if (token.type === "eof") {
          throw invalidEOF();
        }
        switch (token.value) {
          case ",":
            parseState = "beforePropertyName";
            return;
          case "}":
            pop();
        }
      },
      afterArrayValue() {
        if (token.type === "eof") {
          throw invalidEOF();
        }
        switch (token.value) {
          case ",":
            parseState = "beforeArrayValue";
            return;
          case "]":
            pop();
        }
      },
      end() {
      }
    };
    function push() {
      let value2;
      switch (token.type) {
        case "punctuator":
          switch (token.value) {
            case "{":
              value2 = {};
              break;
            case "[":
              value2 = [];
              break;
          }
          break;
        case "null":
        case "boolean":
        case "numeric":
        case "string":
          value2 = token.value;
          break;
      }
      if (root$1 === void 0) {
        root$1 = value2;
      } else {
        const parent = stack[stack.length - 1];
        if (Array.isArray(parent)) {
          parent.push(value2);
        } else {
          Object.defineProperty(parent, key, {
            value: value2,
            writable: true,
            enumerable: true,
            configurable: true
          });
        }
      }
      if (value2 !== null && typeof value2 === "object") {
        stack.push(value2);
        if (Array.isArray(value2)) {
          parseState = "beforeArrayValue";
        } else {
          parseState = "beforePropertyName";
        }
      } else {
        const current = stack[stack.length - 1];
        if (current == null) {
          parseState = "end";
        } else if (Array.isArray(current)) {
          parseState = "afterArrayValue";
        } else {
          parseState = "afterPropertyValue";
        }
      }
    }
    function pop() {
      stack.pop();
      const current = stack[stack.length - 1];
      if (current == null) {
        parseState = "end";
      } else if (Array.isArray(current)) {
        parseState = "afterArrayValue";
      } else {
        parseState = "afterPropertyValue";
      }
    }
    function invalidChar(c2) {
      if (c2 === void 0) {
        return syntaxError(`JSON5: invalid end of input at ${line}:${column}`);
      }
      return syntaxError(`JSON5: invalid character '${formatChar(c2)}' at ${line}:${column}`);
    }
    function invalidEOF() {
      return syntaxError(`JSON5: invalid end of input at ${line}:${column}`);
    }
    function invalidIdentifier() {
      column -= 5;
      return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`);
    }
    function separatorChar(c2) {
      console.warn(`JSON5: '${formatChar(c2)}' in strings is not valid ECMAScript; consider escaping`);
    }
    function formatChar(c2) {
      const replacements = {
        "'": "\\'",
        '"': '\\"',
        "\\": "\\\\",
        "\b": "\\b",
        "\f": "\\f",
        "\n": "\\n",
        "\r": "\\r",
        "	": "\\t",
        "\v": "\\v",
        "\0": "\\0",
        "\u2028": "\\u2028",
        "\u2029": "\\u2029"
      };
      if (replacements[c2]) {
        return replacements[c2];
      }
      if (c2 < " ") {
        const hexString = c2.charCodeAt(0).toString(16);
        return "\\x" + ("00" + hexString).substring(hexString.length);
      }
      return c2;
    }
    function syntaxError(message2) {
      const err2 = new SyntaxError(message2);
      err2.lineNumber = line;
      err2.columnNumber = column;
      return err2;
    }
    var stringify = function stringify2(value2, replacer, space) {
      const stack2 = [];
      let indent = "";
      let propertyList;
      let replacerFunc;
      let gap = "";
      let quote;
      if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
        space = replacer.space;
        quote = replacer.quote;
        replacer = replacer.replacer;
      }
      if (typeof replacer === "function") {
        replacerFunc = replacer;
      } else if (Array.isArray(replacer)) {
        propertyList = [];
        for (const v of replacer) {
          let item2;
          if (typeof v === "string") {
            item2 = v;
          } else if (typeof v === "number" || v instanceof String || v instanceof Number) {
            item2 = String(v);
          }
          if (item2 !== void 0 && propertyList.indexOf(item2) < 0) {
            propertyList.push(item2);
          }
        }
      }
      if (space instanceof Number) {
        space = Number(space);
      } else if (space instanceof String) {
        space = String(space);
      }
      if (typeof space === "number") {
        if (space > 0) {
          space = Math.min(10, Math.floor(space));
          gap = "          ".substr(0, space);
        }
      } else if (typeof space === "string") {
        gap = space.substr(0, 10);
      }
      return serializeProperty("", { "": value2 });
      function serializeProperty(key2, holder) {
        let value3 = holder[key2];
        if (value3 != null) {
          if (typeof value3.toJSON5 === "function") {
            value3 = value3.toJSON5(key2);
          } else if (typeof value3.toJSON === "function") {
            value3 = value3.toJSON(key2);
          }
        }
        if (replacerFunc) {
          value3 = replacerFunc.call(holder, key2, value3);
        }
        if (value3 instanceof Number) {
          value3 = Number(value3);
        } else if (value3 instanceof String) {
          value3 = String(value3);
        } else if (value3 instanceof Boolean) {
          value3 = value3.valueOf();
        }
        switch (value3) {
          case null:
            return "null";
          case true:
            return "true";
          case false:
            return "false";
        }
        if (typeof value3 === "string") {
          return quoteString(value3);
        }
        if (typeof value3 === "number") {
          return String(value3);
        }
        if (typeof value3 === "object") {
          return Array.isArray(value3) ? serializeArray(value3) : serializeObject(value3);
        }
        return void 0;
      }
      function quoteString(value3) {
        const quotes = {
          "'": 0.1,
          '"': 0.2
        };
        const replacements = {
          "'": "\\'",
          '"': '\\"',
          "\\": "\\\\",
          "\b": "\\b",
          "\f": "\\f",
          "\n": "\\n",
          "\r": "\\r",
          "	": "\\t",
          "\v": "\\v",
          "\0": "\\0",
          "\u2028": "\\u2028",
          "\u2029": "\\u2029"
        };
        let product = "";
        for (let i2 = 0; i2 < value3.length; i2++) {
          const c2 = value3[i2];
          switch (c2) {
            case "'":
            case '"':
              quotes[c2]++;
              product += c2;
              continue;
            case "\0":
              if (util.isDigit(value3[i2 + 1])) {
                product += "\\x00";
                continue;
              }
          }
          if (replacements[c2]) {
            product += replacements[c2];
            continue;
          }
          if (c2 < " ") {
            let hexString = c2.charCodeAt(0).toString(16);
            product += "\\x" + ("00" + hexString).substring(hexString.length);
            continue;
          }
          product += c2;
        }
        const quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b);
        product = product.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]);
        return quoteChar + product + quoteChar;
      }
      function serializeObject(value3) {
        if (stack2.indexOf(value3) >= 0) {
          throw TypeError("Converting circular structure to JSON5");
        }
        stack2.push(value3);
        let stepback = indent;
        indent = indent + gap;
        let keys = propertyList || Object.keys(value3);
        let partial = [];
        for (const key2 of keys) {
          const propertyString = serializeProperty(key2, value3);
          if (propertyString !== void 0) {
            let member = serializeKey(key2) + ":";
            if (gap !== "") {
              member += " ";
            }
            member += propertyString;
            partial.push(member);
          }
        }
        let final;
        if (partial.length === 0) {
          final = "{}";
        } else {
          let properties;
          if (gap === "") {
            properties = partial.join(",");
            final = "{" + properties + "}";
          } else {
            let separator2 = ",\n" + indent;
            properties = partial.join(separator2);
            final = "{\n" + indent + properties + ",\n" + stepback + "}";
          }
        }
        stack2.pop();
        indent = stepback;
        return final;
      }
      function serializeKey(key2) {
        if (key2.length === 0) {
          return quoteString(key2);
        }
        const firstChar = String.fromCodePoint(key2.codePointAt(0));
        if (!util.isIdStartChar(firstChar)) {
          return quoteString(key2);
        }
        for (let i2 = firstChar.length; i2 < key2.length; i2++) {
          if (!util.isIdContinueChar(String.fromCodePoint(key2.codePointAt(i2)))) {
            return quoteString(key2);
          }
        }
        return key2;
      }
      function serializeArray(value3) {
        if (stack2.indexOf(value3) >= 0) {
          throw TypeError("Converting circular structure to JSON5");
        }
        stack2.push(value3);
        let stepback = indent;
        indent = indent + gap;
        let partial = [];
        for (let i2 = 0; i2 < value3.length; i2++) {
          const propertyString = serializeProperty(String(i2), value3);
          partial.push(propertyString !== void 0 ? propertyString : "null");
        }
        let final;
        if (partial.length === 0) {
          final = "[]";
        } else {
          if (gap === "") {
            let properties = partial.join(",");
            final = "[" + properties + "]";
          } else {
            let separator2 = ",\n" + indent;
            let properties = partial.join(separator2);
            final = "[\n" + indent + properties + ",\n" + stepback + "]";
          }
        }
        stack2.pop();
        indent = stepback;
        return final;
      }
    };
    const JSON5 = {
      parse: parse$3,
      stringify
    };
    var lib = JSON5;
    const kMethodEvalLogs = "eval_logs";
    const kMethodEvalLog = "eval_log";
    const kMethodEvalLogSize = "eval_log_size";
    const kMethodEvalLogBytes = "eval_log_bytes";
    const kMethodEvalLogHeaders = "eval_log_headers";
    const kJsonRpcVersion = "2.0";
    function webViewJsonRpcClient(vscode2) {
      const target2 = {
        postMessage: (data) => {
          vscode2.postMessage(data);
        },
        onMessage: (handler) => {
          const onMessage = (ev) => {
            handler(ev.data);
          };
          window.addEventListener("message", onMessage);
          return () => {
            window.removeEventListener("message", onMessage);
          };
        }
      };
      return jsonRpcPostMessageRequestTransport(target2).request;
    }
    function jsonRpcPostMessageRequestTransport(target2) {
      const requests = /* @__PURE__ */ new Map();
      const disconnect = target2.onMessage((ev) => {
        const response = asJsonRpcResponse(ev);
        if (response) {
          const request = requests.get(response.id);
          if (request) {
            requests.delete(response.id);
            if (response.error) {
              request.reject(response.error);
            } else {
              request.resolve(response.result);
            }
          }
        }
      });
      return {
        request: (method, params2) => {
          return new Promise((resolve, reject) => {
            const requestId = Math.floor(Math.random() * 1e6);
            requests.set(requestId, { resolve, reject });
            const request = {
              jsonrpc: kJsonRpcVersion,
              id: requestId,
              method,
              params: params2
            };
            target2.postMessage(request);
          });
        },
        disconnect
      };
    }
    function isJsonRpcMessage(message2) {
      return message2.jsonrpc !== void 0 && message2.id !== void 0;
    }
    function asJsonRpcMessage(data) {
      if (isJsonRpcMessage(data) && data.jsonrpc === kJsonRpcVersion) {
        return data;
      }
      return null;
    }
    function asJsonRpcResponse(data) {
      const message2 = asJsonRpcMessage(data);
      if (message2) {
        return message2;
      }
      return null;
    }
    const vscodeClient = webViewJsonRpcClient(getVscodeApi());
    async function client_events() {
      return [];
    }
    async function eval_logs() {
      const response = await vscodeClient(kMethodEvalLogs, []);
      if (response) {
        const parsed = lib.parse(response);
        if (Array.isArray(parsed)) {
          return {
            log_dir: "",
            files: parsed
          };
        } else {
          return parsed;
        }
      } else {
        return void 0;
      }
    }
    async function eval_log(log_file, headerOnly, capabilities2) {
      const response = await vscodeClient(kMethodEvalLog, [log_file, headerOnly]);
      if (response) {
        let json;
        if (capabilities2 == null ? void 0 : capabilities2.webWorkers) {
          json = await asyncJsonParse(response);
        } else {
          json = lib.parse(response);
        }
        return {
          parsed: json,
          raw: response
        };
      } else {
        throw new Error(`Unable to load eval log ${log_file}.`);
      }
    }
    async function eval_log_size(log_file) {
      return await vscodeClient(kMethodEvalLogSize, [log_file]);
    }
    async function eval_log_bytes(log_file, start, end) {
      return await vscodeClient(kMethodEvalLogBytes, [log_file, start, end]);
    }
    async function eval_log_headers(files) {
      const response = await vscodeClient(kMethodEvalLogHeaders, [files]);
      if (response) {
        return lib.parse(response);
      } else {
        return void 0;
      }
    }
    async function download_file() {
      throw Error("Downloading files is not supported in VS Code");
    }
    async function open_log_file(log_file, log_dir) {
      var _a2;
      const msg = {
        type: "displayLogFile",
        url: log_file,
        log_dir
      };
      (_a2 = getVscodeApi()) == null ? void 0 : _a2.postMessage(msg);
    }
    const api$1 = {
      client_events,
      eval_logs,
      eval_log,
      eval_log_size,
      eval_log_bytes,
      eval_log_headers,
      download_file,
      open_log_file
    };
    class AsyncQueue {
      constructor(concurrentLimit = 6) {
        // Max concurrency
        __publicField(this, "concurrentLimit");
        // The queue
        __publicField(this, "queue");
        // Count of currently running tasks
        __publicField(this, "runningCount");
        this.concurrentLimit = concurrentLimit;
        this.queue = [];
        this.runningCount = 0;
      }
      // Adds a task to the queue and runs it if the concurrency limit allows.
      async enqueue(task2) {
        return new Promise((resolve, reject) => {
          this.queue.push(async () => {
            try {
              const result2 = await task2();
              resolve(result2);
            } catch (error2) {
              reject(error2);
            } finally {
              this.runningCount--;
              this.runNext();
            }
          });
          if (this.runningCount < this.concurrentLimit) {
            this.runNext();
          }
        });
      }
      // Runs the next task in the queue if there are available slots for concurrent execution.
      runNext() {
        if (this.queue.length > 0 && this.runningCount < this.concurrentLimit) {
          const task2 = this.queue.shift();
          if (task2) {
            this.runningCount++;
            task2();
          }
        }
      }
    }
    const MAX_BYTES = 50 * 1024 * 1024;
    const openRemoteLogFile = async (api2, url, concurrency) => {
      const queue = new AsyncQueue(concurrency);
      const remoteZipFile = await openRemoteZipFile(
        url,
        api2.eval_log_size,
        api2.eval_log_bytes
      );
      const readJSONFile = async (file, maxBytes) => {
        try {
          const data = await remoteZipFile.readFile(file, maxBytes);
          const textDecoder = new TextDecoder("utf-8");
          const jsonString = textDecoder.decode(data);
          return asyncJsonParse(jsonString);
        } catch (error2) {
          if (error2 instanceof FileSizeLimitError) {
            throw error2;
          } else if (error2 instanceof Error) {
            throw new Error(
              `Failed to read or parse file ${file}: ${error2.message}`
            );
          } else {
            throw new Error(
              `Failed to read or parse file ${file} - an unknown error occurred`
            );
          }
        }
      };
      const listSamples = async () => {
        return Array.from(remoteZipFile.centralDirectory.keys()).filter(
          (filename2) => filename2.startsWith("samples/") && filename2.endsWith(".json")
        ).map((filename2) => {
          const [sampleId, epochStr] = filename2.split("/")[1].split("_epoch_");
          return {
            sampleId,
            epoch: parseInt(epochStr.split(".")[0], 10)
          };
        });
      };
      const readSample = async (sampleId, epoch) => {
        const sampleFile = `samples/${sampleId}_epoch_${epoch}.json`;
        if (remoteZipFile.centralDirectory.has(sampleFile)) {
          return await readJSONFile(sampleFile, MAX_BYTES);
        } else {
          throw new Error(
            `Unable to read sample file ${sampleFile} - it is not present in the manifest.`
          );
        }
      };
      const readHeader = async () => {
        if (remoteZipFile.centralDirectory.has("header.json")) {
          return await readJSONFile("header.json");
        } else {
          const evalSpec = await readJSONFile("_journal/start.json");
          return {
            status: "started",
            eval: evalSpec.eval,
            plan: evalSpec.plan
          };
        }
      };
      const readFallbackSummaries = async () => {
        const summaryFiles = Array.from(
          remoteZipFile.centralDirectory.keys()
        ).filter(
          (filename2) => filename2.startsWith("_journal/summaries/") && filename2.endsWith(".json")
        );
        const summaries = [];
        const errors2 = [];
        await Promise.all(
          summaryFiles.map(
            (filename2) => queue.enqueue(async () => {
              try {
                const partialSummary = await readJSONFile(
                  filename2
                );
                summaries.push(...partialSummary);
              } catch (error2) {
                errors2.push(error2);
              }
            })
          )
        );
        if (errors2.length > 0) {
          console.error(
            `Encountered ${errors2.length} errors while reading summary files:`,
            errors2
          );
        }
        return summaries;
      };
      const readSampleSummaries = async () => {
        if (remoteZipFile.centralDirectory.has("summaries.json")) {
          return await readJSONFile("summaries.json");
        } else {
          return readFallbackSummaries();
        }
      };
      return {
        readHeader,
        readLogSummary: async () => {
          const [header2, sampleSummaries] = await Promise.all([
            readHeader(),
            readSampleSummaries()
          ]);
          const result2 = {
            status: header2.status,
            eval: header2.eval,
            plan: header2.plan,
            results: header2.results,
            stats: header2.stats,
            error: header2.error,
            sampleSummaries
          };
          return result2;
        },
        readSample,
        /**
         * Reads the complete log file.
         */
        readCompleteLog: async () => {
          const [evalLog, samples] = await Promise.all([
            readHeader(),
            listSamples().then(
              (sampleIds) => Promise.all(
                sampleIds.map(
                  ({ sampleId, epoch }) => readSample(sampleId, epoch).then(
                    (sample2) => sample2
                  )
                )
              )
            )
          ]);
          return {
            status: evalLog.status,
            eval: evalLog.eval,
            plan: evalLog.plan,
            results: evalLog.results,
            stats: evalLog.stats,
            error: evalLog.error,
            samples
          };
        }
      };
    };
    const isEvalFile = (file) => {
      return file.endsWith(".eval");
    };
    class SampleSizeLimitedExceededError extends Error {
      constructor(id, epoch, maxBytes) {
        super(
          `Sample ${id} in epoch ${epoch} exceeds the maximum supported size (${maxBytes / 1024 / 1024}MB) and cannot be loaded.`
        );
        __publicField(this, "id");
        __publicField(this, "epoch");
        __publicField(this, "maxBytes");
        __publicField(this, "displayStack");
        this.name = "SampleSizeLimitedExceededError";
        this.id = id;
        this.epoch = epoch;
        this.maxBytes = maxBytes;
        this.displayStack = false;
        Object.setPrototypeOf(this, SampleSizeLimitedExceededError.prototype);
      }
    }
    const clientApi = (api2, log_file) => {
      let current_log = void 0;
      let current_path = void 0;
      const loadedEvalFile = {
        file: void 0,
        remoteLog: void 0
      };
      const remoteEvalFile = async (log_file2, cached = false) => {
        if (!cached || loadedEvalFile.file !== log_file2) {
          loadedEvalFile.file = log_file2;
          loadedEvalFile.remoteLog = await openRemoteLogFile(
            api2,
            encodePathParts(log_file2),
            5
          );
        }
        return loadedEvalFile.remoteLog;
      };
      const get_log = async (log_file2, cached = false) => {
        if (!cached || log_file2 !== current_path || !current_log) {
          if (pending_log_promise) {
            return pending_log_promise;
          }
          pending_log_promise = api2.eval_log(log_file2, 100).then((log2) => {
            current_log = log2;
            current_path = log_file2;
            pending_log_promise = null;
            return log2;
          }).catch((err2) => {
            pending_log_promise = null;
            throw err2;
          });
          return pending_log_promise;
        }
        return current_log;
      };
      let pending_log_promise = null;
      const get_log_summary = async (log_file2) => {
        var _a2;
        if (isEvalFile(log_file2)) {
          const remoteLogFile = await remoteEvalFile(log_file2);
          if (remoteLogFile) {
            return await remoteLogFile.readLogSummary();
          } else {
            throw new Error("Unable to read remote eval file");
          }
        } else {
          const logContents = await get_log(log_file2);
          const sampleSummaries = logContents.parsed.samples ? (_a2 = logContents.parsed.samples) == null ? void 0 : _a2.map((sample2) => {
            var _a3;
            return {
              id: sample2.id,
              epoch: sample2.epoch,
              input: sample2.input,
              target: sample2.target,
              scores: sample2.scores,
              metadata: sample2.metadata,
              error: (_a3 = sample2.error) == null ? void 0 : _a3.message
            };
          }) : [];
          const parsed = logContents.parsed;
          return {
            version: parsed.version,
            status: parsed.status,
            eval: parsed.eval,
            plan: parsed.plan,
            results: parsed.results,
            stats: parsed.stats,
            error: parsed.error,
            sampleSummaries
          };
        }
      };
      const get_log_sample = async (log_file2, id, epoch) => {
        if (isEvalFile(log_file2)) {
          const remoteLogFile = await remoteEvalFile(log_file2, true);
          try {
            if (remoteLogFile) {
              const sample2 = await remoteLogFile.readSample(String(id), epoch);
              return sample2;
            } else {
              throw new Error(`Unable to read remove eval file ${log_file2}`);
            }
          } catch (error2) {
            if (error2 instanceof FileSizeLimitError) {
              throw new SampleSizeLimitedExceededError(id, epoch, error2.maxBytes);
            } else {
              throw error2;
            }
          }
        } else {
          const logContents = await get_log(log_file2, true);
          if (logContents.parsed.samples && logContents.parsed.samples.length > 0) {
            return logContents.parsed.samples.find((sample2) => {
              return sample2.id === id && sample2.epoch === epoch;
            });
          }
        }
        return void 0;
      };
      const get_eval_log_header = async (log_file2) => {
        const remoteLogFile = await openRemoteLogFile(
          api2,
          encodePathParts(log_file2),
          5
        );
        return remoteLogFile.readHeader();
      };
      const get_log_headers = async (log_files) => {
        const eval_files = {};
        const json_files = {};
        let index2 = 0;
        for (const file of log_files) {
          if (isEvalFile(file)) {
            eval_files[file] = index2;
          } else {
            json_files[file] = index2;
          }
          index2++;
        }
        const evalLogHeadersPromises = Object.keys(eval_files).map(
          (file) => get_eval_log_header(file).then((header2) => ({
            index: eval_files[file],
            // Store original index
            header: header2
          }))
        );
        const jsonLogHeadersPromise = api2.eval_log_headers(Object.keys(json_files)).then(
          (headers2) => headers2.map((header2, i2) => ({
            index: json_files[Object.keys(json_files)[i2]],
            // Store original index
            header: header2
          }))
        );
        const headers = await Promise.all([
          ...evalLogHeadersPromises,
          jsonLogHeadersPromise
        ]);
        const orderedHeaders = headers.flat().sort((a, b) => a.index - b.index);
        return orderedHeaders.map(({ header: header2 }) => header2);
      };
      const get_log_paths = async () => {
        const logFiles = await api2.eval_logs();
        if (logFiles) {
          return logFiles;
        } else if (log_file) {
          const summary2 = await get_log_summary(log_file);
          if (summary2) {
            return {
              files: [
                {
                  name: log_file,
                  task: summary2.eval.task,
                  task_id: summary2.eval.task_id
                }
              ]
            };
          }
        }
        throw new Error("Unable to determine log paths.");
      };
      return {
        client_events: () => {
          return api2.client_events();
        },
        get_log_paths: () => {
          return get_log_paths();
        },
        get_log_headers: (log_files) => {
          return get_log_headers(log_files);
        },
        get_log_summary,
        get_log_sample,
        open_log_file: (log_file2, log_dir) => {
          return api2.open_log_file(log_file2, log_dir);
        },
        download_file: (download_file2, file_contents) => {
          return api2.download_file(download_file2, file_contents);
        }
      };
    };
    const resolveApi = () => {
      if (getVscodeApi()) {
        return clientApi(api$1);
      } else {
        const scriptEl = document.getElementById("log_dir_context");
        if (scriptEl) {
          const context = scriptEl.textContent;
          if (context !== null) {
            const data = JSON.parse(context);
            if (data.log_dir || data.log_file) {
              const log_dir2 = data.log_dir || dirname(data.log_file);
              const api2 = simpleHttpApi(log_dir2, data.log_file);
              return clientApi(api2, data.log_file);
            }
          }
        }
        const urlParams = new URLSearchParams(window.location.search);
        const log_file = urlParams.get("log_file");
        const log_dir = urlParams.get("log_dir");
        if (log_file !== null || log_dir !== null) {
          const resolved_log_dir = log_dir === null ? void 0 : log_dir;
          const resolved_log_file = log_file === null ? void 0 : log_file;
          const api2 = simpleHttpApi(resolved_log_dir, resolved_log_file);
          return clientApi(api2, resolved_log_file);
        }
        return clientApi(browserApi);
      }
    };
    const api = resolveApi();
    const DownloadButton = ({
      label: label2,
      fileName,
      fileContents
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          className: "btn btn-outline-primary download-button",
          onClick: async () => {
            await api.download_file(fileName, fileContents);
          },
          children: label2
        }
      );
    };
    const DownloadPanel = ({
      message: message2,
      buttonLabel,
      fileName,
      fileContents
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "download-panel", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "download-panel-message", children: message2 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          DownloadButton,
          {
            label: buttonLabel,
            fileName,
            fileContents
          }
        )
      ] }) });
    };
    const jsonTab = "_jsonTab_6pq03_1";
    const styles$L = {
      jsonTab
    };
    const kJsonMaxSize = 1e7;
    const JsonTab = ({ logFile, capabilities: capabilities2, json }) => {
      if (logFile && json.length > kJsonMaxSize && capabilities2.downloadFiles) {
        const file = `${filename(logFile)}.json`;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$L.jsonTab, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          DownloadPanel,
          {
            message: "The JSON for this log file is too large to render.",
            buttonLabel: "Download JSON File",
            fileName: file,
            fileContents: json
          }
        ) });
      } else {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$L.jsonTab, children: /* @__PURE__ */ jsxRuntimeExports.jsx(JSONPanel, { id: "task-json-contents", json, simple: true }) });
      }
    };
    const EmptyPanel = ({ children: children2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "empty-panel", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "container", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: children2 }) }) });
    };
    const tabs$1 = "_tabs_1qj7d_1";
    const tabContents = "_tabContents_1qj7d_5";
    const scrollable = "_scrollable_1qj7d_10";
    const tab$1 = "_tab_1qj7d_1";
    const tabItem = "_tabItem_1qj7d_24";
    const tabIcon = "_tabIcon_1qj7d_28";
    const tabTools = "_tabTools_1qj7d_32";
    const moduleStyles = {
      tabs: tabs$1,
      tabContents,
      scrollable,
      tab: tab$1,
      tabItem,
      tabIcon,
      tabTools
    };
    const TabSet = ({
      id,
      type = "tabs",
      className: className2,
      tabPanelsClassName,
      tabControlsClassName,
      tools: tools2,
      children: children2
    }) => {
      const validTabs = flattenChildren(children2);
      if (validTabs.length === 0) return null;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "ul",
          {
            id,
            className: clsx("nav", `nav-${type}`, className2, moduleStyles.tabs),
            role: "tablist",
            "aria-orientation": "horizontal",
            children: [
              validTabs.map((tab2, index2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                Tab,
                {
                  index: index2,
                  type,
                  tab: tab2,
                  className: tabControlsClassName
                },
                tab2.props.id
              )),
              tools2 && /* @__PURE__ */ jsxRuntimeExports.jsx(TabTools, { tools: tools2 })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(TabPanels, { id, tabs: validTabs, className: tabPanelsClassName })
      ] });
    };
    const Tab = ({ type = "tabs", tab: tab2, index: index2, className: className2 }) => {
      const tabId = tab2.props.id || computeTabId("tabset", index2);
      const tabContentsId = computeTabContentsId(tab2.props.id);
      const isActive = tab2.props.selected;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("li", { role: "presentation", className: clsx("nav-item", moduleStyles.tabItem), children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          id: tabId,
          className: clsx(
            "nav-link",
            className2,
            isActive && "active",
            type === "pills" ? moduleStyles.pill : moduleStyles.tab,
            "text-size-small",
            "text-style-label"
          ),
          type: "button",
          role: "tab",
          "aria-controls": tabContentsId,
          "aria-selected": isActive,
          onClick: (e) => tab2.props.onSelected(e),
          children: [
            tab2.props.icon && /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: clsx(tab2.props.icon, moduleStyles.tabIcon) }),
            tab2.props.title
          ]
        }
      ) });
    };
    const TabPanels = ({ id, tabs: tabs2, className: className2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("tab-content", className2), id: `${id}-content`, children: tabs2.map((tab2, index2) => /* @__PURE__ */ jsxRuntimeExports.jsx(TabPanel, { ...tab2.props, index: index2 }, tab2.props.id)) });
    const TabPanel = ({
      id,
      selected: selected2,
      style: style2,
      scrollable: scrollable2 = true,
      scrollRef,
      className: className2,
      scrollPosition,
      setScrollPosition,
      children: children2
    }) => {
      const tabContentsId = computeTabContentsId(id);
      const panelRef = reactExports.useRef(null);
      const tabContentsRef = scrollRef || panelRef;
      reactExports.useEffect(() => {
        if (!selected2 || scrollPosition === void 0 || !tabContentsRef.current)
          return;
        const observer = new MutationObserver(() => {
          if (tabContentsRef.current) {
            tabContentsRef.current.scrollTop = scrollPosition;
          }
          observer.disconnect();
        });
        observer.observe(tabContentsRef.current, {
          childList: true,
          subtree: true
        });
        return () => observer.disconnect();
      }, []);
      const onScroll = reactExports.useCallback(
        (e) => {
          if (setScrollPosition) {
            setScrollPosition(e.currentTarget.scrollTop);
          }
        },
        [setScrollPosition]
      );
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id: tabContentsId,
          ref: tabContentsRef,
          className: clsx(
            "tab-pane",
            selected2 && "show active",
            className2,
            moduleStyles.tabContents,
            scrollable2 && moduleStyles.scrollable
          ),
          style: style2,
          onScroll,
          children: children2
        }
      );
    };
    const TabTools = ({ tools: tools2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("tab-tools", moduleStyles.tabTools), children: tools2 });
    const computeTabId = (id, index2) => `${id}-${index2}`;
    const computeTabContentsId = (id) => `${id}-contents`;
    const flattenChildren = (children2) => {
      return reactExports.Children.toArray(children2).flatMap((child) => {
        if (reactExports.isValidElement(child)) {
          const element = child;
          if (element.type === reactExports.Fragment) {
            return flattenChildren(element.props.children);
          }
          return element;
        }
        return [];
      });
    };
    function escapeSelector(id) {
      return id.replace(/([ #.;,?!+*~'":^$[\]()=>|/\\])/g, "\\$1");
    }
    const CardHeader = ({
      id,
      icon,
      label: label2,
      className: className2,
      children: children2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: clsx("card-header-container", "text-style-label", className2),
          id: id || "",
          children: [
            icon ? /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: clsx("card-header-icon", icon) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "card-header-icon" }),
            label2 ? label2 : "",
            " ",
            children2
          ]
        }
      );
    };
    const CardBody = ({ id, children: children2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "card-body", id: id || "", children: children2 });
    };
    const Card = ({ id, children: children2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "card", id, children: children2 });
    };
    const grid$5 = "_grid_ktnsp_1";
    const cell$1 = "_cell_ktnsp_8";
    const value = "_value_ktnsp_13";
    const styles$K = {
      grid: grid$5,
      cell: cell$1,
      value
    };
    const MetaDataGrid = ({
      id,
      entries,
      className: className2,
      style: style2,
      plain
    }) => {
      const baseId = "metadata-grid";
      const entryEls = entryRecords(entries).map((entry2, index2) => {
        const id2 = `${baseId}-value-${index2}`;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
          index2 !== 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              style: {
                gridColumn: "1 / -1",
                borderBottom: `${!plain ? "solid 1px var(--bs-light-border-subtle" : ""}`
              }
            }
          ) : void 0,
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                `${baseId}-key`,
                styles$K.cell,
                "text-style-label",
                "text-style-secondary",
                "text-size-small"
              ),
              children: entry2.name
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(styles$K.value, `${baseId}-value`, "text-size-small"),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(RenderedContent, { id: id2, entry: entry2 })
            }
          )
        ] }, `${baseId}-record-${index2}`);
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id, className: clsx(className2, styles$K.grid), style: style2, children: entryEls });
    };
    const entryRecords = (entries) => {
      if (!entries) {
        return [];
      }
      if (!Array.isArray(entries)) {
        return Object.entries(entries || {}).map(([key2, value2]) => {
          return { name: key2, value: value2 };
        });
      } else {
        return entries;
      }
    };
    const grid$4 = "_grid_3umed_1";
    const styles$J = {
      grid: grid$4
    };
    const SampleScores = ({
      sample: sample2,
      sampleDescriptor,
      scorer
    }) => {
      const scores2 = scorer ? sampleDescriptor.evalDescriptor.scorerDescriptor(sample2, { scorer, name: scorer }).scores() : sampleDescriptor.selectedScorerDescriptor(sample2).scores();
      if (scores2.length === 1) {
        return scores2[0].rendered();
      } else {
        const rows = scores2.map((score2) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { opacity: "0.7" }, children: score2.name }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: score2.rendered() })
          ] });
        });
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$J.grid, children: rows });
      }
    };
    const container$8 = "_container_1jqar_1";
    const label$1 = "_label_1jqar_6";
    const wordBreak = "_wordBreak_1jqar_14";
    const scoreTable = "_scoreTable_1jqar_18";
    const bottomBorder = "_bottomBorder_1jqar_23";
    const headerScore = "_headerScore_1jqar_27";
    const targetValue = "_targetValue_1jqar_31";
    const answerValue = "_answerValue_1jqar_37";
    const scoreValue = "_scoreValue_1jqar_42";
    const noLeft$1 = "_noLeft_1jqar_47";
    const noTop$1 = "_noTop_1jqar_51";
    const styles$I = {
      container: container$8,
      label: label$1,
      wordBreak,
      scoreTable,
      bottomBorder,
      headerScore,
      targetValue,
      answerValue,
      scoreValue,
      noLeft: noLeft$1,
      noTop: noTop$1
    };
    const SampleScoreView = ({
      sample: sample2,
      sampleDescriptor,
      className: className2,
      scorer
    }) => {
      if (!sampleDescriptor) {
        return null;
      }
      const scoreInput = inputString(sample2.input);
      if (sample2.choices && sample2.choices.length > 0) {
        scoreInput.push("");
        scoreInput.push(
          ...sample2.choices.map((choice, index2) => {
            return `${String.fromCharCode(65 + index2)}) ${choice}`;
          })
        );
      }
      const scorerDescriptor = sampleDescriptor.evalDescriptor.scorerDescriptor(
        sample2,
        { scorer, name: scorer }
      );
      const explanation2 = scorerDescriptor.explanation() || "(No Explanation)";
      const answer2 = scorerDescriptor.answer();
      const metadata2 = scorerDescriptor.metadata();
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: clsx(
            "container-fluid",
            className2,
            "font-size-base",
            styles$I.container
          ),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { label: "Score" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(CardBody, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      className: clsx(
                        styles$I.label,
                        "text-style-label",
                        "text-style-secondary"
                      ),
                      children: "Input"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    MarkdownDiv,
                    {
                      markdown: scoreInput.join("\n"),
                      className: styles$I.wordBreak
                    }
                  ) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: clsx("table", styles$I.scoreTable), children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { className: styles$I.bottomBorder, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "th",
                      {
                        className: clsx(
                          styles$I.label,
                          "text-style-label",
                          "text-style-secondary"
                        ),
                        children: "Target"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "th",
                      {
                        className: clsx(
                          styles$I.label,
                          "text-style-label",
                          "text-style-secondary"
                        ),
                        children: "Answer"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "th",
                      {
                        className: clsx(
                          styles$I.label,
                          "text-style-label",
                          "text-style-secondary",
                          styles$I.headerScore
                        ),
                        children: "Score"
                      }
                    )
                  ] }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { className: styles$I.bottomBorder, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: styles$I.targetValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      MarkdownDiv,
                      {
                        markdown: arrayToString(
                          arrayToString((sample2 == null ? void 0 : sample2.target) || "none")
                        ),
                        className: clsx("no-last-para-padding", styles$I.noLeft)
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: clsx(styles$I.answerValue), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      MarkdownDiv,
                      {
                        className: clsx("no-last-para-padding", styles$I.noLeft),
                        markdown: answer2
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: clsx(styles$I.scoreValue), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      SampleScores,
                      {
                        sample: sample2,
                        sampleDescriptor,
                        scorer
                      }
                    ) })
                  ] }) })
                ] })
              ] })
            ] }),
            explanation2 !== answer2 ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { label: "Explanation" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                MarkdownDiv,
                {
                  markdown: arrayToString(explanation2),
                  className: clsx("no-last-para-padding", styles$I.noLeft)
                }
              ) })
            ] }) : "",
            metadata2 && Object.keys(metadata2).length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { label: "Metadata" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                MetaDataGrid,
                {
                  id: "task-sample-score-metadata",
                  className: clsx("tab-pane", styles$I.noTop),
                  entries: metadata2
                }
              ) })
            ] }) : ""
          ]
        }
      );
    };
    const wrapper$3 = "_wrapper_sq96g_1";
    const col2$2 = "_col2_sq96g_8";
    const col1_3$1 = "_col1_3_sq96g_12";
    const col3$1 = "_col3_sq96g_16";
    const separator$3 = "_separator_sq96g_20";
    const padded$1 = "_padded_sq96g_26";
    const styles$H = {
      wrapper: wrapper$3,
      col2: col2$2,
      col1_3: col1_3$1,
      col3: col3$1,
      separator: separator$3,
      padded: padded$1
    };
    const ModelUsagePanel = ({ usage }) => {
      if (!usage) {
        return null;
      }
      const rows = [];
      if (usage.reasoning_tokens) {
        rows.push({
          label: "Reasoning",
          value: usage.reasoning_tokens,
          secondary: false,
          bordered: true
        });
        rows.push({
          label: "---",
          value: void 0,
          secondary: false,
          padded: true
        });
      }
      rows.push({
        label: "input",
        value: usage.input_tokens,
        secondary: false
      });
      if (usage.input_tokens_cache_read) {
        rows.push({
          label: "cache_read",
          value: usage.input_tokens_cache_read,
          secondary: true
        });
      }
      if (usage.input_tokens_cache_write) {
        rows.push({
          label: "cache_write",
          value: usage.input_tokens_cache_write,
          secondary: true
        });
      }
      rows.push({
        label: "Output",
        value: usage.output_tokens,
        secondary: false,
        bordered: true
      });
      rows.push({
        label: "---",
        value: void 0,
        secondary: false
      });
      rows.push({
        label: "Total",
        value: usage.total_tokens,
        secondary: false
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-small", styles$H.wrapper), children: rows.map((row2, idx) => {
        if (row2.label === "---") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                styles$H.separator,
                row2.padded ? styles$H.padded : void 0
              )
            },
            `$usage-sep-${idx}`
          );
        } else {
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  "text-style-label",
                  "text-style-secondary",
                  row2.secondary ? styles$H.col2 : styles$H.col1_3
                ),
                children: row2.label
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$H.col3, children: row2.value ? formatNumber(row2.value) : "" })
          ] }, `$usage-row-${idx}`);
        }
      }) });
    };
    const table = "_table_dbhwb_1";
    const tableTokens = "_tableTokens_dbhwb_6";
    const tableH = "_tableH_dbhwb_10";
    const model = "_model_dbhwb_15";
    const styles$G = {
      table,
      tableTokens,
      tableH,
      model
    };
    const TokenTable = ({ className: className2, children: children2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "table",
        {
          className: clsx(
            "table",
            "table-sm",
            "text-size-smaller",
            styles$G.table,
            className2
          ),
          children: children2
        }
      );
    };
    const TokenHeader = () => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("thead", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", {}),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "td",
            {
              colSpan: 3,
              className: clsx(
                "card-subheading",
                styles$G.tableTokens,
                "text-size-small",
                "text-style-label",
                "text-style-secondary"
              ),
              align: "center",
              children: "Tokens"
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "th",
            {
              className: clsx(
                styles$G.tableH,
                "text-sixe-small",
                "text-style-label",
                "text-style-secondary"
              ),
              children: "Model"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "th",
            {
              className: clsx(
                styles$G.tableH,
                "text-sixe-small",
                "text-style-label",
                "text-style-secondary"
              ),
              children: "Usage"
            }
          )
        ] })
      ] });
    };
    const TokenRow = ({ model: model2, usage }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$G.model, children: model2 }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(ModelUsagePanel, { usage }) })
      ] });
    };
    const ModelTokenTable = ({
      model_usage,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(TokenTable, { className: className2, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(TokenHeader, {}),
        /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: Object.keys(model_usage).map((key2) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(TokenRow, { model: key2, usage: model_usage[key2] }, key2);
        }) })
      ] });
    };
    const printHtml = (html, css) => {
      const printWindow = window.open("", "", "height=600,width=800");
      if (printWindow !== null) {
        printWindow.document.write("<html><head><title>Print</title>");
        printWindow.document.write(`
          <link rel="stylesheet" crossorigin="" href="./assets/index.css">
          <style>
            @media print {
              ${css}
            }
          </style>
        `);
        printWindow.document.write("</head><body>");
        printWindow.document.write(html);
        printWindow.document.write("</body></html>");
        printWindow.document.close();
        printWindow.onload = function() {
          printWindow.focus();
          printWindow.print();
          printWindow.close();
        };
      } else {
        console.error("Print window failed to open.");
      }
    };
    const printHeadingHtml = () => {
      const taskEl = document.getElementById("task-title");
      const modelEl = document.getElementById("task-model");
      const timeEl = document.getElementById("task-created");
      if (!taskEl || !modelEl || !timeEl) {
        throw new Error(
          "Failed to compute heading HTML. The task, model, or time element can't be found."
        );
      }
      const task2 = taskEl.innerText;
      const model2 = modelEl.innerText;
      const time = timeEl.innerText;
      const headingHtml = `
<div style="display: grid; grid-template-columns: repeat(3, 1fr); column-gap: 0.5em; margin-bottom: 2em; justify-content: space-between; border-bottom: solid 1px silver;">
<div style="font-weight: 600">${task2}</div>
<div style="text-align: center;">${model2}</div>
<div style="text-align: right;">${time}</div>
</div>`;
      return headingHtml;
    };
    const Ce = 0, Lt = 1, Yt = 2, En = 4;
    function sn(t2) {
      return () => t2;
    }
    function lo(t2) {
      t2();
    }
    function ne(t2, e) {
      return (n) => t2(e(n));
    }
    function ln(t2, e) {
      return () => t2(e);
    }
    function Hn(t2, e) {
      return (n) => t2(e, n);
    }
    function Ae(t2) {
      return t2 !== void 0;
    }
    function co(...t2) {
      return () => {
        t2.map(lo);
      };
    }
    function Gt() {
    }
    function ye(t2, e) {
      return e(t2), t2;
    }
    function uo(t2, e) {
      return e(t2);
    }
    function X(...t2) {
      return t2;
    }
    function K(t2, e) {
      return t2(Lt, e);
    }
    function M(t2, e) {
      t2(Ce, e);
    }
    function We(t2) {
      t2(Yt);
    }
    function lt(t2) {
      return t2(En);
    }
    function F(t2, e) {
      return K(t2, Hn(e, Ce));
    }
    function Rt(t2, e) {
      const n = t2(Lt, (o) => {
        n(), e(o);
      });
      return n;
    }
    function cn(t2) {
      let e, n;
      return (o) => (r2) => {
        e = r2, n && clearTimeout(n), n = setTimeout(() => {
          o(e);
        }, t2);
      };
    }
    function Bn(t2, e) {
      return t2 === e;
    }
    function Y(t2 = Bn) {
      let e;
      return (n) => (o) => {
        t2(e, o) || (e = o, n(o));
      };
    }
    function V(t2) {
      return (e) => (n) => {
        t2(n) && e(n);
      };
    }
    function H(t2) {
      return (e) => ne(e, t2);
    }
    function vt$1(t2) {
      return (e) => () => {
        e(t2);
      };
    }
    function x(t2, ...e) {
      const n = ao(...e);
      return (o, r2) => {
        switch (o) {
          case Yt:
            We(t2);
            return;
          case Lt:
            return K(t2, n(r2));
        }
      };
    }
    function bt(t2, e) {
      return (n) => (o) => {
        n(e = t2(e, o));
      };
    }
    function qt(t2) {
      return (e) => (n) => {
        t2 > 0 ? t2-- : e(n);
      };
    }
    function zt(t2) {
      let e = null, n;
      return (o) => (r2) => {
        e = r2, !n && (n = setTimeout(() => {
          n = void 0, o(e);
        }, t2));
      };
    }
    function G(...t2) {
      const e = new Array(t2.length);
      let n = 0, o = null;
      const r2 = Math.pow(2, t2.length) - 1;
      return t2.forEach((s, i2) => {
        const l = Math.pow(2, i2);
        K(s, (c2) => {
          const d = n;
          n = n | l, e[i2] = c2, d !== r2 && n === r2 && o && (o(), o = null);
        });
      }), (s) => (i2) => {
        const l = () => {
          s([i2].concat(e));
        };
        n === r2 ? l() : o = l;
      };
    }
    function ao(...t2) {
      return (e) => t2.reduceRight(uo, e);
    }
    function fo(t2) {
      let e, n;
      const o = () => e == null ? void 0 : e();
      return function(r2, s) {
        switch (r2) {
          case Lt:
            return s ? n === s ? void 0 : (o(), n = s, e = K(t2, s), e) : (o(), Gt);
          case Yt:
            o(), n = null;
            return;
        }
      };
    }
    function w(t2) {
      let e = t2;
      const n = $();
      return (o, r2) => {
        switch (o) {
          case Ce:
            e = r2;
            break;
          case Lt: {
            r2(e);
            break;
          }
          case En:
            return e;
        }
        return n(o, r2);
      };
    }
    function ct(t2, e) {
      return ye(w(e), (n) => F(t2, n));
    }
    function $() {
      const t2 = [];
      return (e, n) => {
        switch (e) {
          case Ce:
            t2.slice().forEach((o) => {
              o(n);
            });
            return;
          case Yt:
            t2.splice(0, t2.length);
            return;
          case Lt:
            return t2.push(n), () => {
              const o = t2.indexOf(n);
              o > -1 && t2.splice(o, 1);
            };
        }
      };
    }
    function pt(t2) {
      return ye($(), (e) => F(t2, e));
    }
    function U(t2, e = [], { singleton: n } = { singleton: true }) {
      return {
        constructor: t2,
        dependencies: e,
        id: mo(),
        singleton: n
      };
    }
    const mo = () => Symbol();
    function po(t2) {
      const e = /* @__PURE__ */ new Map(), n = ({ constructor: o, dependencies: r2, id: s, singleton: i2 }) => {
        if (i2 && e.has(s))
          return e.get(s);
        const l = o(r2.map((c2) => n(c2)));
        return i2 && e.set(s, l), l;
      };
      return n(t2);
    }
    function rt(...t2) {
      const e = $(), n = new Array(t2.length);
      let o = 0;
      const r2 = Math.pow(2, t2.length) - 1;
      return t2.forEach((s, i2) => {
        const l = Math.pow(2, i2);
        K(s, (c2) => {
          n[i2] = c2, o = o | l, o === r2 && M(e, n);
        });
      }), function(s, i2) {
        switch (s) {
          case Yt: {
            We(e);
            return;
          }
          case Lt:
            return o === r2 && i2(n), K(e, i2);
        }
      };
    }
    function A(t2, e = Bn) {
      return x(t2, Y(e));
    }
    function un(...t2) {
      return function(e, n) {
        switch (e) {
          case Yt:
            return;
          case Lt:
            return co(...t2.map((o) => K(o, n)));
        }
      };
    }
    var ht = /* @__PURE__ */ ((t2) => (t2[t2.DEBUG = 0] = "DEBUG", t2[t2.INFO = 1] = "INFO", t2[t2.WARN = 2] = "WARN", t2[t2.ERROR = 3] = "ERROR", t2))(ht || {});
    const ho = {
      0: "debug",
      3: "error",
      1: "log",
      2: "warn"
    }, go = () => typeof globalThis > "u" ? window : globalThis, Pt = U(
      () => {
        const t2 = w(
          3
          /* ERROR */
        );
        return {
          log: w((n, o, r2 = 1) => {
            var i2;
            const s = (i2 = go().VIRTUOSO_LOG_LEVEL) != null ? i2 : lt(t2);
            r2 >= s && console[ho[r2]](
              "%creact-virtuoso: %c%s %o",
              "color: #0253b3; font-weight: bold",
              "color: initial",
              n,
              o
            );
          }),
          logLevel: t2
        };
      },
      [],
      { singleton: true }
    );
    function Et(t2, e, n) {
      return Me(t2, e, n).callbackRef;
    }
    function Me(t2, e, n) {
      const o = React$2.useRef(null);
      let r2 = (s) => {
      };
      if (typeof ResizeObserver < "u") {
        const s = React$2.useMemo(() => new ResizeObserver((i2) => {
          const l = () => {
            const c2 = i2[0].target;
            c2.offsetParent !== null && t2(c2);
          };
          n ? l() : requestAnimationFrame(l);
        }), [t2]);
        r2 = (i2) => {
          i2 && e ? (s.observe(i2), o.current = i2) : (o.current && s.unobserve(o.current), o.current = null);
        };
      }
      return { callbackRef: r2, ref: o };
    }
    function kn(t2, e, n, o, r2, s, i2, l, c2) {
      const d = React$2.useCallback(
        (f) => {
          const S = Io(f.children, e, l ? "offsetWidth" : "offsetHeight", r2);
          let p = f.parentElement;
          for (; !p.dataset.virtuosoScroller; )
            p = p.parentElement;
          const m = p.lastElementChild.dataset.viewportType === "window", C2 = i2 ? l ? i2.scrollLeft : i2.scrollTop : m ? l ? window.pageXOffset || document.documentElement.scrollLeft : window.pageYOffset || document.documentElement.scrollTop : l ? p.scrollLeft : p.scrollTop, I = i2 ? l ? i2.scrollWidth : i2.scrollHeight : m ? l ? document.documentElement.scrollWidth : document.documentElement.scrollHeight : l ? p.scrollWidth : p.scrollHeight, y = i2 ? l ? i2.offsetWidth : i2.offsetHeight : m ? l ? window.innerWidth : window.innerHeight : l ? p.offsetWidth : p.offsetHeight;
          o({
            scrollHeight: I,
            scrollTop: Math.max(C2, 0),
            viewportHeight: y
          }), s == null || s(
            l ? an("column-gap", getComputedStyle(f).columnGap, r2) : an("row-gap", getComputedStyle(f).rowGap, r2)
          ), S !== null && t2(S);
        },
        [t2, e, r2, s, i2, o]
      );
      return Me(d, n, c2);
    }
    function Io(t2, e, n, o) {
      const r2 = t2.length;
      if (r2 === 0)
        return null;
      const s = [];
      for (let i2 = 0; i2 < r2; i2++) {
        const l = t2.item(i2);
        if (l.dataset.index === void 0)
          continue;
        const c2 = parseInt(l.dataset.index), d = parseFloat(l.dataset.knownSize), f = e(l, n);
        if (f === 0 && o("Zero-sized element, this should not happen", { child: l }, ht.ERROR), f === d)
          continue;
        const S = s[s.length - 1];
        s.length === 0 || S.size !== f || S.endIndex !== c2 - 1 ? s.push({ endIndex: c2, size: f, startIndex: c2 }) : s[s.length - 1].endIndex++;
      }
      return s;
    }
    function an(t2, e, n) {
      return e !== "normal" && !(e != null && e.endsWith("px")) && n(`${t2} was not resolved to pixel value correctly`, e, ht.WARN), e === "normal" ? 0 : parseInt(e != null ? e : "0", 10);
    }
    function _e(t2, e, n) {
      const o = React$2.useRef(null), r2 = React$2.useCallback(
        (c2) => {
          if (!(c2 != null && c2.offsetParent))
            return;
          const d = c2.getBoundingClientRect(), f = d.width;
          let S, p;
          if (e) {
            const m = e.getBoundingClientRect(), C2 = d.top - m.top;
            p = m.height - Math.max(0, C2), S = C2 + e.scrollTop;
          } else
            p = window.innerHeight - Math.max(0, d.top), S = d.top + window.pageYOffset;
          o.current = {
            offsetTop: S,
            visibleHeight: p,
            visibleWidth: f
          }, t2(o.current);
        },
        [t2, e]
      ), { callbackRef: s, ref: i2 } = Me(r2, true, n), l = React$2.useCallback(() => {
        r2(i2.current);
      }, [r2, i2]);
      return React$2.useEffect(() => {
        if (e) {
          e.addEventListener("scroll", l);
          const c2 = new ResizeObserver(() => {
            requestAnimationFrame(l);
          });
          return c2.observe(e), () => {
            e.removeEventListener("scroll", l), c2.unobserve(e);
          };
        } else
          return window.addEventListener("scroll", l), window.addEventListener("resize", l), () => {
            window.removeEventListener("scroll", l), window.removeEventListener("resize", l);
          };
      }, [l, e]), s;
    }
    const at = U(
      () => {
        const t2 = $(), e = $(), n = w(0), o = $(), r2 = w(0), s = $(), i2 = $(), l = w(0), c2 = w(0), d = w(0), f = w(0), S = $(), p = $(), m = w(false), C2 = w(false), I = w(false);
        return F(
          x(
            t2,
            H(({ scrollTop: y }) => y)
          ),
          e
        ), F(
          x(
            t2,
            H(({ scrollHeight: y }) => y)
          ),
          i2
        ), F(e, r2), {
          deviation: n,
          fixedFooterHeight: d,
          fixedHeaderHeight: c2,
          footerHeight: f,
          headerHeight: l,
          horizontalDirection: C2,
          scrollBy: p,
          // input
          scrollContainerState: t2,
          scrollHeight: i2,
          scrollingInProgress: m,
          // signals
          scrollTo: S,
          scrollTop: e,
          skipAnimationFrameInResizeObserver: I,
          smoothScrollTargetReached: o,
          // state
          statefulScrollTop: r2,
          viewportHeight: s
        };
      },
      [],
      { singleton: true }
    ), oe = { lvl: 0 };
    function On(t2, e) {
      const n = t2.length;
      if (n === 0)
        return [];
      let { index: o, value: r2 } = e(t2[0]);
      const s = [];
      for (let i2 = 1; i2 < n; i2++) {
        const { index: l, value: c2 } = e(t2[i2]);
        s.push({ end: l - 1, start: o, value: r2 }), o = l, r2 = c2;
      }
      return s.push({ end: 1 / 0, start: o, value: r2 }), s;
    }
    function j(t2) {
      return t2 === oe;
    }
    function re(t2, e) {
      if (!j(t2))
        return e === t2.k ? t2.v : e < t2.k ? re(t2.l, e) : re(t2.r, e);
    }
    function wt(t2, e, n = "k") {
      if (j(t2))
        return [-1 / 0, void 0];
      if (Number(t2[n]) === e)
        return [t2.k, t2.v];
      if (Number(t2[n]) < e) {
        const o = wt(t2.r, e, n);
        return o[0] === -1 / 0 ? [t2.k, t2.v] : o;
      }
      return wt(t2.l, e, n);
    }
    function mt(t2, e, n) {
      return j(t2) ? Ln(e, n, 1) : e === t2.k ? ot(t2, { k: e, v: n }) : e < t2.k ? dn(ot(t2, { l: mt(t2.l, e, n) })) : dn(ot(t2, { r: mt(t2.r, e, n) }));
    }
    function Kt() {
      return oe;
    }
    function ve(t2, e, n) {
      if (j(t2))
        return [];
      const o = wt(t2, e)[0];
      return So(ze(t2, o, n));
    }
    function Fe(t2, e) {
      if (j(t2)) return oe;
      const { k: n, l: o, r: r2 } = t2;
      if (e === n) {
        if (j(o))
          return r2;
        if (j(r2))
          return o;
        {
          const [s, i2] = zn(o);
          return ge(ot(t2, { k: s, l: Fn(o), v: i2 }));
        }
      } else return e < n ? ge(ot(t2, { l: Fe(o, e) })) : ge(ot(t2, { r: Fe(r2, e) }));
    }
    function _t(t2) {
      return j(t2) ? [] : [..._t(t2.l), { k: t2.k, v: t2.v }, ..._t(t2.r)];
    }
    function ze(t2, e, n) {
      if (j(t2))
        return [];
      const { k: o, l: r2, r: s, v: i2 } = t2;
      let l = [];
      return o > e && (l = l.concat(ze(r2, e, n))), o >= e && o <= n && l.push({ k: o, v: i2 }), o <= n && (l = l.concat(ze(s, e, n))), l;
    }
    function ge(t2) {
      const { l: e, lvl: n, r: o } = t2;
      if (o.lvl >= n - 1 && e.lvl >= n - 1)
        return t2;
      if (n > o.lvl + 1) {
        if (He(e))
          return Pn(ot(t2, { lvl: n - 1 }));
        if (!j(e) && !j(e.r))
          return ot(e.r, {
            l: ot(e, { r: e.r.l }),
            lvl: n,
            r: ot(t2, {
              l: e.r.r,
              lvl: n - 1
            })
          });
        throw new Error("Unexpected empty nodes");
      } else {
        if (He(t2))
          return Le(ot(t2, { lvl: n - 1 }));
        if (!j(o) && !j(o.l)) {
          const r2 = o.l, s = He(r2) ? o.lvl - 1 : o.lvl;
          return ot(r2, {
            l: ot(t2, {
              lvl: n - 1,
              r: r2.l
            }),
            lvl: r2.lvl + 1,
            r: Le(ot(o, { l: r2.r, lvl: s }))
          });
        } else
          throw new Error("Unexpected empty nodes");
      }
    }
    function ot(t2, e) {
      return Ln(
        e.k !== void 0 ? e.k : t2.k,
        e.v !== void 0 ? e.v : t2.v,
        e.lvl !== void 0 ? e.lvl : t2.lvl,
        e.l !== void 0 ? e.l : t2.l,
        e.r !== void 0 ? e.r : t2.r
      );
    }
    function Fn(t2) {
      return j(t2.r) ? t2.l : ge(ot(t2, { r: Fn(t2.r) }));
    }
    function He(t2) {
      return j(t2) || t2.lvl > t2.r.lvl;
    }
    function zn(t2) {
      return j(t2.r) ? [t2.k, t2.v] : zn(t2.r);
    }
    function Ln(t2, e, n, o = oe, r2 = oe) {
      return { k: t2, l: o, lvl: n, r: r2, v: e };
    }
    function dn(t2) {
      return Le(Pn(t2));
    }
    function Pn(t2) {
      const { l: e } = t2;
      return !j(e) && e.lvl === t2.lvl ? ot(e, { r: ot(t2, { l: e.r }) }) : t2;
    }
    function Le(t2) {
      const { lvl: e, r: n } = t2;
      return !j(n) && !j(n.r) && n.lvl === e && n.r.lvl === e ? ot(n, { l: ot(t2, { r: n.l }), lvl: e + 1 }) : t2;
    }
    function So(t2) {
      return On(t2, ({ k: e, v: n }) => ({ index: e, value: n }));
    }
    function Vn(t2, e) {
      return !!(t2 && t2.startIndex === e.startIndex && t2.endIndex === e.endIndex);
    }
    function se(t2, e) {
      return !!(t2 && t2[0] === e[0] && t2[1] === e[1]);
    }
    const Ge = U(
      () => ({ recalcInProgress: w(false) }),
      [],
      { singleton: true }
    );
    function An(t2, e, n) {
      return t2[Se(t2, e, n)];
    }
    function Se(t2, e, n, o = 0) {
      let r2 = t2.length - 1;
      for (; o <= r2; ) {
        const s = Math.floor((o + r2) / 2), i2 = t2[s], l = n(i2, e);
        if (l === 0)
          return s;
        if (l === -1) {
          if (r2 - o < 2)
            return s - 1;
          r2 = s - 1;
        } else {
          if (r2 === o)
            return s;
          o = s + 1;
        }
      }
      throw new Error(`Failed binary finding record in array - ${t2.join(",")}, searched for ${e}`);
    }
    function xo(t2, e, n, o) {
      const r2 = Se(t2, e, o), s = Se(t2, n, o, r2);
      return t2.slice(r2, s + 1);
    }
    function Ct(t2, e) {
      return Math.round(t2.getBoundingClientRect()[e]);
    }
    function be(t2) {
      return !j(t2.groupOffsetTree);
    }
    function Ne({ index: t2 }, e) {
      return e === t2 ? 0 : e < t2 ? -1 : 1;
    }
    function To() {
      return {
        groupIndices: [],
        groupOffsetTree: Kt(),
        lastIndex: 0,
        lastOffset: 0,
        lastSize: 0,
        offsetTree: [],
        sizeTree: Kt()
      };
    }
    function wo(t2, e) {
      let n = j(t2) ? 0 : 1 / 0;
      for (const o of e) {
        const { endIndex: r2, size: s, startIndex: i2 } = o;
        if (n = Math.min(n, i2), j(t2)) {
          t2 = mt(t2, 0, s);
          continue;
        }
        const l = ve(t2, i2 - 1, r2 + 1);
        if (l.some(Ho(o)))
          continue;
        let c2 = false, d = false;
        for (const { end: f, start: S, value: p } of l)
          c2 ? (r2 >= S || s === p) && (t2 = Fe(t2, S)) : (d = p !== s, c2 = true), f > r2 && r2 >= S && p !== s && (t2 = mt(t2, r2 + 1, p));
        d && (t2 = mt(t2, i2, s));
      }
      return [t2, n];
    }
    function Co(t2) {
      return typeof t2.groupIndex < "u";
    }
    function yo({ offset: t2 }, e) {
      return e === t2 ? 0 : e < t2 ? -1 : 1;
    }
    function ie(t2, e, n) {
      if (e.length === 0)
        return 0;
      const { index: o, offset: r2, size: s } = An(e, t2, Ne), i2 = t2 - o, l = s * i2 + (i2 - 1) * n + r2;
      return l > 0 ? l + n : l;
    }
    function Wn(t2, e) {
      if (!be(e))
        return t2;
      let n = 0;
      for (; e.groupIndices[n] <= t2 + n; )
        n++;
      return t2 + n;
    }
    function Mn(t2, e, n) {
      if (Co(t2))
        return e.groupIndices[t2.groupIndex] + 1;
      {
        const o = t2.index === "LAST" ? n : t2.index;
        let r2 = Wn(o, e);
        return r2 = Math.max(0, r2, Math.min(n, r2)), r2;
      }
    }
    function vo(t2, e, n, o = 0) {
      return o > 0 && (e = Math.max(e, An(t2, o, Ne).offset)), On(xo(t2, e, n, yo), Eo);
    }
    function bo(t2, [e, n, o, r2]) {
      e.length > 0 && o("received item sizes", e, ht.DEBUG);
      const s = t2.sizeTree;
      let i2 = s, l = 0;
      if (n.length > 0 && j(s) && e.length === 2) {
        const p = e[0].size, m = e[1].size;
        i2 = n.reduce((C2, I) => mt(mt(C2, I, p), I + 1, m), i2);
      } else
        [i2, l] = wo(i2, e);
      if (i2 === s)
        return t2;
      const { lastIndex: c2, lastOffset: d, lastSize: f, offsetTree: S } = Pe(t2.offsetTree, l, i2, r2);
      return {
        groupIndices: n,
        groupOffsetTree: n.reduce((p, m) => mt(p, m, ie(m, S, r2)), Kt()),
        lastIndex: c2,
        lastOffset: d,
        lastSize: f,
        offsetTree: S,
        sizeTree: i2
      };
    }
    function Ro(t2) {
      return _t(t2).map(({ k: e, v: n }, o, r2) => {
        const s = r2[o + 1];
        return { endIndex: s ? s.k - 1 : 1 / 0, size: n, startIndex: e };
      });
    }
    function fn(t2, e) {
      let n = 0, o = 0;
      for (; n < t2; )
        n += e[o + 1] - e[o] - 1, o++;
      return o - (n === t2 ? 0 : 1);
    }
    function Pe(t2, e, n, o) {
      let r2 = t2, s = 0, i2 = 0, l = 0, c2 = 0;
      if (e !== 0) {
        c2 = Se(r2, e - 1, Ne), l = r2[c2].offset;
        const f = wt(n, e - 1);
        s = f[0], i2 = f[1], r2.length && r2[c2].size === wt(n, e)[1] && (c2 -= 1), r2 = r2.slice(0, c2 + 1);
      } else
        r2 = [];
      for (const { start: d, value: f } of ve(n, e, 1 / 0)) {
        const S = d - s, p = S * i2 + l + S * o;
        r2.push({
          index: d,
          offset: p,
          size: f
        }), s = d, l = p, i2 = f;
      }
      return {
        lastIndex: s,
        lastOffset: l,
        lastSize: i2,
        offsetTree: r2
      };
    }
    function Eo(t2) {
      return { index: t2.index, value: t2 };
    }
    function Ho(t2) {
      const { endIndex: e, size: n, startIndex: o } = t2;
      return (r2) => r2.start === o && (r2.end === e || r2.end === 1 / 0) && r2.value === n;
    }
    const Bo = {
      offsetHeight: "height",
      offsetWidth: "width"
    }, Ht = U(
      ([{ log: t2 }, { recalcInProgress: e }]) => {
        const n = $(), o = $(), r2 = ct(o, 0), s = $(), i2 = $(), l = w(0), c2 = w([]), d = w(void 0), f = w(void 0), S = w((h, a) => Ct(h, Bo[a])), p = w(void 0), m = w(0), C2 = To(), I = ct(
          x(n, G(c2, t2, m), bt(bo, C2), Y()),
          C2
        ), y = ct(
          x(
            c2,
            Y(),
            bt((h, a) => ({ current: a, prev: h.current }), {
              current: [],
              prev: []
            }),
            H(({ prev: h }) => h)
          ),
          []
        );
        F(
          x(
            c2,
            V((h) => h.length > 0),
            G(I, m),
            H(([h, a, R]) => {
              const k = h.reduce((O, z, P2) => mt(O, z, ie(z, a.offsetTree, R) || P2), Kt());
              return {
                ...a,
                groupIndices: h,
                groupOffsetTree: k
              };
            })
          ),
          I
        ), F(
          x(
            o,
            G(I),
            V(([h, { lastIndex: a }]) => h < a),
            H(([h, { lastIndex: a, lastSize: R }]) => [
              {
                endIndex: a,
                size: R,
                startIndex: h
              }
            ])
          ),
          n
        ), F(d, f);
        const g = ct(
          x(
            d,
            H((h) => h === void 0)
          ),
          true
        );
        F(
          x(
            f,
            V((h) => h !== void 0 && j(lt(I).sizeTree)),
            H((h) => [{ endIndex: 0, size: h, startIndex: 0 }])
          ),
          n
        );
        const u = pt(
          x(
            n,
            G(I),
            bt(
              ({ sizes: h }, [a, R]) => ({
                changed: R !== h,
                sizes: R
              }),
              { changed: false, sizes: C2 }
            ),
            H((h) => h.changed)
          )
        );
        K(
          x(
            l,
            bt(
              (h, a) => ({ diff: h.prev - a, prev: a }),
              { diff: 0, prev: 0 }
            ),
            H((h) => h.diff)
          ),
          (h) => {
            const { groupIndices: a } = lt(I);
            if (h > 0)
              M(e, true), M(s, h + fn(h, a));
            else if (h < 0) {
              const R = lt(y);
              R.length > 0 && (h -= fn(-h, R)), M(i2, h);
            }
          }
        ), K(x(l, G(t2)), ([h, a]) => {
          h < 0 && a(
            "`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",
            { firstItemIndex: l },
            ht.ERROR
          );
        });
        const T = pt(s);
        F(
          x(
            s,
            G(I),
            H(([h, a]) => {
              const R = a.groupIndices.length > 0, k = [], O = a.lastSize;
              if (R) {
                const z = re(a.sizeTree, 0);
                let P2 = 0, D = 0;
                for (; P2 < h; ) {
                  const B = a.groupIndices[D], q = a.groupIndices.length === D + 1 ? 1 / 0 : a.groupIndices[D + 1] - B - 1;
                  k.push({
                    endIndex: B,
                    size: z,
                    startIndex: B
                  }), k.push({
                    endIndex: B + 1 + q - 1,
                    size: O,
                    startIndex: B + 1
                  }), D++, P2 += q + 1;
                }
                const J = _t(a.sizeTree);
                return P2 !== h && J.shift(), J.reduce(
                  (B, { k: q, v: st }) => {
                    let dt = B.ranges;
                    return B.prevSize !== 0 && (dt = [
                      ...B.ranges,
                      {
                        endIndex: q + h - 1,
                        size: B.prevSize,
                        startIndex: B.prevIndex
                      }
                    ]), {
                      prevIndex: q + h,
                      prevSize: st,
                      ranges: dt
                    };
                  },
                  {
                    prevIndex: h,
                    prevSize: 0,
                    ranges: k
                  }
                ).ranges;
              }
              return _t(a.sizeTree).reduce(
                (z, { k: P2, v: D }) => ({
                  prevIndex: P2 + h,
                  prevSize: D,
                  ranges: [...z.ranges, { endIndex: P2 + h - 1, size: z.prevSize, startIndex: z.prevIndex }]
                }),
                {
                  prevIndex: 0,
                  prevSize: O,
                  ranges: []
                }
              ).ranges;
            })
          ),
          n
        );
        const b = pt(
          x(
            i2,
            G(I, m),
            H(([h, { offsetTree: a }, R]) => {
              const k = -h;
              return ie(k, a, R);
            })
          )
        );
        return F(
          x(
            i2,
            G(I, m),
            H(([h, a, R]) => {
              if (a.groupIndices.length > 0) {
                if (j(a.sizeTree))
                  return a;
                let O = Kt();
                const z = lt(y);
                let P2 = 0, D = 0, J = 0;
                for (; P2 < -h; ) {
                  J = z[D];
                  const B = z[D + 1] - J - 1;
                  D++, P2 += B + 1;
                }
                if (O = _t(a.sizeTree).reduce((B, { k: q, v: st }) => mt(B, Math.max(0, q + h), st), O), P2 !== -h) {
                  const B = re(a.sizeTree, J);
                  O = mt(O, 0, B);
                  const q = wt(a.sizeTree, -h + 1)[1];
                  O = mt(O, 1, q);
                }
                return {
                  ...a,
                  sizeTree: O,
                  ...Pe(a.offsetTree, 0, O, R)
                };
              } else {
                const O = _t(a.sizeTree).reduce((z, { k: P2, v: D }) => mt(z, Math.max(0, P2 + h), D), Kt());
                return {
                  ...a,
                  sizeTree: O,
                  ...Pe(a.offsetTree, 0, O, R)
                };
              }
            })
          ),
          I
        ), {
          beforeUnshiftWith: T,
          // input
          data: p,
          defaultItemSize: f,
          firstItemIndex: l,
          fixedItemSize: d,
          gap: m,
          groupIndices: c2,
          itemSize: S,
          listRefresh: u,
          shiftWith: i2,
          shiftWithOffset: b,
          sizeRanges: n,
          // output
          sizes: I,
          statefulTotalCount: r2,
          totalCount: o,
          trackItemSizes: g,
          unshiftWith: s
        };
      },
      X(Pt, Ge),
      { singleton: true }
    );
    function ko(t2) {
      return t2.reduce(
        (e, n) => (e.groupIndices.push(e.totalCount), e.totalCount += n + 1, e),
        {
          groupIndices: [],
          totalCount: 0
        }
      );
    }
    const _n = U(
      ([{ groupIndices: t2, sizes: e, totalCount: n }, { headerHeight: o, scrollTop: r2 }]) => {
        const s = $(), i2 = $(), l = pt(x(s, H(ko)));
        return F(
          x(
            l,
            H((c2) => c2.totalCount)
          ),
          n
        ), F(
          x(
            l,
            H((c2) => c2.groupIndices)
          ),
          t2
        ), F(
          x(
            rt(r2, e, o),
            V(([c2, d]) => be(d)),
            H(([c2, d, f]) => wt(d.groupOffsetTree, Math.max(c2 - f, 0), "v")[0]),
            Y(),
            H((c2) => [c2])
          ),
          i2
        ), { groupCounts: s, topItemsIndexes: i2 };
      },
      X(Ht, at)
    ), Vt$1 = U(
      ([{ log: t2 }]) => {
        const e = w(false), n = pt(
          x(
            e,
            V((o) => o),
            Y()
          )
        );
        return K(e, (o) => {
          o && lt(t2)("props updated", {}, ht.DEBUG);
        }), { didMount: n, propsReady: e };
      },
      X(Pt),
      { singleton: true }
    ), Oo = typeof document < "u" && "scrollBehavior" in document.documentElement.style;
    function Gn(t2) {
      const e = typeof t2 == "number" ? { index: t2 } : t2;
      return e.align || (e.align = "start"), (!e.behavior || !Oo) && (e.behavior = "auto"), e.offset || (e.offset = 0), e;
    }
    const ce = U(
      ([
        { gap: t2, listRefresh: e, sizes: n, totalCount: o },
        {
          fixedFooterHeight: r2,
          fixedHeaderHeight: s,
          footerHeight: i2,
          headerHeight: l,
          scrollingInProgress: c2,
          scrollTo: d,
          smoothScrollTargetReached: f,
          viewportHeight: S
        },
        { log: p }
      ]) => {
        const m = $(), C2 = $(), I = w(0);
        let y = null, g = null, u = null;
        function T() {
          y && (y(), y = null), u && (u(), u = null), g && (clearTimeout(g), g = null), M(c2, false);
        }
        return F(
          x(
            m,
            G(n, S, o, I, l, i2, p),
            G(t2, s, r2),
            H(
              ([
                [b, h, a, R, k, O, z, P2],
                D,
                J,
                nt
              ]) => {
                const B = Gn(b), { align: q, behavior: st, offset: dt } = B, St = R - 1, ft = Mn(B, h, St);
                let ut = ie(ft, h.offsetTree, D) + O;
                q === "end" ? (ut += J + wt(h.sizeTree, ft)[1] - a + nt, ft === St && (ut += z)) : q === "center" ? ut += (J + wt(h.sizeTree, ft)[1] - a + nt) / 2 : ut -= k, dt && (ut += dt);
                const At = (xt) => {
                  T(), xt ? (P2("retrying to scroll to", { location: b }, ht.DEBUG), M(m, b)) : (M(C2, true), P2("list did not change, scroll successful", {}, ht.DEBUG));
                };
                if (T(), st === "smooth") {
                  let xt = false;
                  u = K(e, (Xt) => {
                    xt = xt || Xt;
                  }), y = Rt(f, () => {
                    At(xt);
                  });
                } else
                  y = Rt(x(e, Fo(150)), At);
                return g = setTimeout(() => {
                  T();
                }, 1200), M(c2, true), P2("scrolling from index to", { behavior: st, index: ft, top: ut }, ht.DEBUG), { behavior: st, top: ut };
              }
            )
          ),
          d
        ), {
          scrollTargetReached: C2,
          scrollToIndex: m,
          topListHeight: I
        };
      },
      X(Ht, at, Pt),
      { singleton: true }
    );
    function Fo(t2) {
      return (e) => {
        const n = setTimeout(() => {
          e(false);
        }, t2);
        return (o) => {
          o && (e(true), clearTimeout(n));
        };
      };
    }
    function De(t2, e) {
      t2 == 0 ? e() : requestAnimationFrame(() => {
        De(t2 - 1, e);
      });
    }
    function $e(t2, e) {
      const n = e - 1;
      return typeof t2 == "number" ? t2 : t2.index === "LAST" ? n : t2.index;
    }
    const ue = U(
      ([{ defaultItemSize: t2, listRefresh: e, sizes: n }, { scrollTop: o }, { scrollTargetReached: r2, scrollToIndex: s }, { didMount: i2 }]) => {
        const l = w(true), c2 = w(0), d = w(true);
        return F(
          x(
            i2,
            G(c2),
            V(([f, S]) => !!S),
            vt$1(false)
          ),
          l
        ), F(
          x(
            i2,
            G(c2),
            V(([f, S]) => !!S),
            vt$1(false)
          ),
          d
        ), K(
          x(
            rt(e, i2),
            G(l, n, t2, d),
            V(([[, f], S, { sizeTree: p }, m, C2]) => f && (!j(p) || Ae(m)) && !S && !C2),
            G(c2)
          ),
          ([, f]) => {
            Rt(r2, () => {
              M(d, true);
            }), De(4, () => {
              Rt(o, () => {
                M(l, true);
              }), M(s, f);
            });
          }
        ), {
          initialItemFinalLocationReached: d,
          initialTopMostItemIndex: c2,
          scrolledToInitialItem: l
        };
      },
      X(Ht, at, ce, Vt$1),
      { singleton: true }
    );
    function Nn(t2, e) {
      return Math.abs(t2 - e) < 1.01;
    }
    const le = "up", te = "down", zo = "none", Lo = {
      atBottom: false,
      notAtBottomBecause: "NOT_SHOWING_LAST_ITEM",
      state: {
        offsetBottom: 0,
        scrollHeight: 0,
        scrollTop: 0,
        viewportHeight: 0
      }
    }, Po = 0, ae = U(([{ footerHeight: t2, headerHeight: e, scrollBy: n, scrollContainerState: o, scrollTop: r2, viewportHeight: s }]) => {
      const i2 = w(false), l = w(true), c2 = $(), d = $(), f = w(4), S = w(Po), p = ct(
        x(
          un(x(A(r2), qt(1), vt$1(true)), x(A(r2), qt(1), vt$1(false), cn(100))),
          Y()
        ),
        false
      ), m = ct(
        x(un(x(n, vt$1(true)), x(n, vt$1(false), cn(200))), Y()),
        false
      );
      F(
        x(
          rt(A(r2), A(S)),
          H(([u, T]) => u <= T),
          Y()
        ),
        l
      ), F(x(l, zt(50)), d);
      const C2 = pt(
        x(
          rt(o, A(s), A(e), A(t2), A(f)),
          bt((u, [{ scrollHeight: T, scrollTop: b }, h, a, R, k]) => {
            const O = b + h - T > -k, z = {
              scrollHeight: T,
              scrollTop: b,
              viewportHeight: h
            };
            if (O) {
              let D, J;
              return b > u.state.scrollTop ? (D = "SCROLLED_DOWN", J = u.state.scrollTop - b) : (D = "SIZE_DECREASED", J = u.state.scrollTop - b || u.scrollTopDelta), {
                atBottom: true,
                atBottomBecause: D,
                scrollTopDelta: J,
                state: z
              };
            }
            let P2;
            return z.scrollHeight > u.state.scrollHeight ? P2 = "SIZE_INCREASED" : h < u.state.viewportHeight ? P2 = "VIEWPORT_HEIGHT_DECREASING" : b < u.state.scrollTop ? P2 = "SCROLLING_UPWARDS" : P2 = "NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM", {
              atBottom: false,
              notAtBottomBecause: P2,
              state: z
            };
          }, Lo),
          Y((u, T) => u && u.atBottom === T.atBottom)
        )
      ), I = ct(
        x(
          o,
          bt(
            (u, { scrollHeight: T, scrollTop: b, viewportHeight: h }) => {
              if (Nn(u.scrollHeight, T))
                return {
                  changed: false,
                  jump: 0,
                  scrollHeight: T,
                  scrollTop: b
                };
              {
                const a = T - (b + h) < 1;
                return u.scrollTop !== b && a ? {
                  changed: true,
                  jump: u.scrollTop - b,
                  scrollHeight: T,
                  scrollTop: b
                } : {
                  changed: true,
                  jump: 0,
                  scrollHeight: T,
                  scrollTop: b
                };
              }
            },
            { changed: false, jump: 0, scrollHeight: 0, scrollTop: 0 }
          ),
          V((u) => u.changed),
          H((u) => u.jump)
        ),
        0
      );
      F(
        x(
          C2,
          H((u) => u.atBottom)
        ),
        i2
      ), F(x(i2, zt(50)), c2);
      const y = w(te);
      F(
        x(
          o,
          H(({ scrollTop: u }) => u),
          Y(),
          bt(
            (u, T) => lt(m) ? { direction: u.direction, prevScrollTop: T } : { direction: T < u.prevScrollTop ? le : te, prevScrollTop: T },
            { direction: te, prevScrollTop: 0 }
          ),
          H((u) => u.direction)
        ),
        y
      ), F(x(o, zt(50), vt$1(zo)), y);
      const g = w(0);
      return F(
        x(
          p,
          V((u) => !u),
          vt$1(0)
        ),
        g
      ), F(
        x(
          r2,
          zt(100),
          G(p),
          V(([u, T]) => !!T),
          bt(([u, T], [b]) => [T, b], [0, 0]),
          H(([u, T]) => T - u)
        ),
        g
      ), {
        atBottomState: C2,
        atBottomStateChange: c2,
        atBottomThreshold: f,
        atTopStateChange: d,
        atTopThreshold: S,
        isAtBottom: i2,
        isAtTop: l,
        isScrolling: p,
        lastJumpDueToItemResize: I,
        scrollDirection: y,
        scrollVelocity: g
      };
    }, X(at)), xe = "top", Te = "bottom", mn = "none";
    function pn(t2, e, n) {
      return typeof t2 == "number" ? n === le && e === xe || n === te && e === Te ? t2 : 0 : n === le ? e === xe ? t2.main : t2.reverse : e === Te ? t2.main : t2.reverse;
    }
    function hn(t2, e) {
      var n;
      return typeof t2 == "number" ? t2 : (n = t2[e]) != null ? n : 0;
    }
    const Ue = U(
      ([{ deviation: t2, fixedHeaderHeight: e, headerHeight: n, scrollTop: o, viewportHeight: r2 }]) => {
        const s = $(), i2 = w(0), l = w(0), c2 = w(0), d = ct(
          x(
            rt(
              A(o),
              A(r2),
              A(n),
              A(s, se),
              A(c2),
              A(i2),
              A(e),
              A(t2),
              A(l)
            ),
            H(
              ([
                f,
                S,
                p,
                [m, C2],
                I,
                y,
                g,
                u,
                T
              ]) => {
                const b = f - u, h = y + g, a = Math.max(p - b, 0);
                let R = mn;
                const k = hn(T, xe), O = hn(T, Te);
                return m -= u, m += p + g, C2 += p + g, C2 -= u, m > f + h - k && (R = le), C2 < f - a + S + O && (R = te), R !== mn ? [
                  Math.max(b - p - pn(I, xe, R) - k, 0),
                  b - a - g + S + pn(I, Te, R) + O
                ] : null;
              }
            ),
            V((f) => f != null),
            Y(se)
          ),
          [0, 0]
        );
        return {
          increaseViewportBy: l,
          // input
          listBoundary: s,
          overscan: c2,
          topListHeight: i2,
          // output
          visibleRange: d
        };
      },
      X(at),
      { singleton: true }
    );
    function Vo(t2, e, n) {
      if (be(e)) {
        const o = Wn(t2, e);
        return [
          { index: wt(e.groupOffsetTree, o)[0], offset: 0, size: 0 },
          { data: n == null ? void 0 : n[0], index: o, offset: 0, size: 0 }
        ];
      }
      return [{ data: n == null ? void 0 : n[0], index: t2, offset: 0, size: 0 }];
    }
    const Be = {
      bottom: 0,
      firstItemIndex: 0,
      items: [],
      offsetBottom: 0,
      offsetTop: 0,
      top: 0,
      topItems: [],
      topListHeight: 0,
      totalCount: 0
    };
    function Ie(t2, e, n, o, r2, s) {
      const { lastIndex: i2, lastOffset: l, lastSize: c2 } = r2;
      let d = 0, f = 0;
      if (t2.length > 0) {
        d = t2[0].offset;
        const I = t2[t2.length - 1];
        f = I.offset + I.size;
      }
      const S = n - i2, p = l + S * c2 + (S - 1) * o, m = d, C2 = p - f;
      return {
        bottom: f,
        firstItemIndex: s,
        items: gn(t2, r2, s),
        offsetBottom: C2,
        offsetTop: d,
        top: m,
        topItems: gn(e, r2, s),
        topListHeight: e.reduce((I, y) => y.size + I, 0),
        totalCount: n
      };
    }
    function Dn(t2, e, n, o, r2, s) {
      let i2 = 0;
      if (n.groupIndices.length > 0)
        for (const f of n.groupIndices) {
          if (f - i2 >= t2)
            break;
          i2++;
        }
      const l = t2 + i2, c2 = $e(e, l), d = Array.from({ length: l }).map((f, S) => ({
        data: s[S + c2],
        index: S + c2,
        offset: 0,
        size: 0
      }));
      return Ie(d, [], l, r2, n, o);
    }
    function gn(t2, e, n) {
      if (t2.length === 0)
        return [];
      if (!be(e))
        return t2.map((d) => ({ ...d, index: d.index + n, originalIndex: d.index }));
      const o = t2[0].index, r2 = t2[t2.length - 1].index, s = [], i2 = ve(e.groupOffsetTree, o, r2);
      let l, c2 = 0;
      for (const d of t2) {
        (!l || l.end < d.index) && (l = i2.shift(), c2 = e.groupIndices.indexOf(l.start));
        let f;
        d.index === l.start ? f = {
          index: c2,
          type: "group"
        } : f = {
          groupIndex: c2,
          index: d.index - (c2 + 1) + n
        }, s.push({
          ...f,
          data: d.data,
          offset: d.offset,
          originalIndex: d.index,
          size: d.size
        });
      }
      return s;
    }
    const Nt = U(
      ([
        { data: t2, firstItemIndex: e, gap: n, sizes: o, totalCount: r2 },
        s,
        { listBoundary: i2, topListHeight: l, visibleRange: c2 },
        { initialTopMostItemIndex: d, scrolledToInitialItem: f },
        { topListHeight: S },
        p,
        { didMount: m },
        { recalcInProgress: C2 }
      ]) => {
        const I = w([]), y = w(0), g = $();
        F(s.topItemsIndexes, I);
        const u = ct(
          x(
            rt(
              m,
              C2,
              A(c2, se),
              A(r2),
              A(o),
              A(d),
              f,
              A(I),
              A(e),
              A(n),
              t2
            ),
            V(([a, R, , k, , , , , , , O]) => {
              const z = O && O.length !== k;
              return a && !R && !z;
            }),
            H(
              ([
                ,
                ,
                [a, R],
                k,
                O,
                z,
                P2,
                D,
                J,
                nt,
                B
              ]) => {
                const q = O, { offsetTree: st, sizeTree: dt } = q, St = lt(y);
                if (k === 0)
                  return { ...Be, totalCount: k };
                if (a === 0 && R === 0)
                  return St === 0 ? { ...Be, totalCount: k } : Dn(St, z, O, J, nt, B || []);
                if (j(dt))
                  return St > 0 ? null : Ie(
                    Vo($e(z, k), q, B),
                    [],
                    k,
                    nt,
                    q,
                    J
                  );
                const ft = [];
                if (D.length > 0) {
                  const Wt = D[0], yt = D[D.length - 1];
                  let Bt = 0;
                  for (const v of ve(dt, Wt, yt)) {
                    const N = v.value, Q = Math.max(v.start, Wt), it = Math.min(v.end, yt);
                    for (let tt = Q; tt <= it; tt++)
                      ft.push({ data: B == null ? void 0 : B[tt], index: tt, offset: Bt, size: N }), Bt += N;
                  }
                }
                if (!P2)
                  return Ie([], ft, k, nt, q, J);
                const ut = D.length > 0 ? D[D.length - 1] + 1 : 0, At = vo(st, a, R, ut);
                if (At.length === 0)
                  return null;
                const xt = k - 1, Xt = ye([], (Wt) => {
                  for (const yt of At) {
                    const Bt = yt.value;
                    let v = Bt.offset, N = yt.start;
                    const Q = Bt.size;
                    if (Bt.offset < a) {
                      N += Math.floor((a - Bt.offset + nt) / (Q + nt));
                      const tt = N - yt.start;
                      v += tt * Q + tt * nt;
                    }
                    N < ut && (v += (ut - N) * Q, N = ut);
                    const it = Math.min(yt.end, xt);
                    for (let tt = N; tt <= it && !(v >= R); tt++)
                      Wt.push({ data: B == null ? void 0 : B[tt], index: tt, offset: v, size: Q }), v += Q + nt;
                  }
                });
                return Ie(Xt, ft, k, nt, q, J);
              }
            ),
            //@ts-expect-error filter needs to be fixed
            V((a) => a !== null),
            Y()
          ),
          Be
        );
        F(
          x(
            t2,
            V(Ae),
            H((a) => a == null ? void 0 : a.length)
          ),
          r2
        ), F(
          x(
            u,
            H((a) => a.topListHeight)
          ),
          S
        ), F(S, l), F(
          x(
            u,
            H((a) => [a.top, a.bottom])
          ),
          i2
        ), F(
          x(
            u,
            H((a) => a.items)
          ),
          g
        );
        const T = pt(
          x(
            u,
            V(({ items: a }) => a.length > 0),
            G(r2, t2),
            V(([{ items: a }, R]) => a[a.length - 1].originalIndex === R - 1),
            H(([, a, R]) => [a - 1, R]),
            Y(se),
            H(([a]) => a)
          )
        ), b = pt(
          x(
            u,
            zt(200),
            V(({ items: a, topItems: R }) => a.length > 0 && a[0].originalIndex === R.length),
            H(({ items: a }) => a[0].index),
            Y()
          )
        ), h = pt(
          x(
            u,
            V(({ items: a }) => a.length > 0),
            H(({ items: a }) => {
              let R = 0, k = a.length - 1;
              for (; a[R].type === "group" && R < k; )
                R++;
              for (; a[k].type === "group" && k > R; )
                k--;
              return {
                endIndex: a[k].index,
                startIndex: a[R].index
              };
            }),
            Y(Vn)
          )
        );
        return { endReached: T, initialItemCount: y, itemsRendered: g, listState: u, rangeChanged: h, startReached: b, topItemsIndexes: I, ...p };
      },
      X(
        Ht,
        _n,
        Ue,
        ue,
        ce,
        ae,
        Vt$1,
        Ge
      ),
      { singleton: true }
    ), $n = U(
      ([{ fixedFooterHeight: t2, fixedHeaderHeight: e, footerHeight: n, headerHeight: o }, { listState: r2 }]) => {
        const s = $(), i2 = ct(
          x(
            rt(n, t2, o, e, r2),
            H(([l, c2, d, f, S]) => l + c2 + d + f + S.offsetBottom + S.bottom)
          ),
          0
        );
        return F(A(i2), s), { totalListHeight: i2, totalListHeightChanged: s };
      },
      X(at, Nt),
      { singleton: true }
    ), Ao = U(
      ([{ viewportHeight: t2 }, { totalListHeight: e }]) => {
        const n = w(false), o = ct(
          x(
            rt(n, t2, e),
            V(([r2]) => r2),
            H(([, r2, s]) => Math.max(0, r2 - s)),
            zt(0),
            Y()
          ),
          0
        );
        return { alignToBottom: n, paddingTopAddition: o };
      },
      X(at, $n),
      { singleton: true }
    );
    function In(t2) {
      return t2 ? t2 === "smooth" ? "smooth" : "auto" : false;
    }
    const Wo = (t2, e) => typeof t2 == "function" ? In(t2(e)) : e && In(t2), Mo = U(
      ([
        { listRefresh: t2, totalCount: e },
        { atBottomState: n, isAtBottom: o },
        { scrollToIndex: r2 },
        { scrolledToInitialItem: s },
        { didMount: i2, propsReady: l },
        { log: c2 },
        { scrollingInProgress: d }
      ]) => {
        const f = w(false), S = $();
        let p = null;
        function m(I) {
          M(r2, {
            align: "end",
            behavior: I,
            index: "LAST"
          });
        }
        K(
          x(
            rt(x(A(e), qt(1)), i2),
            G(A(f), o, s, d),
            H(([[I, y], g, u, T, b]) => {
              let h = y && T, a = "auto";
              return h && (a = Wo(g, u || b), h = h && !!a), { followOutputBehavior: a, shouldFollow: h, totalCount: I };
            }),
            V(({ shouldFollow: I }) => I)
          ),
          ({ followOutputBehavior: I, totalCount: y }) => {
            p && (p(), p = null), p = Rt(t2, () => {
              lt(c2)("following output to ", { totalCount: y }, ht.DEBUG), m(I), p = null;
            });
          }
        );
        function C2(I) {
          const y = Rt(n, (g) => {
            I && !g.atBottom && g.notAtBottomBecause === "SIZE_INCREASED" && !p && (lt(c2)("scrolling to bottom due to increased size", {}, ht.DEBUG), m("auto"));
          });
          setTimeout(y, 100);
        }
        return K(
          x(
            rt(A(f), e, l),
            V(([I, , y]) => I && y),
            bt(
              ({ value: I }, [, y]) => ({ refreshed: I === y, value: y }),
              { refreshed: false, value: 0 }
            ),
            V(({ refreshed: I }) => I),
            G(f, e)
          ),
          ([, I]) => {
            lt(s) && C2(I !== false);
          }
        ), K(S, () => {
          C2(lt(f) !== false);
        }), K(rt(A(f), n), ([I, y]) => {
          I && !y.atBottom && y.notAtBottomBecause === "VIEWPORT_HEIGHT_DECREASING" && m("auto");
        }), { autoscrollToBottom: S, followOutput: f };
      },
      X(Ht, ae, ce, ue, Vt$1, Pt, at)
    ), _o = U(
      ([{ data: t2, firstItemIndex: e, gap: n, sizes: o }, { initialTopMostItemIndex: r2 }, { initialItemCount: s, listState: i2 }, { didMount: l }]) => (F(
        x(
          l,
          G(s),
          V(([, c2]) => c2 !== 0),
          G(r2, o, e, n, t2),
          H(([[, c2], d, f, S, p, m = []]) => Dn(c2, d, f, S, p, m))
        ),
        i2
      ), {}),
      X(Ht, ue, Nt, Vt$1),
      { singleton: true }
    ), Go = U(
      ([{ didMount: t2 }, { scrollTo: e }, { listState: n }]) => {
        const o = w(0);
        return K(
          x(
            t2,
            G(o),
            V(([, r2]) => r2 !== 0),
            H(([, r2]) => ({ top: r2 }))
          ),
          (r2) => {
            Rt(
              x(
                n,
                qt(1),
                V((s) => s.items.length > 1)
              ),
              () => {
                requestAnimationFrame(() => {
                  M(e, r2);
                });
              }
            );
          }
        ), {
          initialScrollTop: o
        };
      },
      X(Vt$1, at, Nt),
      { singleton: true }
    ), No = ({
      itemBottom: t2,
      itemTop: e,
      locationParams: { align: n, behavior: o, ...r2 },
      viewportBottom: s,
      viewportTop: i2
    }) => e < i2 ? { ...r2, align: n != null ? n : "start", behavior: o } : t2 > s ? { ...r2, align: n != null ? n : "end", behavior: o } : null, Do = U(
      ([
        { gap: t2, sizes: e, totalCount: n },
        { fixedFooterHeight: o, fixedHeaderHeight: r2, headerHeight: s, scrollingInProgress: i2, scrollTop: l, viewportHeight: c2 },
        { scrollToIndex: d }
      ]) => {
        const f = $();
        return F(
          x(
            f,
            G(e, c2, n, s, r2, o, l),
            G(t2),
            H(([[S, p, m, C2, I, y, g, u], T]) => {
              const { align: b, behavior: h, calculateViewLocation: a = No, done: R, ...k } = S, O = Mn(S, p, C2 - 1), z = ie(O, p.offsetTree, T) + I + y, P2 = z + wt(p.sizeTree, O)[1], D = u + y, J = u + m - g, nt = a({
                itemBottom: P2,
                itemTop: z,
                locationParams: { align: b, behavior: h, ...k },
                viewportBottom: J,
                viewportTop: D
              });
              return nt ? R && Rt(
                x(
                  i2,
                  V((B) => !B),
                  // skips the initial publish of false, and the cleanup call.
                  // but if scrollingInProgress is true, we skip the initial publish.
                  qt(lt(i2) ? 1 : 2)
                ),
                R
              ) : R && R(), nt;
            }),
            V((S) => S !== null)
          ),
          d
        ), {
          scrollIntoView: f
        };
      },
      X(Ht, at, ce, Nt, Pt),
      { singleton: true }
    ), Un = U(
      ([{ scrollVelocity: t2 }]) => {
        const e = w(false), n = $(), o = w(false);
        return F(
          x(
            t2,
            G(o, e, n),
            V(([r2, s]) => !!s),
            H(([r2, s, i2, l]) => {
              const { enter: c2, exit: d } = s;
              if (i2) {
                if (d(r2, l))
                  return false;
              } else if (c2(r2, l))
                return true;
              return i2;
            }),
            Y()
          ),
          e
        ), K(
          x(rt(e, t2, n), G(o)),
          ([[r2, s, i2], l]) => {
            r2 && l && l.change && l.change(s, i2);
          }
        ), { isSeeking: e, scrollSeekConfiguration: o, scrollSeekRangeChanged: n, scrollVelocity: t2 };
      },
      X(ae),
      { singleton: true }
    ), Ke = U(([{ scrollContainerState: t2, scrollTo: e }]) => {
      const n = $(), o = $(), r2 = $(), s = w(false), i2 = w(void 0);
      return F(
        x(
          rt(n, o),
          H(([{ scrollHeight: l, scrollTop: c2, viewportHeight: d }, { offsetTop: f }]) => ({
            scrollHeight: l,
            scrollTop: Math.max(0, c2 - f),
            viewportHeight: d
          }))
        ),
        t2
      ), F(
        x(
          e,
          G(o),
          H(([l, { offsetTop: c2 }]) => ({
            ...l,
            top: l.top + c2
          }))
        ),
        r2
      ), {
        customScrollParent: i2,
        // config
        useWindowScroll: s,
        // input
        windowScrollContainerState: n,
        // signals
        windowScrollTo: r2,
        windowViewportRect: o
      };
    }, X(at)), $o = U(
      ([
        { sizeRanges: t2, sizes: e },
        { headerHeight: n, scrollTop: o },
        { initialTopMostItemIndex: r2 },
        { didMount: s },
        { useWindowScroll: i2, windowScrollContainerState: l, windowViewportRect: c2 }
      ]) => {
        const d = $(), f = w(void 0), S = w(null), p = w(null);
        return F(l, S), F(c2, p), K(
          x(
            d,
            G(e, o, i2, S, p, n)
          ),
          ([m, C2, I, y, g, u, T]) => {
            const b = Ro(C2.sizeTree);
            y && g !== null && u !== null && (I = g.scrollTop - u.offsetTop), I -= T, m({ ranges: b, scrollTop: I });
          }
        ), F(x(f, V(Ae), H(Uo)), r2), F(
          x(
            s,
            G(f),
            V(([, m]) => m !== void 0),
            Y(),
            H(([, m]) => m.ranges)
          ),
          t2
        ), {
          getState: d,
          restoreStateFrom: f
        };
      },
      X(Ht, at, ue, Vt$1, Ke)
    );
    function Uo(t2) {
      return { align: "start", index: 0, offset: t2.scrollTop };
    }
    const Ko = U(([{ topItemsIndexes: t2 }]) => {
      const e = w(0);
      return F(
        x(
          e,
          V((n) => n >= 0),
          H((n) => Array.from({ length: n }).map((o, r2) => r2))
        ),
        t2
      ), { topItemCount: e };
    }, X(Nt));
    function Kn(t2) {
      let e = false, n;
      return () => (e || (e = true, n = t2()), n);
    }
    const jo = Kn(() => /iP(ad|od|hone)/i.test(navigator.userAgent) && /WebKit/i.test(navigator.userAgent)), qo = U(
      ([
        { deviation: t2, scrollBy: e, scrollingInProgress: n, scrollTop: o },
        { isAtBottom: r2, isScrolling: s, lastJumpDueToItemResize: i2, scrollDirection: l },
        { listState: c2 },
        { beforeUnshiftWith: d, gap: f, shiftWithOffset: S, sizes: p },
        { log: m },
        { recalcInProgress: C2 }
      ]) => {
        const I = pt(
          x(
            c2,
            G(i2),
            bt(
              ([, g, u, T], [{ bottom: b, items: h, offsetBottom: a, totalCount: R }, k]) => {
                const O = b + a;
                let z = 0;
                return u === R && g.length > 0 && h.length > 0 && (h[0].originalIndex === 0 && g[0].originalIndex === 0 || (z = O - T, z !== 0 && (z += k))), [z, h, R, O];
              },
              [0, [], 0, 0]
            ),
            V(([g]) => g !== 0),
            G(o, l, n, r2, m, C2),
            V(([, g, u, T, , , b]) => !b && !T && g !== 0 && u === le),
            H(([[g], , , , , u]) => (u("Upward scrolling compensation", { amount: g }, ht.DEBUG), g))
          )
        );
        function y(g) {
          g > 0 ? (M(e, { behavior: "auto", top: -g }), M(t2, 0)) : (M(t2, 0), M(e, { behavior: "auto", top: -g }));
        }
        return K(x(I, G(t2, s)), ([g, u, T]) => {
          T && jo() ? M(t2, u - g) : y(-g);
        }), K(
          x(
            rt(ct(s, false), t2, C2),
            V(([g, u, T]) => !g && !T && u !== 0),
            H(([g, u]) => u),
            zt(1)
          ),
          y
        ), F(
          x(
            S,
            H((g) => ({ top: -g }))
          ),
          e
        ), K(
          x(
            d,
            G(p, f),
            H(([g, { groupIndices: u, lastSize: T, sizeTree: b }, h]) => {
              function a(R) {
                return R * (T + h);
              }
              if (u.length === 0)
                return a(g);
              {
                let R = 0;
                const k = re(b, 0);
                let O = 0, z = 0;
                for (; O < g; ) {
                  O++, R += k;
                  let P2 = u.length === z + 1 ? 1 / 0 : u[z + 1] - u[z] - 1;
                  O + P2 > g && (R -= k, P2 = g - O + 1), O += P2, R += a(P2), z++;
                }
                return R;
              }
            })
          ),
          (g) => {
            M(t2, g), requestAnimationFrame(() => {
              M(e, { top: g }), requestAnimationFrame(() => {
                M(t2, 0), M(C2, false);
              });
            });
          }
        ), { deviation: t2 };
      },
      X(at, ae, Nt, Ht, Pt, Ge)
    ), Yo = U(
      ([
        t2,
        e,
        n,
        o,
        r2,
        s,
        i2,
        l,
        c2,
        d
      ]) => ({
        ...t2,
        ...e,
        ...n,
        ...o,
        ...r2,
        ...s,
        ...i2,
        ...l,
        ...c2,
        ...d
      }),
      X(
        Ue,
        _o,
        Vt$1,
        Un,
        $n,
        Go,
        Ao,
        Ke,
        Do,
        Pt
      )
    ), jn = U(
      ([
        {
          data: t2,
          defaultItemSize: e,
          firstItemIndex: n,
          fixedItemSize: o,
          gap: r2,
          groupIndices: s,
          itemSize: i2,
          sizeRanges: l,
          sizes: c2,
          statefulTotalCount: d,
          totalCount: f,
          trackItemSizes: S
        },
        { initialItemFinalLocationReached: p, initialTopMostItemIndex: m, scrolledToInitialItem: C2 },
        I,
        y,
        g,
        { listState: u, topItemsIndexes: T, ...b },
        { scrollToIndex: h },
        a,
        { topItemCount: R },
        { groupCounts: k },
        O
      ]) => (F(b.rangeChanged, O.scrollSeekRangeChanged), F(
        x(
          O.windowViewportRect,
          H((z) => z.visibleHeight)
        ),
        I.viewportHeight
      ), {
        data: t2,
        defaultItemHeight: e,
        firstItemIndex: n,
        fixedItemHeight: o,
        gap: r2,
        groupCounts: k,
        initialItemFinalLocationReached: p,
        initialTopMostItemIndex: m,
        scrolledToInitialItem: C2,
        sizeRanges: l,
        topItemCount: R,
        topItemsIndexes: T,
        // input
        totalCount: f,
        ...g,
        groupIndices: s,
        itemSize: i2,
        listState: u,
        scrollToIndex: h,
        // output
        statefulTotalCount: d,
        trackItemSizes: S,
        // exported from stateFlagsSystem
        ...b,
        // the bag of IO from featureGroup1System
        ...O,
        ...I,
        sizes: c2,
        ...y
      }),
      X(
        Ht,
        ue,
        at,
        $o,
        Mo,
        Nt,
        ce,
        qo,
        Ko,
        _n,
        Yo
      )
    );
    function Zo(t2, e) {
      const n = {}, o = {};
      let r2 = 0;
      const s = t2.length;
      for (; r2 < s; )
        o[t2[r2]] = 1, r2 += 1;
      for (const i2 in e)
        Object.hasOwn(o, i2) || (n[i2] = e[i2]);
      return n;
    }
    const pe = typeof document < "u" ? React$2.useLayoutEffect : React$2.useEffect;
    function je(t2, e, n) {
      const o = Object.keys(e.required || {}), r2 = Object.keys(e.optional || {}), s = Object.keys(e.methods || {}), i2 = Object.keys(e.events || {}), l = React$2.createContext({});
      function c2(g, u) {
        g.propsReady && M(g.propsReady, false);
        for (const T of o) {
          const b = g[e.required[T]];
          M(b, u[T]);
        }
        for (const T of r2)
          if (T in u) {
            const b = g[e.optional[T]];
            M(b, u[T]);
          }
        g.propsReady && M(g.propsReady, true);
      }
      function d(g) {
        return s.reduce((u, T) => (u[T] = (b) => {
          const h = g[e.methods[T]];
          M(h, b);
        }, u), {});
      }
      function f(g) {
        return i2.reduce((u, T) => (u[T] = fo(g[e.events[T]]), u), {});
      }
      const S = React$2.forwardRef((g, u) => {
        const { children: T, ...b } = g, [h] = React$2.useState(() => ye(po(t2), (k) => {
          c2(k, b);
        })), [a] = React$2.useState(ln(f, h));
        pe(() => {
          for (const k of i2)
            k in b && K(a[k], b[k]);
          return () => {
            Object.values(a).map(We);
          };
        }, [b, a, h]), pe(() => {
          c2(h, b);
        }), React$2.useImperativeHandle(u, sn(d(h)));
        const R = n;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(l.Provider, { value: h, children: n ? /* @__PURE__ */ jsxRuntimeExports.jsx(R, { ...Zo([...o, ...r2, ...i2], b), children: T }) : T });
      }), p = (g) => React$2.useCallback(Hn(M, React$2.useContext(l)[g]), [g]), m = (g) => {
        const T = React$2.useContext(l)[g], b = React$2.useCallback(
          (h) => K(T, h),
          [T]
        );
        return React$2.useSyncExternalStore(
          b,
          () => lt(T),
          () => lt(T)
        );
      }, C2 = (g) => {
        const T = React$2.useContext(l)[g], [b, h] = React$2.useState(ln(lt, T));
        return pe(
          () => K(T, (a) => {
            a !== b && h(sn(a));
          }),
          [T, b]
        ), b;
      }, I = React$2.version.startsWith("18") ? m : C2;
      return {
        Component: S,
        useEmitter: (g, u) => {
          const b = React$2.useContext(l)[g];
          pe(() => K(b, u), [u, b]);
        },
        useEmitterValue: I,
        usePublisher: p
      };
    }
    const Re = React$2.createContext(void 0), qn = React$2.createContext(void 0), Yn = typeof document < "u" ? React$2.useLayoutEffect : React$2.useEffect;
    function Zn(t2, e, n, o = Gt, r2, s) {
      const i2 = React$2.useRef(null), l = React$2.useRef(null), c2 = React$2.useRef(null), d = React$2.useCallback(
        (p) => {
          const m = p.target, C2 = m === window || m === document, I = s ? C2 ? window.pageXOffset || document.documentElement.scrollLeft : m.scrollLeft : C2 ? window.pageYOffset || document.documentElement.scrollTop : m.scrollTop, y = s ? C2 ? document.documentElement.scrollWidth : m.scrollWidth : C2 ? document.documentElement.scrollHeight : m.scrollHeight, g = s ? C2 ? window.innerWidth : m.offsetWidth : C2 ? window.innerHeight : m.offsetHeight, u = () => {
            t2({
              scrollHeight: y,
              scrollTop: Math.max(I, 0),
              viewportHeight: g
            });
          };
          p.suppressFlushSync ? u() : io.flushSync(u), l.current !== null && (I === l.current || I <= 0 || I === y - g) && (l.current = null, e(true), c2.current && (clearTimeout(c2.current), c2.current = null));
        },
        [t2, e]
      );
      React$2.useEffect(() => {
        const p = r2 || i2.current;
        return o(r2 || i2.current), d({ suppressFlushSync: true, target: p }), p.addEventListener("scroll", d, { passive: true }), () => {
          o(null), p.removeEventListener("scroll", d);
        };
      }, [i2, d, n, o, r2]);
      function f(p) {
        const m = i2.current;
        if (!m || (s ? "offsetWidth" in m && m.offsetWidth === 0 : "offsetHeight" in m && m.offsetHeight === 0))
          return;
        const C2 = p.behavior === "smooth";
        let I, y, g;
        m === window ? (y = Math.max(
          Ct(document.documentElement, s ? "width" : "height"),
          s ? document.documentElement.scrollWidth : document.documentElement.scrollHeight
        ), I = s ? window.innerWidth : window.innerHeight, g = s ? document.documentElement.scrollLeft : document.documentElement.scrollTop) : (y = m[s ? "scrollWidth" : "scrollHeight"], I = Ct(m, s ? "width" : "height"), g = m[s ? "scrollLeft" : "scrollTop"]);
        const u = y - I;
        if (p.top = Math.ceil(Math.max(Math.min(u, p.top), 0)), Nn(I, y) || p.top === g) {
          t2({ scrollHeight: y, scrollTop: g, viewportHeight: I }), C2 && e(true);
          return;
        }
        C2 ? (l.current = p.top, c2.current && clearTimeout(c2.current), c2.current = setTimeout(() => {
          c2.current = null, l.current = null, e(true);
        }, 1e3)) : l.current = null, s && (p = { behavior: p.behavior, left: p.top }), m.scrollTo(p);
      }
      function S(p) {
        s && (p = { behavior: p.behavior, left: p.top }), i2.current.scrollBy(p);
      }
      return { scrollByCallback: S, scrollerRef: i2, scrollToCallback: f };
    }
    const ke = "-webkit-sticky", Sn = "sticky", Xn = Kn(() => {
      if (typeof document > "u")
        return Sn;
      const t2 = document.createElement("div");
      return t2.style.position = ke, t2.style.position === ke ? ke : Sn;
    });
    function qe(t2) {
      return t2;
    }
    const Xo = /* @__PURE__ */ U(() => {
      const t2 = w((c2) => `Item ${c2}`), e = w(null), n = w((c2) => `Group ${c2}`), o = w({}), r2 = w(qe), s = w("div"), i2 = w(Gt), l = (c2, d = null) => ct(
        x(
          o,
          H((f) => f[c2]),
          Y()
        ),
        d
      );
      return {
        components: o,
        computeItemKey: r2,
        context: e,
        EmptyPlaceholder: l("EmptyPlaceholder"),
        FooterComponent: l("Footer"),
        GroupComponent: l("Group", "div"),
        groupContent: n,
        HeaderComponent: l("Header"),
        HeaderFooterTag: s,
        ItemComponent: l("Item", "div"),
        itemContent: t2,
        ListComponent: l("List", "div"),
        ScrollerComponent: l("Scroller", "div"),
        scrollerRef: i2,
        ScrollSeekPlaceholder: l("ScrollSeekPlaceholder"),
        TopItemListComponent: l("TopItemList")
      };
    }), Jo = /* @__PURE__ */ U(
      ([t2, e]) => ({ ...t2, ...e }),
      X(jn, Xo)
    ), Qo = ({ height: t2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: t2 } }), tr = { overflowAnchor: "none", position: Xn(), zIndex: 1 }, Jn = { overflowAnchor: "none" }, er = { ...Jn, display: "inline-block", height: "100%" }, xn = /* @__PURE__ */ React$2.memo(function({ showTopList: e = false }) {
      const n = W("listState"), o = gt("sizeRanges"), r2 = W("useWindowScroll"), s = W("customScrollParent"), i2 = gt("windowScrollContainerState"), l = gt("scrollContainerState"), c2 = s || r2 ? i2 : l, d = W("itemContent"), f = W("context"), S = W("groupContent"), p = W("trackItemSizes"), m = W("itemSize"), C2 = W("log"), I = gt("gap"), y = W("horizontalDirection"), { callbackRef: g } = kn(
        o,
        m,
        p,
        e ? Gt : c2,
        C2,
        I,
        s,
        y,
        W("skipAnimationFrameInResizeObserver")
      ), [u, T] = React$2.useState(0);
      Xe("deviation", (B) => {
        u !== B && T(B);
      });
      const b = W("EmptyPlaceholder"), h = W("ScrollSeekPlaceholder") || Qo, a = W("ListComponent"), R = W("ItemComponent"), k = W("GroupComponent"), O = W("computeItemKey"), z = W("isSeeking"), P2 = W("groupIndices").length > 0, D = W("alignToBottom"), J = W("initialItemFinalLocationReached"), nt = e ? {} : {
        boxSizing: "border-box",
        ...y ? {
          display: "inline-block",
          height: "100%",
          marginLeft: u !== 0 ? u : D ? "auto" : 0,
          paddingLeft: n.offsetTop,
          paddingRight: n.offsetBottom,
          whiteSpace: "nowrap"
        } : {
          marginTop: u !== 0 ? u : D ? "auto" : 0,
          paddingBottom: n.offsetBottom,
          paddingTop: n.offsetTop
        },
        ...J ? {} : { visibility: "hidden" }
      };
      return !e && n.totalCount === 0 && b ? /* @__PURE__ */ jsxRuntimeExports.jsx(b, { ...Z(b, f) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
        a,
        {
          ...Z(a, f),
          "data-testid": e ? "virtuoso-top-item-list" : "virtuoso-item-list",
          ref: g,
          style: nt,
          children: (e ? n.topItems : n.items).map((B) => {
            const q = B.originalIndex, st = O(q + n.firstItemIndex, B.data, f);
            return z ? /* @__PURE__ */ reactExports.createElement(
              h,
              {
                ...Z(h, f),
                height: B.size,
                index: B.index,
                key: st,
                type: B.type || "item",
                ...B.type === "group" ? {} : { groupIndex: B.groupIndex }
              }
            ) : B.type === "group" ? /* @__PURE__ */ reactExports.createElement(
              k,
              {
                ...Z(k, f),
                "data-index": q,
                "data-item-index": B.index,
                "data-known-size": B.size,
                key: st,
                style: tr
              },
              S(B.index, f)
            ) : /* @__PURE__ */ reactExports.createElement(
              R,
              {
                ...Z(R, f),
                ...Qn(R, B.data),
                "data-index": q,
                "data-item-group-index": B.groupIndex,
                "data-item-index": B.index,
                "data-known-size": B.size,
                key: st,
                style: y ? er : Jn
              },
              P2 ? d(B.index, B.groupIndex, B.data, f) : d(B.index, B.data, f)
            );
          })
        }
      );
    }), nr = {
      height: "100%",
      outline: "none",
      overflowY: "auto",
      position: "relative",
      WebkitOverflowScrolling: "touch"
    }, or = {
      outline: "none",
      overflowX: "auto",
      position: "relative"
    }, Zt = (t2) => ({
      height: "100%",
      position: "absolute",
      top: 0,
      width: "100%",
      ...t2 ? { display: "flex", flexDirection: "column" } : {}
    }), rr = {
      position: Xn(),
      top: 0,
      width: "100%",
      zIndex: 1
    };
    function Z(t2, e) {
      if (typeof t2 != "string")
        return { context: e };
    }
    function Qn(t2, e) {
      return { item: typeof t2 == "string" ? void 0 : e };
    }
    const sr = /* @__PURE__ */ React$2.memo(function() {
      const e = W("HeaderComponent"), n = gt("headerHeight"), o = W("HeaderFooterTag"), r2 = Et(
        React$2.useMemo(
          () => (i2) => {
            n(Ct(i2, "height"));
          },
          [n]
        ),
        true,
        W("skipAnimationFrameInResizeObserver")
      ), s = W("context");
      return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z(e, s) }) }) : null;
    }), ir = /* @__PURE__ */ React$2.memo(function() {
      const e = W("FooterComponent"), n = gt("footerHeight"), o = W("HeaderFooterTag"), r2 = Et(
        React$2.useMemo(
          () => (i2) => {
            n(Ct(i2, "height"));
          },
          [n]
        ),
        true,
        W("skipAnimationFrameInResizeObserver")
      ), s = W("context");
      return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z(e, s) }) }) : null;
    });
    function Ye({ useEmitter: t2, useEmitterValue: e, usePublisher: n }) {
      return React$2.memo(function({ children: s, style: i2, ...l }) {
        const c2 = n("scrollContainerState"), d = e("ScrollerComponent"), f = n("smoothScrollTargetReached"), S = e("scrollerRef"), p = e("context"), m = e("horizontalDirection") || false, { scrollByCallback: C2, scrollerRef: I, scrollToCallback: y } = Zn(
          c2,
          f,
          d,
          S,
          void 0,
          m
        );
        return t2("scrollTo", y), t2("scrollBy", C2), /* @__PURE__ */ jsxRuntimeExports.jsx(
          d,
          {
            "data-testid": "virtuoso-scroller",
            "data-virtuoso-scroller": true,
            ref: I,
            style: { ...m ? or : nr, ...i2 },
            tabIndex: 0,
            ...l,
            ...Z(d, p),
            children: s
          }
        );
      });
    }
    function Ze({ useEmitter: t2, useEmitterValue: e, usePublisher: n }) {
      return React$2.memo(function({ children: s, style: i2, ...l }) {
        const c2 = n("windowScrollContainerState"), d = e("ScrollerComponent"), f = n("smoothScrollTargetReached"), S = e("totalListHeight"), p = e("deviation"), m = e("customScrollParent"), C2 = e("context"), { scrollByCallback: I, scrollerRef: y, scrollToCallback: g } = Zn(
          c2,
          f,
          d,
          Gt,
          m
        );
        return Yn(() => (y.current = m || window, () => {
          y.current = null;
        }), [y, m]), t2("windowScrollTo", g), t2("scrollBy", I), /* @__PURE__ */ jsxRuntimeExports.jsx(
          d,
          {
            "data-virtuoso-scroller": true,
            style: { position: "relative", ...i2, ...S !== 0 ? { height: S + p } : {} },
            ...l,
            ...Z(d, C2),
            children: s
          }
        );
      });
    }
    const lr = ({ children: t2 }) => {
      const e = React$2.useContext(Re), n = gt("viewportHeight"), o = gt("fixedItemHeight"), r2 = W("alignToBottom"), s = W("horizontalDirection"), i2 = React$2.useMemo(
        () => ne(n, (c2) => Ct(c2, s ? "width" : "height")),
        [n, s]
      ), l = Et(i2, true, W("skipAnimationFrameInResizeObserver"));
      return React$2.useEffect(() => {
        e && (n(e.viewportHeight), o(e.itemHeight));
      }, [e, n, o]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-viewport-type": "element", ref: l, style: Zt(r2), children: t2 });
    }, cr = ({ children: t2 }) => {
      const e = React$2.useContext(Re), n = gt("windowViewportRect"), o = gt("fixedItemHeight"), r2 = W("customScrollParent"), s = _e(
        n,
        r2,
        W("skipAnimationFrameInResizeObserver")
      ), i2 = W("alignToBottom");
      return React$2.useEffect(() => {
        e && (o(e.itemHeight), n({ offsetTop: 0, visibleHeight: e.viewportHeight, visibleWidth: 100 }));
      }, [e, n, o]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-viewport-type": "window", ref: s, style: Zt(i2), children: t2 });
    }, ur = ({ children: t2 }) => {
      const e = W("TopItemListComponent") || "div", n = W("headerHeight"), o = { ...rr, marginTop: `${n}px` }, r2 = W("context");
      return /* @__PURE__ */ jsxRuntimeExports.jsx(e, { style: o, ...Z(e, r2), children: t2 });
    }, ar = /* @__PURE__ */ React$2.memo(function(e) {
      const n = W("useWindowScroll"), o = W("topItemsIndexes").length > 0, r2 = W("customScrollParent"), s = W("context"), i2 = r2 || n ? fr : dr, l = r2 || n ? cr : lr;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(i2, { ...e, ...Z(i2, s), children: [
        o && /* @__PURE__ */ jsxRuntimeExports.jsx(ur, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(xn, { showTopList: true }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(l, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(sr, {}),
          /* @__PURE__ */ jsxRuntimeExports.jsx(xn, {}),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ir, {})
        ] })
      ] });
    }), {
      Component: to,
      useEmitter: Xe,
      useEmitterValue: W,
      usePublisher: gt
    } = /* @__PURE__ */ je(
      Jo,
      {
        events: {
          atBottomStateChange: "atBottomStateChange",
          atTopStateChange: "atTopStateChange",
          endReached: "endReached",
          groupIndices: "groupIndices",
          isScrolling: "isScrolling",
          itemsRendered: "itemsRendered",
          rangeChanged: "rangeChanged",
          startReached: "startReached",
          totalListHeightChanged: "totalListHeightChanged"
        },
        methods: {
          autoscrollToBottom: "autoscrollToBottom",
          getState: "getState",
          scrollBy: "scrollBy",
          scrollIntoView: "scrollIntoView",
          scrollTo: "scrollTo",
          scrollToIndex: "scrollToIndex"
        },
        optional: {
          alignToBottom: "alignToBottom",
          atBottomThreshold: "atBottomThreshold",
          atTopThreshold: "atTopThreshold",
          components: "components",
          computeItemKey: "computeItemKey",
          context: "context",
          customScrollParent: "customScrollParent",
          data: "data",
          defaultItemHeight: "defaultItemHeight",
          firstItemIndex: "firstItemIndex",
          fixedItemHeight: "fixedItemHeight",
          followOutput: "followOutput",
          groupContent: "groupContent",
          groupCounts: "groupCounts",
          headerFooterTag: "HeaderFooterTag",
          horizontalDirection: "horizontalDirection",
          increaseViewportBy: "increaseViewportBy",
          initialItemCount: "initialItemCount",
          initialScrollTop: "initialScrollTop",
          initialTopMostItemIndex: "initialTopMostItemIndex",
          itemContent: "itemContent",
          itemSize: "itemSize",
          logLevel: "logLevel",
          overscan: "overscan",
          restoreStateFrom: "restoreStateFrom",
          scrollerRef: "scrollerRef",
          scrollSeekConfiguration: "scrollSeekConfiguration",
          skipAnimationFrameInResizeObserver: "skipAnimationFrameInResizeObserver",
          topItemCount: "topItemCount",
          totalCount: "totalCount",
          useWindowScroll: "useWindowScroll"
        },
        required: {}
      },
      ar
    ), dr = /* @__PURE__ */ Ye({ useEmitter: Xe, useEmitterValue: W, usePublisher: gt }), fr = /* @__PURE__ */ Ze({ useEmitter: Xe, useEmitterValue: W, usePublisher: gt }), $r = to, mr = /* @__PURE__ */ U(() => {
      const t2 = w((c2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { children: [
        "Item $",
        c2
      ] })), e = w(null), n = w(null), o = w(null), r2 = w({}), s = w(qe), i2 = w(Gt), l = (c2, d = null) => ct(
        x(
          r2,
          H((f) => f[c2]),
          Y()
        ),
        d
      );
      return {
        components: r2,
        computeItemKey: s,
        context: e,
        EmptyPlaceholder: l("EmptyPlaceholder"),
        FillerRow: l("FillerRow"),
        fixedFooterContent: o,
        fixedHeaderContent: n,
        itemContent: t2,
        ScrollerComponent: l("Scroller", "div"),
        scrollerRef: i2,
        ScrollSeekPlaceholder: l("ScrollSeekPlaceholder"),
        TableBodyComponent: l("TableBody", "tbody"),
        TableComponent: l("Table", "table"),
        TableFooterComponent: l("TableFoot", "tfoot"),
        TableHeadComponent: l("TableHead", "thead"),
        TableRowComponent: l("TableRow", "tr")
      };
    });
    /* @__PURE__ */ U(
      ([t2, e]) => ({ ...t2, ...e }),
      X(jn, mr)
    );
    const wn = {
      bottom: 0,
      itemHeight: 0,
      items: [],
      itemWidth: 0,
      offsetBottom: 0,
      offsetTop: 0,
      top: 0
    }, br = {
      bottom: 0,
      itemHeight: 0,
      items: [{ index: 0 }],
      itemWidth: 0,
      offsetBottom: 0,
      offsetTop: 0,
      top: 0
    }, { ceil: Cn, floor: we, max: ee, min: Oe, round: yn } = Math;
    function vn(t2, e, n) {
      return Array.from({ length: e - t2 + 1 }).map((o, r2) => ({ data: n === null ? null : n[r2 + t2], index: r2 + t2 }));
    }
    function Rr(t2) {
      return {
        ...br,
        items: t2
      };
    }
    function he(t2, e) {
      return t2 && t2.width === e.width && t2.height === e.height;
    }
    function Er(t2, e) {
      return t2 && t2.column === e.column && t2.row === e.row;
    }
    const Hr = /* @__PURE__ */ U(
      ([
        { increaseViewportBy: t2, listBoundary: e, overscan: n, visibleRange: o },
        { footerHeight: r2, headerHeight: s, scrollBy: i2, scrollContainerState: l, scrollTo: c2, scrollTop: d, smoothScrollTargetReached: f, viewportHeight: S },
        p,
        m,
        { didMount: C2, propsReady: I },
        { customScrollParent: y, useWindowScroll: g, windowScrollContainerState: u, windowScrollTo: T, windowViewportRect: b },
        h
      ]) => {
        const a = w(0), R = w(0), k = w(wn), O = w({ height: 0, width: 0 }), z = w({ height: 0, width: 0 }), P2 = $(), D = $(), J = w(0), nt = w(null), B = w({ column: 0, row: 0 }), q = $(), st = $(), dt = w(false), St = w(0), ft = w(true), ut = w(false), At = w(false);
        K(
          x(
            C2,
            G(St),
            V(([v, N]) => !!N)
          ),
          () => {
            M(ft, false);
          }
        ), K(
          x(
            rt(C2, ft, z, O, St, ut),
            V(([v, N, Q, it, , tt]) => v && !N && Q.height !== 0 && it.height !== 0 && !tt)
          ),
          ([, , , , v]) => {
            M(ut, true), De(1, () => {
              M(P2, v);
            }), Rt(x(d), () => {
              M(e, [0, 0]), M(ft, true);
            });
          }
        ), F(
          x(
            st,
            V((v) => v != null && v.scrollTop > 0),
            vt$1(0)
          ),
          R
        ), K(
          x(
            C2,
            G(st),
            V(([, v]) => v != null)
          ),
          ([, v]) => {
            v && (M(O, v.viewport), M(z, v.item), M(B, v.gap), v.scrollTop > 0 && (M(dt, true), Rt(x(d, qt(1)), (N) => {
              M(dt, false);
            }), M(c2, { top: v.scrollTop })));
          }
        ), F(
          x(
            O,
            H(({ height: v }) => v)
          ),
          S
        ), F(
          x(
            rt(
              A(O, he),
              A(z, he),
              A(B, (v, N) => v && v.column === N.column && v.row === N.row),
              A(d)
            ),
            H(([v, N, Q, it]) => ({
              gap: Q,
              item: N,
              scrollTop: it,
              viewport: v
            }))
          ),
          q
        ), F(
          x(
            rt(
              A(a),
              o,
              A(B, Er),
              A(z, he),
              A(O, he),
              A(nt),
              A(R),
              A(dt),
              A(ft),
              A(St)
            ),
            V(([, , , , , , , v]) => !v),
            H(
              ([
                v,
                [N, Q],
                it,
                tt,
                kt,
                Jt,
                Dt,
                ,
                de,
                Ot
              ]) => {
                const { column: Ft, row: Qt } = it, { height: fe, width: Ee } = tt, { width: Qe } = kt;
                if (Dt === 0 && (v === 0 || Qe === 0))
                  return wn;
                if (Ee === 0) {
                  const rn = $e(Ot, v), ro = rn + Math.max(Dt - 1, 0);
                  return Rr(vn(rn, ro, Jt));
                }
                const me = eo(Qe, Ee, Ft);
                let $t, Mt;
                de ? N === 0 && Q === 0 && Dt > 0 ? ($t = 0, Mt = Dt - 1) : ($t = me * we((N + Qt) / (fe + Qt)), Mt = me * Cn((Q + Qt) / (fe + Qt)) - 1, Mt = Oe(v - 1, ee(Mt, me - 1)), $t = Oe(Mt, ee(0, $t))) : ($t = 0, Mt = -1);
                const tn = vn($t, Mt, Jt), { bottom: en, top: nn } = bn(kt, it, tt, tn), on = Cn(v / me), oo = on * fe + (on - 1) * Qt - en;
                return { bottom: en, itemHeight: fe, items: tn, itemWidth: Ee, offsetBottom: oo, offsetTop: nn, top: nn };
              }
            )
          ),
          k
        ), F(
          x(
            nt,
            V((v) => v !== null),
            H((v) => v.length)
          ),
          a
        ), F(
          x(
            rt(O, z, k, B),
            V(([v, N, { items: Q }]) => Q.length > 0 && N.height !== 0 && v.height !== 0),
            H(([v, N, { items: Q }, it]) => {
              const { bottom: tt, top: kt } = bn(v, it, N, Q);
              return [kt, tt];
            }),
            Y(se)
          ),
          e
        );
        const xt = w(false);
        F(
          x(
            d,
            G(xt),
            H(([v, N]) => N || v !== 0)
          ),
          xt
        );
        const Xt = pt(
          x(
            rt(k, a),
            V(([{ items: v }]) => v.length > 0),
            G(xt),
            V(([[v, N], Q]) => {
              const tt = v.items[v.items.length - 1].index === N - 1;
              return (Q || v.bottom > 0 && v.itemHeight > 0 && v.offsetBottom === 0 && v.items.length === N) && tt;
            }),
            H(([[, v]]) => v - 1),
            Y()
          )
        ), Wt = pt(
          x(
            A(k),
            V(({ items: v }) => v.length > 0 && v[0].index === 0),
            vt$1(0),
            Y()
          )
        ), yt = pt(
          x(
            A(k),
            G(dt),
            V(([{ items: v }, N]) => v.length > 0 && !N),
            H(([{ items: v }]) => ({
              endIndex: v[v.length - 1].index,
              startIndex: v[0].index
            })),
            Y(Vn),
            zt(0)
          )
        );
        F(yt, m.scrollSeekRangeChanged), F(
          x(
            P2,
            G(O, z, a, B),
            H(([v, N, Q, it, tt]) => {
              const kt = Gn(v), { align: Jt, behavior: Dt, offset: de } = kt;
              let Ot = kt.index;
              Ot === "LAST" && (Ot = it - 1), Ot = ee(0, Ot, Oe(it - 1, Ot));
              let Ft = Ve(N, tt, Q, Ot);
              return Jt === "end" ? Ft = yn(Ft - N.height + Q.height) : Jt === "center" && (Ft = yn(Ft - N.height / 2 + Q.height / 2)), de && (Ft += de), { behavior: Dt, top: Ft };
            })
          ),
          c2
        );
        const Bt = ct(
          x(
            k,
            H((v) => v.offsetBottom + v.bottom)
          ),
          0
        );
        return F(
          x(
            b,
            H((v) => ({ height: v.visibleHeight, width: v.visibleWidth }))
          ),
          O
        ), {
          customScrollParent: y,
          // input
          data: nt,
          deviation: J,
          footerHeight: r2,
          gap: B,
          headerHeight: s,
          increaseViewportBy: t2,
          initialItemCount: R,
          itemDimensions: z,
          overscan: n,
          restoreStateFrom: st,
          scrollBy: i2,
          scrollContainerState: l,
          scrollHeight: D,
          scrollTo: c2,
          scrollToIndex: P2,
          scrollTop: d,
          smoothScrollTargetReached: f,
          totalCount: a,
          useWindowScroll: g,
          viewportDimensions: O,
          windowScrollContainerState: u,
          windowScrollTo: T,
          windowViewportRect: b,
          ...m,
          // output
          gridState: k,
          horizontalDirection: At,
          initialTopMostItemIndex: St,
          totalListHeight: Bt,
          ...p,
          endReached: Xt,
          propsReady: I,
          rangeChanged: yt,
          startReached: Wt,
          stateChanged: q,
          stateRestoreInProgress: dt,
          ...h
        };
      },
      X(Ue, at, ae, Un, Vt$1, Ke, Pt)
    );
    function eo(t2, e, n) {
      return ee(1, we((t2 + n) / (we(e) + n)));
    }
    function bn(t2, e, n, o) {
      const { height: r2 } = n;
      if (r2 === void 0 || o.length === 0)
        return { bottom: 0, top: 0 };
      const s = Ve(t2, e, n, o[0].index);
      return { bottom: Ve(t2, e, n, o[o.length - 1].index) + r2, top: s };
    }
    function Ve(t2, e, n, o) {
      const r2 = eo(t2.width, n.width, e.column), s = we(o / r2), i2 = s * n.height + ee(0, s - 1) * e.row;
      return i2 > 0 ? i2 + e.row : i2;
    }
    const Br = /* @__PURE__ */ U(() => {
      const t2 = w((S) => `Item ${S}`), e = w({}), n = w(null), o = w("virtuoso-grid-item"), r2 = w("virtuoso-grid-list"), s = w(qe), i2 = w("div"), l = w(Gt), c2 = (S, p = null) => ct(
        x(
          e,
          H((m) => m[S]),
          Y()
        ),
        p
      ), d = w(false), f = w(false);
      return F(A(f), d), {
        components: e,
        computeItemKey: s,
        context: n,
        FooterComponent: c2("Footer"),
        HeaderComponent: c2("Header"),
        headerFooterTag: i2,
        itemClassName: o,
        ItemComponent: c2("Item", "div"),
        itemContent: t2,
        listClassName: r2,
        ListComponent: c2("List", "div"),
        readyStateChanged: d,
        reportReadyState: f,
        ScrollerComponent: c2("Scroller", "div"),
        scrollerRef: l,
        ScrollSeekPlaceholder: c2("ScrollSeekPlaceholder", "div")
      };
    }), kr = /* @__PURE__ */ U(
      ([t2, e]) => ({ ...t2, ...e }),
      X(Hr, Br)
    ), Or = /* @__PURE__ */ React$2.memo(function() {
      const e = et("gridState"), n = et("listClassName"), o = et("itemClassName"), r2 = et("itemContent"), s = et("computeItemKey"), i2 = et("isSeeking"), l = It("scrollHeight"), c2 = et("ItemComponent"), d = et("ListComponent"), f = et("ScrollSeekPlaceholder"), S = et("context"), p = It("itemDimensions"), m = It("gap"), C2 = et("log"), I = et("stateRestoreInProgress"), y = It("reportReadyState"), g = Et(
        React$2.useMemo(
          () => (u) => {
            const T = u.parentElement.parentElement.scrollHeight;
            l(T);
            const b = u.firstChild;
            if (b) {
              const { height: h, width: a } = b.getBoundingClientRect();
              p({ height: h, width: a });
            }
            m({
              column: Rn("column-gap", getComputedStyle(u).columnGap, C2),
              row: Rn("row-gap", getComputedStyle(u).rowGap, C2)
            });
          },
          [l, p, m, C2]
        ),
        true,
        false
      );
      return Yn(() => {
        e.itemHeight > 0 && e.itemWidth > 0 && y(true);
      }, [e]), I ? null : /* @__PURE__ */ jsxRuntimeExports.jsx(
        d,
        {
          className: n,
          ref: g,
          ...Z(d, S),
          "data-testid": "virtuoso-item-list",
          style: { paddingBottom: e.offsetBottom, paddingTop: e.offsetTop },
          children: e.items.map((u) => {
            const T = s(u.index, u.data, S);
            return i2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              f,
              {
                ...Z(f, S),
                height: e.itemHeight,
                index: u.index,
                width: e.itemWidth
              },
              T
            ) : /* @__PURE__ */ reactExports.createElement(
              c2,
              {
                ...Z(c2, S),
                className: o,
                "data-index": u.index,
                key: T
              },
              r2(u.index, u.data, S)
            );
          })
        }
      );
    }), Fr = React$2.memo(function() {
      const e = et("HeaderComponent"), n = It("headerHeight"), o = et("headerFooterTag"), r2 = Et(
        React$2.useMemo(
          () => (i2) => {
            n(Ct(i2, "height"));
          },
          [n]
        ),
        true,
        false
      ), s = et("context");
      return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z(e, s) }) }) : null;
    }), zr = React$2.memo(function() {
      const e = et("FooterComponent"), n = It("footerHeight"), o = et("headerFooterTag"), r2 = Et(
        React$2.useMemo(
          () => (i2) => {
            n(Ct(i2, "height"));
          },
          [n]
        ),
        true,
        false
      ), s = et("context");
      return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z(e, s) }) }) : null;
    }), Lr = ({ children: t2 }) => {
      const e = React$2.useContext(qn), n = It("itemDimensions"), o = It("viewportDimensions"), r2 = Et(
        React$2.useMemo(
          () => (s) => {
            o(s.getBoundingClientRect());
          },
          [o]
        ),
        true,
        false
      );
      return React$2.useEffect(() => {
        e && (o({ height: e.viewportHeight, width: e.viewportWidth }), n({ height: e.itemHeight, width: e.itemWidth }));
      }, [e, o, n]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: r2, style: Zt(false), children: t2 });
    }, Pr = ({ children: t2 }) => {
      const e = React$2.useContext(qn), n = It("windowViewportRect"), o = It("itemDimensions"), r2 = et("customScrollParent"), s = _e(n, r2, false);
      return React$2.useEffect(() => {
        e && (o({ height: e.itemHeight, width: e.itemWidth }), n({ offsetTop: 0, visibleHeight: e.viewportHeight, visibleWidth: e.viewportWidth }));
      }, [e, n, o]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: s, style: Zt(false), children: t2 });
    }, Vr = /* @__PURE__ */ React$2.memo(function({ ...e }) {
      const n = et("useWindowScroll"), o = et("customScrollParent"), r2 = o || n ? Mr : Wr, s = o || n ? Pr : Lr, i2 = et("context");
      return /* @__PURE__ */ jsxRuntimeExports.jsx(r2, { ...e, ...Z(r2, i2), children: /* @__PURE__ */ jsxRuntimeExports.jsxs(s, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Fr, {}),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Or, {}),
        /* @__PURE__ */ jsxRuntimeExports.jsx(zr, {})
      ] }) });
    }), {
      useEmitter: no,
      useEmitterValue: et,
      usePublisher: It
    } = /* @__PURE__ */ je(
      kr,
      {
        events: {
          atBottomStateChange: "atBottomStateChange",
          atTopStateChange: "atTopStateChange",
          endReached: "endReached",
          isScrolling: "isScrolling",
          rangeChanged: "rangeChanged",
          readyStateChanged: "readyStateChanged",
          startReached: "startReached",
          stateChanged: "stateChanged"
        },
        methods: {
          scrollBy: "scrollBy",
          scrollTo: "scrollTo",
          scrollToIndex: "scrollToIndex"
        },
        optional: {
          components: "components",
          computeItemKey: "computeItemKey",
          context: "context",
          customScrollParent: "customScrollParent",
          data: "data",
          headerFooterTag: "headerFooterTag",
          increaseViewportBy: "increaseViewportBy",
          initialItemCount: "initialItemCount",
          initialTopMostItemIndex: "initialTopMostItemIndex",
          itemClassName: "itemClassName",
          itemContent: "itemContent",
          listClassName: "listClassName",
          logLevel: "logLevel",
          overscan: "overscan",
          restoreStateFrom: "restoreStateFrom",
          scrollerRef: "scrollerRef",
          scrollSeekConfiguration: "scrollSeekConfiguration",
          totalCount: "totalCount",
          useWindowScroll: "useWindowScroll"
        }
      },
      Vr
    ), Wr = /* @__PURE__ */ Ye({ useEmitter: no, useEmitterValue: et, usePublisher: It }), Mr = /* @__PURE__ */ Ze({ useEmitter: no, useEmitterValue: et, usePublisher: It });
    function Rn(t2, e, n) {
      return e !== "normal" && !(e != null && e.endsWith("px")) && n(`${t2} was not resolved to pixel value correctly`, e, ht.WARN), e === "normal" ? 0 : parseInt(e != null ? e : "0", 10);
    }
    const list = "_list_1emnm_1";
    const styles$F = {
      list
    };
    const ChatViewVirtualList = ({
      id,
      messages,
      toolCallStyle,
      className: className2,
      indented: indented2,
      numbered = true,
      scrollRef
    }) => {
      const collapsedMessages = resolveMessages(messages);
      const [followOutput, setFollowOutput] = reactExports.useState(false);
      const renderRow = (item2, index2) => {
        const number2 = collapsedMessages.length > 1 && numbered ? index2 + 1 : void 0;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          ChatMessageRow,
          {
            parentName: id || "chat-virtual-list",
            number: number2,
            resolvedMessage: item2,
            indented: indented2,
            toolCallStyle
          }
        );
      };
      const result2 = /* @__PURE__ */ jsxRuntimeExports.jsx(
        $r,
        {
          customScrollParent: (scrollRef == null ? void 0 : scrollRef.current) ? scrollRef.current : void 0,
          style: { height: "100%", width: "100%" },
          data: collapsedMessages,
          itemContent: (index2, data) => {
            return renderRow(data, index2);
          },
          increaseViewportBy: { top: 1e3, bottom: 1e3 },
          overscan: {
            main: 10,
            reverse: 10
          },
          followOutput,
          atBottomStateChange: (atBottom) => {
            setFollowOutput(atBottom);
          },
          skipAnimationFrameInResizeObserver: true,
          className: clsx(styles$F.list, className2)
        }
      );
      return result2;
    };
    const tabPanel = "_tabPanel_1isha_1";
    const fullWidth = "_fullWidth_1isha_5";
    const metadataPanel = "_metadataPanel_1isha_9";
    const padded = "_padded_1isha_18";
    const ansi = "_ansi_1isha_23";
    const noTop = "_noTop_1isha_27";
    const timePanel = "_timePanel_1isha_31";
    const styles$E = {
      tabPanel,
      fullWidth,
      metadataPanel,
      padded,
      ansi,
      noTop,
      timePanel
    };
    const flatBody = "_flatBody_1uw6w_1";
    const iconSmall$1 = "_iconSmall_1uw6w_9";
    const lineBase = "_lineBase_1uw6w_15";
    const styles$D = {
      flatBody,
      iconSmall: iconSmall$1,
      lineBase
    };
    const errorType = (message2) => {
      if (!message2) {
        return "Error";
      }
      if (message2.includes("(")) {
        return message2.split("(")[0];
      }
      return "Error";
    };
    const FlatSampleError = ({ message: message2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$D.flatBody), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: clsx(ApplicationIcons.error, styles$D.iconSmall) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$D.lineBase, "text-truncate"), children: errorType(message2) })
      ] });
    };
    const target = "_target_9qy4e_1";
    const answer = "_answer_9qy4e_5";
    const grid$3 = "_grid_9qy4e_9";
    const centerLabel = "_centerLabel_9qy4e_17";
    const wrap = "_wrap_9qy4e_22";
    const titled = "_titled_9qy4e_26";
    const styles$C = {
      target,
      answer,
      grid: grid$3,
      centerLabel,
      wrap,
      titled
    };
    const SampleSummaryView = ({
      parent_id,
      sample: sample2,
      sampleDescriptor
    }) => {
      var _a2;
      const input2 = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.input) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.input) : 0;
      const target2 = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.target) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.target) : 0;
      const answer2 = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.answer) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.answer) : 0;
      const limitSize = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.limit) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.limit) : 0;
      const timeSize = sample2.working_time || sample2.total_time ? 0.15 : 0;
      const idSize = Math.max(
        2,
        Math.min(10, sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.raw.id)
      );
      const scoreInput = inputString(sample2.input);
      if (sample2.choices && sample2.choices.length > 0) {
        scoreInput.push("");
        scoreInput.push(
          ...sample2.choices.map((choice, index2) => {
            return `${String.fromCharCode(65 + index2)}) ${choice}`;
          })
        );
      }
      const columns = [];
      columns.push({
        label: "Id",
        value: sample2.id,
        size: `${idSize}em`
      });
      columns.push({
        label: "Input",
        value: scoreInput,
        size: `${input2}fr`,
        clamp: true
      });
      if (sample2.target) {
        columns.push({
          label: "Target",
          value: /* @__PURE__ */ jsxRuntimeExports.jsx(
            MarkdownDiv,
            {
              markdown: arrayToString(arrayToString((sample2 == null ? void 0 : sample2.target) || "none")),
              className: clsx("no-last-para-padding", styles$C.target)
            }
          ),
          size: `${target2}fr`,
          clamp: true
        });
      }
      const fullAnswer = sample2 && sampleDescriptor ? sampleDescriptor.selectedScorerDescriptor(sample2).answer() : void 0;
      if (fullAnswer) {
        columns.push({
          label: "Answer",
          value: sample2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            MarkdownDiv,
            {
              markdown: fullAnswer,
              className: clsx("no-last-para-padding", styles$C.answer)
            }
          ) : "",
          size: `${answer2}fr`,
          clamp: true
        });
      }
      const toolTip = (working_time) => {
        if (working_time === void 0 || working_time === null) {
          return void 0;
        }
        return `Working time: ${formatTime$1(working_time)}`;
      };
      if (sample2.total_time) {
        columns.push({
          label: "Time",
          value: formatTime$1(sample2.total_time),
          size: `${timeSize}fr`,
          center: true,
          title: toolTip(sample2.working_time)
        });
      }
      if ((sample2 == null ? void 0 : sample2.limit) && limitSize > 0) {
        columns.push({
          label: "Limit",
          value: sample2.limit.type,
          size: `${limitSize}fr`,
          center: true
        });
      }
      columns.push({
        label: "Score",
        value: sample2.error ? /* @__PURE__ */ jsxRuntimeExports.jsx(FlatSampleError, { message: sample2.error.message }) : (
          // TODO: Cleanup once the PR lands which makes sample / sample summary share common interface
          ((_a2 = sampleDescriptor == null ? void 0 : sampleDescriptor.selectedScore(sample2)) == null ? void 0 : _a2.render()) || ""
        ),
        size: "minmax(2em, 30em)",
        center: true
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          id: `sample-heading-${parent_id}`,
          className: clsx(styles$C.grid, "text-size-base"),
          style: {
            gridTemplateColumns: `${columns.map((col) => {
              return col.size;
            }).join(" ")}`
          },
          children: [
            columns.map((col, idx) => {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: clsx(
                    "text-style-label",
                    "text-style-secondary",
                    "text-size-base",
                    col.title ? styles$C.titled : void 0,
                    col.center ? styles$C.centerLabel : void 0
                  ),
                  title: col.title,
                  children: col.label
                },
                `sample-summ-lbl-${idx}`
              );
            }),
            columns.map((col, idx) => {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: clsx(
                    styles$C.wrap,
                    col.clamp ? "three-line-clamp" : void 0,
                    col.center ? styles$C.centerLabel : void 0
                  ),
                  children: col.value
                },
                `sample-summ-val-${idx}`
              );
            })
          ]
        }
      );
    };
    const title$2 = "_title_19l1b_1";
    const contents = "_contents_19l1b_8";
    const styles$B = {
      title: title$2,
      contents
    };
    const EventRow = ({
      title: title2,
      icon,
      className: className2,
      children: children2
    }) => {
      const contentEl = title2 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("text-size-small", styles$B.title, className2), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: icon || ApplicationIcons.metadata }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label"), children: title2 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: children2 })
      ] }) : "";
      const card2 = /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("card", styles$B.contents), children: contentEl });
      return card2;
    };
    const ApprovalEventView = ({
      event,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventRow,
        {
          title: decisionLabel(event.decision),
          icon: decisionIcon(event.decision),
          className: className2,
          children: event.explanation || ""
        }
      );
    };
    const decisionLabel = (decision) => {
      switch (decision) {
        case "approve":
          return "Approved";
        case "reject":
          return "Rejected";
        case "terminate":
          return "Terminated";
        case "escalate":
          return "Escalated";
        case "modify":
          return "Modified";
        default:
          return decision;
      }
    };
    const decisionIcon = (decision) => {
      switch (decision) {
        case "approve":
          return ApplicationIcons.approvals.approve;
        case "reject":
          return ApplicationIcons.approvals.reject;
        case "terminate":
          return ApplicationIcons.approvals.terminate;
        case "escalate":
          return ApplicationIcons.approvals.escalate;
        case "modify":
          return ApplicationIcons.approvals.modify;
        default:
          return ApplicationIcons.approve;
      }
    };
    const tab = "_tab_1je38_1";
    const styles$A = {
      tab
    };
    const EventNav = ({
      target: target2,
      title: title2,
      selectedNav,
      setSelectedNav
    }) => {
      const active2 = target2 === selectedNav;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("li", { className: "nav-item", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          role: "tab",
          "aria-controls": target2,
          "aria-selected": active2,
          className: clsx(
            "nav-link",
            active2 ? "active " : "",
            "text-style-label",
            "text-size-small",
            styles$A.tab
          ),
          onClick: () => {
            setSelectedNav(target2);
          },
          children: title2
        }
      ) });
    };
    const navs$1 = "_navs_1vm6p_1";
    const styles$z = {
      navs: navs$1
    };
    const EventNavs = ({
      navs: navs2,
      selectedNav,
      setSelectedNav
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "ul",
        {
          className: clsx("nav", "nav-pills", styles$z.navs),
          role: "tablist",
          "aria-orientation": "horizontal",
          children: navs2.map((nav2) => {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              EventNav,
              {
                target: nav2.target,
                title: nav2.title,
                selectedNav,
                setSelectedNav
              },
              nav2.title
            );
          })
        }
      );
    };
    const label = "_label_7z797_1";
    const navs = "_navs_7z797_6";
    const card = "_card_7z797_12";
    const cardContent = "_cardContent_7z797_18";
    const hidden$1 = "_hidden_7z797_23";
    const styles$y = {
      label,
      navs,
      card,
      cardContent,
      hidden: hidden$1
    };
    const EventPanel = ({
      id,
      className: className2,
      title: title2,
      subTitle,
      text: text2,
      icon,
      collapse,
      collapsed,
      setCollapsed,
      children: children2,
      setSelectedNav,
      selectedNav
    }) => {
      const hasCollapse = collapse !== void 0;
      const isCollapsed = collapsed === void 0 ? collapse : collapsed;
      const pillId = (index2) => {
        return `${id}-nav-pill-${index2}`;
      };
      const filteredArrChildren = (Array.isArray(children2) ? children2 : [children2]).filter((child) => !!child);
      const defaultPillId = pillId(0);
      const gridColumns2 = [];
      if (hasCollapse) {
        gridColumns2.push("minmax(0, max-content)");
      }
      if (icon) {
        gridColumns2.push("max-content");
      }
      gridColumns2.push("minmax(0, max-content)");
      gridColumns2.push("auto");
      gridColumns2.push("minmax(0, max-content)");
      gridColumns2.push("minmax(0, max-content)");
      const titleEl = title2 || icon || filteredArrChildren.length > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          title: subTitle,
          className: clsx("text-size-small"),
          style: {
            display: "grid",
            gridTemplateColumns: gridColumns2.join(" "),
            columnGap: "0.3em",
            cursor: hasCollapse ? "pointer" : void 0
          },
          children: [
            hasCollapse ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              "i",
              {
                onClick: () => {
                  setCollapsed(!isCollapsed);
                },
                className: isCollapsed ? ApplicationIcons.chevron.right : ApplicationIcons.chevron.down
              }
            ) : "",
            icon ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              "i",
              {
                className: clsx(
                  icon || ApplicationIcons.metadata,
                  "text-style-secondary"
                ),
                onClick: () => {
                  setCollapsed(!isCollapsed);
                }
              }
            ) : "",
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx("text-style-secondary", "text-style-label"),
                onClick: () => {
                  setCollapsed(!isCollapsed);
                },
                children: title2
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                onClick: () => {
                  setCollapsed(!isCollapsed);
                }
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx("text-style-secondary", styles$y.label),
                onClick: () => {
                  setCollapsed(!isCollapsed);
                },
                children: collapsed ? text2 : ""
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$y.navs, children: (!hasCollapse || !isCollapsed) && filteredArrChildren && filteredArrChildren.length > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              EventNavs,
              {
                navs: filteredArrChildren.map((child, index2) => {
                  const defaultTitle = `Tab ${index2}`;
                  const title22 = child && React$2.isValidElement(child) ? child.props["data-name"] || defaultTitle : defaultTitle;
                  return {
                    id: `eventpanel-${id}-${index2}`,
                    title: title22,
                    target: pillId(index2)
                  };
                }),
                selectedNav: selectedNav || defaultPillId,
                setSelectedNav
              }
            ) : "" })
          ]
        }
      ) : "";
      const card2 = /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { id, className: clsx(className2, styles$y.card), children: [
        titleEl,
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: clsx(
              "tab-content",
              styles$y.cardContent,
              hasCollapse && isCollapsed ? styles$y.hidden : void 0
            ),
            children: filteredArrChildren == null ? void 0 : filteredArrChildren.map((child, index2) => {
              const id2 = pillId(index2);
              const isSelected = selectedNav ? id2 === selectedNav : id2 === defaultPillId;
              return /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  id: id2,
                  className: clsx("tab-pane", "show", isSelected ? "active" : ""),
                  children: child
                },
                `children-${id2}-${index2}`
              );
            })
          }
        )
      ] });
      return card2;
    };
    const ErrorEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventPanel,
        {
          id,
          title: "Error",
          className: className2,
          subTitle: formatDateTime(new Date(event.timestamp)),
          icon: ApplicationIcons.error,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            ANSIDisplay,
            {
              output: event.error.traceback_ansi,
              style: {
                fontSize: "clamp(0.5rem, calc(0.25em + 1vw), 0.8rem)",
                margin: "0.5em 0"
              }
            }
          )
        }
      );
    };
    const panel = "_panel_8zdtn_1";
    const styles$x = {
      panel
    };
    const InfoEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      const panels = [];
      if (typeof event.data === "string") {
        panels.push(/* @__PURE__ */ jsxRuntimeExports.jsx(MarkdownDiv, { markdown: event.data, className: styles$x.panel }));
      } else {
        panels.push(/* @__PURE__ */ jsxRuntimeExports.jsx(JSONPanel, { data: event.data, className: styles$x.panel }));
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventPanel,
        {
          id,
          title: "Info" + (event.source ? ": " + event.source : ""),
          className: className2,
          subTitle: formatDateTime(new Date(event.timestamp)),
          icon: ApplicationIcons.info,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: panels
        }
      );
    };
    const InputEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventPanel,
        {
          id,
          title: "Input",
          className: className2,
          subTitle: formatDateTime(new Date(event.timestamp)),
          icon: ApplicationIcons.input,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            ANSIDisplay,
            {
              output: event.input_ansi,
              style: { fontSize: "clamp(0.4rem, 1.15vw, 0.9rem)" }
            }
          )
        }
      );
    };
    const grid$2 = "_grid_1eq5o_1";
    const styles$w = {
      grid: grid$2
    };
    const LoggerEventView = ({
      event,
      className: className2
    }) => {
      const obj = parsedJson(event.message.message);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventRow,
        {
          className: className2,
          title: event.message.level,
          icon: ApplicationIcons.logging[event.message.level.toLowerCase()],
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("text-size-base", styles$w.grid), children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-smaller"), children: obj !== void 0 && obj !== null ? /* @__PURE__ */ jsxRuntimeExports.jsx(MetaDataGrid, { entries: obj }) : event.message.message }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("text-size-smaller", "text-style-secondary"), children: [
              event.message.filename,
              ":",
              event.message.lineno
            ] })
          ] })
        }
      );
    };
    const container$7 = "_container_1brs9_1";
    const title$1 = "_title_1brs9_5";
    const styles$v = {
      container: container$7,
      title: title$1
    };
    const EventSection = ({
      title: title2,
      children: children2,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$v.container, className2), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: clsx("text-size-small", "text-style-label", styles$v.title),
            children: title2
          }
        ),
        children2
      ] });
    };
    const output = "_output_3axgd_1";
    const container$6 = "_container_3axgd_5";
    const all = "_all_3axgd_10";
    const tableSelection = "_tableSelection_3axgd_16";
    const tools$1 = "_tools_3axgd_22";
    const codePre = "_codePre_3axgd_26";
    const code$1 = "_code_3axgd_26";
    const toolConfig = "_toolConfig_3axgd_38";
    const styles$u = {
      output,
      container: container$6,
      all,
      tableSelection,
      tools: tools$1,
      codePre,
      code: code$1,
      toolConfig
    };
    const wrapper$2 = "_wrapper_45f60_1";
    const col2$1 = "_col2_45f60_8";
    const col1_3 = "_col1_3_45f60_12";
    const col3 = "_col3_45f60_16";
    const separator$2 = "_separator_45f60_20";
    const topMargin = "_topMargin_45f60_26";
    const styles$t = {
      wrapper: wrapper$2,
      col2: col2$1,
      col1_3,
      col3,
      separator: separator$2,
      topMargin
    };
    const EventTimingPanel = ({
      timestamp,
      completed,
      working_start,
      working_time
    }) => {
      const rows = [
        {
          label: "Clock Time",
          value: void 0,
          secondary: false
        },
        {
          label: "---",
          value: void 0,
          secondary: false
        }
      ];
      if (!completed) {
        rows.push({
          label: "Timestamp",
          value: formatDateTime(new Date(timestamp))
        });
      } else {
        rows.push({ label: "Start", value: formatDateTime(new Date(timestamp)) });
        rows.push({ label: "End", value: formatDateTime(new Date(completed)) });
      }
      if (working_start || working_time) {
        rows.push({
          label: "Working Time",
          value: void 0,
          secondary: false,
          topMargin: true
        });
        rows.push({
          label: "---",
          value: void 0,
          secondary: false
        });
        if (working_start) {
          rows.push({
            label: "Start",
            value: formatTime$1(working_start)
          });
        }
        if (working_time) {
          rows.push({
            label: "Duration",
            value: formatTime$1(working_time)
          });
        }
        if (working_start && working_time) {
          rows.push({
            label: "End",
            value: formatTime$1(
              Math.round(working_start * 10) / 10 + Math.round(working_time * 10) / 10
            )
          });
        }
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-small", styles$t.wrapper), children: rows.map((row2, idx) => {
        if (row2.label === "---") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$t.separator }, `$usage-sep-${idx}`);
        } else {
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  "text-style-label",
                  "text-style-secondary",
                  row2.secondary ? styles$t.col2 : styles$t.col1_3,
                  row2.topMargin ? styles$t.topMargin : void 0
                ),
                children: row2.label
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$t.col3, children: row2.value ? row2.value : "" })
          ] }, `$usage-row-${idx}`);
        }
      }) });
    };
    const formatTiming = (timestamp, working_start) => {
      if (working_start) {
        return `${formatDateTime(new Date(timestamp))}
@ working time: ${formatTime$1(working_start)}`;
      } else {
        return formatDateTime(new Date(timestamp));
      }
    };
    const formatTitle = (title2, total_tokens, working_start) => {
      const subItems = [];
      if (total_tokens) {
        subItems.push(`${formatNumber(total_tokens)} tokens`);
      }
      if (working_start) {
        subItems.push(`${formatTime$1(working_start)}`);
      }
      const subtitle = subItems.length > 0 ? ` (${subItems.join(", ")})` : "";
      return `${title2}${subtitle}`;
    };
    const ModelEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      var _a2, _b2;
      const totalUsage = (_a2 = event.output.usage) == null ? void 0 : _a2.total_tokens;
      const callTime = event.output.time;
      const outputMessages = (_b2 = event.output.choices) == null ? void 0 : _b2.map((choice) => {
        return choice.message;
      });
      const entries = { ...event.config };
      entries["tool_choice"] = event.tool_choice;
      delete entries["max_connections"];
      const userMessages = [];
      for (const msg of event.input.slice().reverse()) {
        if (msg.role === "user" && !msg.tool_call_id) {
          userMessages.push(msg);
        } else {
          break;
        }
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        EventPanel,
        {
          id,
          className: className2,
          title: formatTitle(`Model Call: ${event.model}`, totalUsage, callTime),
          subTitle: formatTiming(event.timestamp, event.working_start),
          icon: ApplicationIcons.model,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-name": "Summary", className: styles$u.container, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              ChatView,
              {
                id: `${id}-model-output`,
                messages: [...userMessages, ...outputMessages || []],
                className: clsx(styles$u.output),
                numbered: false,
                toolCallStyle: "compact"
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { "data-name": "All", className: styles$u.container, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$u.all, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Configuration", className: styles$u.tableSelection, children: /* @__PURE__ */ jsxRuntimeExports.jsx(MetaDataGrid, { entries, plain: true }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Usage", className: styles$u.tableSelection, children: event.output.usage !== null ? /* @__PURE__ */ jsxRuntimeExports.jsx(ModelUsagePanel, { usage: event.output.usage }) : void 0 }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Timing", className: styles$u.tableSelection, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  EventTimingPanel,
                  {
                    timestamp: event.timestamp,
                    completed: event.completed,
                    working_start: event.working_start,
                    working_time: event.working_time
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  EventSection,
                  {
                    title: "Tools",
                    className: clsx(styles$u.tableSelection, styles$u.tools),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(ToolsConfig, { tools: event.tools })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Messages", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                ChatView,
                {
                  id: `${id}-model-input-full`,
                  messages: [...event.input, ...outputMessages || []]
                }
              ) })
            ] }),
            event.call ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              APIView,
              {
                "data-name": "API",
                call: event.call,
                className: styles$u.container
              }
            ) : ""
          ]
        }
      );
    };
    const APIView = ({ call, className: className2 }) => {
      if (!call) {
        return null;
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(className2), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Request", children: /* @__PURE__ */ jsxRuntimeExports.jsx(APICodeCell, { contents: call.request }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Response", children: /* @__PURE__ */ jsxRuntimeExports.jsx(APICodeCell, { contents: call.response }) })
      ] });
    };
    const APICodeCell = ({ id, contents: contents2 }) => {
      const codeRef = reactExports.useRef(null);
      const sourceCode = reactExports.useMemo(() => {
        return JSON.stringify(contents2, void 0, 2);
      }, [contents2]);
      reactExports.useEffect(() => {
        if (codeRef.current) {
          prismExports.highlightElement(codeRef.current);
        }
      }, [contents2]);
      if (!contents2) {
        return null;
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("model-call"), children: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: clsx(styles$u.codePre), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "code",
        {
          id,
          ref: codeRef,
          className: clsx("language-json", styles$u.code, "text-size-small"),
          children: sourceCode
        }
      ) }) });
    };
    const ToolsConfig = ({ tools: tools2 }) => {
      const toolEls = tools2.map((tool2, idx) => {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label", "text-style-secondary"), children: tool2.name }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: tool2.description })
        ] }, `${tool2.name}-${idx}`);
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$u.toolConfig, children: toolEls });
    };
    const noMargin = "_noMargin_1a3fk_1";
    const code = "_code_1a3fk_5";
    const sample = "_sample_1a3fk_10";
    const section = "_section_1a3fk_14";
    const metadata$1 = "_metadata_1a3fk_21";
    const styles$s = {
      noMargin,
      code,
      sample,
      section,
      metadata: metadata$1
    };
    const SampleInitEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      const stateObj = event.state;
      const sections = [];
      if (event.sample.files && Object.keys(event.sample.files).length > 0) {
        sections.push(
          /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Files", children: Object.keys(event.sample.files).map((file) => {
            return /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: styles$s.noMargin, children: file }, `sample-init-file-${file}`);
          }) }, `sample-${id}-init-files`)
        );
      }
      if (event.sample.setup) {
        sections.push(
          /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Setup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: styles$s.code, children: /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "sourceCode", children: event.sample.setup }) }) }, `sample-${id}-init-setup`)
        );
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        EventPanel,
        {
          id,
          className: className2,
          title: "Sample",
          icon: ApplicationIcons.sample,
          subTitle: formatDateTime(new Date(event.timestamp)),
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { "data-name": "Sample", className: styles$s.sample, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ChatView, { messages: stateObj["messages"] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                event.sample.choices ? event.sample.choices.map((choice, index2) => {
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    String.fromCharCode(65 + index2),
                    ") ",
                    choice
                  ] }, `$choice-{choice}`);
                }) : "",
                sections.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$s.section, children: sections }) : "",
                /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Target", children: toArray(event.sample.target).map((target2) => {
                  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: target2 }, target2);
                }) })
              ] })
            ] }),
            event.sample.metadata && Object.keys(event.sample.metadata).length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MetaDataGrid,
              {
                "data-name": "Metadata",
                className: styles$s.metadata,
                entries: event.sample.metadata
              }
            ) : ""
          ]
        }
      );
    };
    const SampleLimitEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      const resolve_title = (type) => {
        switch (type) {
          case "custom":
            return "Custom Limit Exceeded";
          case "time":
            return "Time Limit Execeeded";
          case "message":
            return "Message Limit Exceeded";
          case "token":
            return "Token Limit Exceeded";
          case "operator":
            return "Operator Canceled";
          case "working":
            return "Execution Time Limit Exceeded";
        }
      };
      const resolve_icon = (type) => {
        switch (type) {
          case "custom":
            return ApplicationIcons.limits.custom;
          case "time":
            return ApplicationIcons.limits.time;
          case "message":
            return ApplicationIcons.limits.messages;
          case "token":
            return ApplicationIcons.limits.tokens;
          case "operator":
            return ApplicationIcons.limits.operator;
          case "working":
            return ApplicationIcons.limits.execution;
        }
      };
      const title2 = resolve_title(event.type);
      const icon = resolve_icon(event.type);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventPanel,
        {
          id,
          title: title2,
          icon,
          className: className2,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: event.message
        }
      );
    };
    const explanation = "_explanation_1ww42_1";
    const separator$1 = "_separator_1ww42_8";
    const metadata = "_metadata_1ww42_13";
    const styles$r = {
      explanation,
      separator: separator$1,
      metadata
    };
    const ScoreEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      const resolvedTarget = event.target ? Array.isArray(event.target) ? event.target.join("\n") : event.target : void 0;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        EventPanel,
        {
          id,
          title: (event.intermediate ? "Intermediate " : "") + "Score",
          className: clsx(className2, "text-size-small"),
          subTitle: formatDateTime(new Date(event.timestamp)),
          icon: ApplicationIcons.scorer,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { "data-name": "Explanation", className: clsx(styles$r.explanation), children: [
              event.target ? /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$r.separator) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-style-label", children: "Target" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(MarkdownDiv, { markdown: resolvedTarget || "" }) })
              ] }) : "",
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$r.separator) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-style-label", children: "Answer" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(MarkdownDiv, { markdown: event.score.answer || "" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$r.separator) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-style-label", children: "Explanation" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(MarkdownDiv, { markdown: event.score.explanation || "" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$r.separator) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-style-label", children: "Score" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: renderScore(event.score.value) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$r.separator) })
            ] }),
            event.score.metadata ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-name": "Metadata", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              MetaDataGrid,
              {
                entries: event.score.metadata,
                className: styles$r.metadata
              }
            ) }) : void 0
          ]
        }
      );
    };
    const renderScore = (value2) => {
      if (Array.isArray(value2)) {
        return value2.join(" ");
      } else if (typeof value2 === "object") {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(MetaDataGrid, { entries: value2 });
      } else {
        return value2;
      }
    };
    class Processor {
      constructor(options2) {
        this.selfOptions = options2 || {};
        this.pipes = {};
      }
      options(options2) {
        if (options2) {
          this.selfOptions = options2;
        }
        return this.selfOptions;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      pipe(name2, pipeArg) {
        let pipe = pipeArg;
        if (typeof name2 === "string") {
          if (typeof pipe === "undefined") {
            return this.pipes[name2];
          } else {
            this.pipes[name2] = pipe;
          }
        }
        if (name2 && name2.name) {
          pipe = name2;
          if (pipe.processor === this) {
            return pipe;
          }
          this.pipes[pipe.name] = pipe;
        }
        pipe.processor = this;
        return pipe;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      process(input2, pipe) {
        let context = input2;
        context.options = this.options();
        let nextPipe = pipe || input2.pipe || "default";
        let lastPipe;
        while (nextPipe) {
          if (typeof context.nextAfterChildren !== "undefined") {
            context.next = context.nextAfterChildren;
            context.nextAfterChildren = null;
          }
          if (typeof nextPipe === "string") {
            nextPipe = this.pipe(nextPipe);
          }
          nextPipe.process(context);
          lastPipe = nextPipe;
          nextPipe = null;
          if (context) {
            if (context.next) {
              context = context.next;
              nextPipe = context.pipe || lastPipe;
            }
          }
        }
        return context.hasResult ? context.result : void 0;
      }
    }
    class Pipe {
      constructor(name2) {
        this.name = name2;
        this.filters = [];
      }
      process(input2) {
        if (!this.processor) {
          throw new Error("add this pipe to a processor before using it");
        }
        const debug = this.debug;
        const length = this.filters.length;
        const context = input2;
        for (let index2 = 0; index2 < length; index2++) {
          const filter = this.filters[index2];
          if (debug) {
            this.log(`filter: ${filter.filterName}`);
          }
          filter(context);
          if (typeof context === "object" && context.exiting) {
            context.exiting = false;
            break;
          }
        }
        if (!context.next && this.resultCheck) {
          this.resultCheck(context);
        }
      }
      log(msg) {
        console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
      }
      append(...args) {
        this.filters.push(...args);
        return this;
      }
      prepend(...args) {
        this.filters.unshift(...args);
        return this;
      }
      indexOf(filterName) {
        if (!filterName) {
          throw new Error("a filter name is required");
        }
        for (let index2 = 0; index2 < this.filters.length; index2++) {
          const filter = this.filters[index2];
          if (filter.filterName === filterName) {
            return index2;
          }
        }
        throw new Error(`filter not found: ${filterName}`);
      }
      list() {
        return this.filters.map((f) => f.filterName);
      }
      after(filterName, ...params2) {
        const index2 = this.indexOf(filterName);
        this.filters.splice(index2 + 1, 0, ...params2);
        return this;
      }
      before(filterName, ...params2) {
        const index2 = this.indexOf(filterName);
        this.filters.splice(index2, 0, ...params2);
        return this;
      }
      replace(filterName, ...params2) {
        const index2 = this.indexOf(filterName);
        this.filters.splice(index2, 1, ...params2);
        return this;
      }
      remove(filterName) {
        const index2 = this.indexOf(filterName);
        this.filters.splice(index2, 1);
        return this;
      }
      clear() {
        this.filters.length = 0;
        return this;
      }
      shouldHaveResult(should) {
        if (should === false) {
          this.resultCheck = null;
          return;
        }
        if (this.resultCheck) {
          return;
        }
        this.resultCheck = (context) => {
          if (!context.hasResult) {
            console.log(context);
            const error2 = new Error(`${this.name} failed`);
            error2.noResult = true;
            throw error2;
          }
        };
        return this;
      }
    }
    class Context {
      setResult(result2) {
        this.result = result2;
        this.hasResult = true;
        return this;
      }
      exit() {
        this.exiting = true;
        return this;
      }
      push(child, name2) {
        child.parent = this;
        if (typeof name2 !== "undefined") {
          child.childName = name2;
        }
        child.root = this.root || this;
        child.options = child.options || this.options;
        if (!this.children) {
          this.children = [child];
          this.nextAfterChildren = this.next || null;
          this.next = child;
        } else {
          this.children[this.children.length - 1].next = child;
          this.children.push(child);
        }
        child.next = this;
        return this;
      }
    }
    function cloneRegExp(re2) {
      const regexMatch = /^\/(.*)\/([gimyu]*)$/.exec(re2.toString());
      return new RegExp(regexMatch[1], regexMatch[2]);
    }
    function clone(arg) {
      if (typeof arg !== "object") {
        return arg;
      }
      if (arg === null) {
        return null;
      }
      if (Array.isArray(arg)) {
        return arg.map(clone);
      }
      if (arg instanceof Date) {
        return new Date(arg.getTime());
      }
      if (arg instanceof RegExp) {
        return cloneRegExp(arg);
      }
      const cloned = {};
      for (const name2 in arg) {
        if (Object.prototype.hasOwnProperty.call(arg, name2)) {
          cloned[name2] = clone(arg[name2]);
        }
      }
      return cloned;
    }
    class DiffContext extends Context {
      constructor(left, right) {
        super();
        this.left = left;
        this.right = right;
        this.pipe = "diff";
      }
      setResult(result2) {
        if (this.options.cloneDiffValues && typeof result2 === "object") {
          const clone$1 = typeof this.options.cloneDiffValues === "function" ? this.options.cloneDiffValues : clone;
          if (typeof result2[0] === "object") {
            result2[0] = clone$1(result2[0]);
          }
          if (typeof result2[1] === "object") {
            result2[1] = clone$1(result2[1]);
          }
        }
        return super.setResult(result2);
      }
    }
    class PatchContext extends Context {
      constructor(left, delta) {
        super();
        this.left = left;
        this.delta = delta;
        this.pipe = "patch";
      }
    }
    class ReverseContext extends Context {
      constructor(delta) {
        super();
        this.delta = delta;
        this.pipe = "reverse";
      }
    }
    const diffFilter$3 = function trivialMatchesDiffFilter(context) {
      if (context.left === context.right) {
        context.setResult(void 0).exit();
        return;
      }
      if (typeof context.left === "undefined") {
        if (typeof context.right === "function") {
          throw new Error("functions are not supported");
        }
        context.setResult([context.right]).exit();
        return;
      }
      if (typeof context.right === "undefined") {
        context.setResult([context.left, 0, 0]).exit();
        return;
      }
      if (typeof context.left === "function" || typeof context.right === "function") {
        throw new Error("functions are not supported");
      }
      context.leftType = context.left === null ? "null" : typeof context.left;
      context.rightType = context.right === null ? "null" : typeof context.right;
      if (context.leftType !== context.rightType) {
        context.setResult([context.left, context.right]).exit();
        return;
      }
      if (context.leftType === "boolean" || context.leftType === "number") {
        context.setResult([context.left, context.right]).exit();
        return;
      }
      if (context.leftType === "object") {
        context.leftIsArray = Array.isArray(context.left);
      }
      if (context.rightType === "object") {
        context.rightIsArray = Array.isArray(context.right);
      }
      if (context.leftIsArray !== context.rightIsArray) {
        context.setResult([context.left, context.right]).exit();
        return;
      }
      if (context.left instanceof RegExp) {
        if (context.right instanceof RegExp) {
          context.setResult([context.left.toString(), context.right.toString()]).exit();
        } else {
          context.setResult([context.left, context.right]).exit();
        }
      }
    };
    diffFilter$3.filterName = "trivial";
    const patchFilter$3 = function trivialMatchesPatchFilter(context) {
      if (typeof context.delta === "undefined") {
        context.setResult(context.left).exit();
        return;
      }
      context.nested = !Array.isArray(context.delta);
      if (context.nested) {
        return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta.length === 1) {
        context.setResult(nonNestedDelta[0]).exit();
        return;
      }
      if (nonNestedDelta.length === 2) {
        if (context.left instanceof RegExp) {
          const regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(nonNestedDelta[1]);
          if (regexArgs) {
            context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
            return;
          }
        }
        context.setResult(nonNestedDelta[1]).exit();
        return;
      }
      if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
        context.setResult(void 0).exit();
      }
    };
    patchFilter$3.filterName = "trivial";
    const reverseFilter$3 = function trivialReferseFilter(context) {
      if (typeof context.delta === "undefined") {
        context.setResult(context.delta).exit();
        return;
      }
      context.nested = !Array.isArray(context.delta);
      if (context.nested) {
        return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta.length === 1) {
        context.setResult([nonNestedDelta[0], 0, 0]).exit();
        return;
      }
      if (nonNestedDelta.length === 2) {
        context.setResult([nonNestedDelta[1], nonNestedDelta[0]]).exit();
        return;
      }
      if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
        context.setResult([nonNestedDelta[0]]).exit();
      }
    };
    reverseFilter$3.filterName = "trivial";
    const collectChildrenDiffFilter = (context) => {
      if (!context || !context.children) {
        return;
      }
      const length = context.children.length;
      let child;
      let result2 = context.result;
      for (let index2 = 0; index2 < length; index2++) {
        child = context.children[index2];
        if (typeof child.result === "undefined") {
          continue;
        }
        result2 = result2 || {};
        result2[child.childName] = child.result;
      }
      if (result2 && context.leftIsArray) {
        result2._t = "a";
      }
      context.setResult(result2).exit();
    };
    collectChildrenDiffFilter.filterName = "collectChildren";
    const objectsDiffFilter = (context) => {
      if (context.leftIsArray || context.leftType !== "object") {
        return;
      }
      const left = context.left;
      const right = context.right;
      let name2;
      let child;
      const propertyFilter = context.options.propertyFilter;
      for (name2 in left) {
        if (!Object.prototype.hasOwnProperty.call(left, name2)) {
          continue;
        }
        if (propertyFilter && !propertyFilter(name2, context)) {
          continue;
        }
        child = new DiffContext(left[name2], right[name2]);
        context.push(child, name2);
      }
      for (name2 in right) {
        if (!Object.prototype.hasOwnProperty.call(right, name2)) {
          continue;
        }
        if (propertyFilter && !propertyFilter(name2, context)) {
          continue;
        }
        if (typeof left[name2] === "undefined") {
          child = new DiffContext(void 0, right[name2]);
          context.push(child, name2);
        }
      }
      if (!context.children || context.children.length === 0) {
        context.setResult(void 0).exit();
        return;
      }
      context.exit();
    };
    objectsDiffFilter.filterName = "objects";
    const patchFilter$2 = function nestedPatchFilter(context) {
      if (!context.nested) {
        return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t) {
        return;
      }
      const objectDelta = nestedDelta;
      let name2;
      let child;
      for (name2 in objectDelta) {
        child = new PatchContext(context.left[name2], objectDelta[name2]);
        context.push(child, name2);
      }
      context.exit();
    };
    patchFilter$2.filterName = "objects";
    const collectChildrenPatchFilter$1 = function collectChildrenPatchFilter2(context) {
      if (!context || !context.children) {
        return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t) {
        return;
      }
      const object = context.left;
      const length = context.children.length;
      let child;
      for (let index2 = 0; index2 < length; index2++) {
        child = context.children[index2];
        const property = child.childName;
        if (Object.prototype.hasOwnProperty.call(context.left, property) && child.result === void 0) {
          delete object[property];
        } else if (object[property] !== child.result) {
          object[property] = child.result;
        }
      }
      context.setResult(object).exit();
    };
    collectChildrenPatchFilter$1.filterName = "collectChildren";
    const reverseFilter$2 = function nestedReverseFilter(context) {
      if (!context.nested) {
        return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t) {
        return;
      }
      const objectDelta = context.delta;
      let name2;
      let child;
      for (name2 in objectDelta) {
        child = new ReverseContext(objectDelta[name2]);
        context.push(child, name2);
      }
      context.exit();
    };
    reverseFilter$2.filterName = "objects";
    const collectChildrenReverseFilter$1 = (context) => {
      if (!context || !context.children) {
        return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t) {
        return;
      }
      const length = context.children.length;
      let child;
      const delta = {};
      for (let index2 = 0; index2 < length; index2++) {
        child = context.children[index2];
        const property = child.childName;
        if (delta[property] !== child.result) {
          delta[property] = child.result;
        }
      }
      context.setResult(delta).exit();
    };
    collectChildrenReverseFilter$1.filterName = "collectChildren";
    const defaultMatch = function(array1, array2, index1, index2) {
      return array1[index1] === array2[index2];
    };
    const lengthMatrix = function(array1, array2, match, context) {
      const len1 = array1.length;
      const len2 = array2.length;
      let x2, y;
      const matrix = new Array(len1 + 1);
      for (x2 = 0; x2 < len1 + 1; x2++) {
        matrix[x2] = new Array(len2 + 1);
        for (y = 0; y < len2 + 1; y++) {
          matrix[x2][y] = 0;
        }
      }
      matrix.match = match;
      for (x2 = 1; x2 < len1 + 1; x2++) {
        for (y = 1; y < len2 + 1; y++) {
          if (match(array1, array2, x2 - 1, y - 1, context)) {
            matrix[x2][y] = matrix[x2 - 1][y - 1] + 1;
          } else {
            matrix[x2][y] = Math.max(matrix[x2 - 1][y], matrix[x2][y - 1]);
          }
        }
      }
      return matrix;
    };
    const backtrack = function(matrix, array1, array2, context) {
      let index1 = array1.length;
      let index2 = array2.length;
      const subsequence = {
        sequence: [],
        indices1: [],
        indices2: []
      };
      while (index1 !== 0 && index2 !== 0) {
        const sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);
        if (sameLetter) {
          subsequence.sequence.unshift(array1[index1 - 1]);
          subsequence.indices1.unshift(index1 - 1);
          subsequence.indices2.unshift(index2 - 1);
          --index1;
          --index2;
        } else {
          const valueAtMatrixAbove = matrix[index1][index2 - 1];
          const valueAtMatrixLeft = matrix[index1 - 1][index2];
          if (valueAtMatrixAbove > valueAtMatrixLeft) {
            --index2;
          } else {
            --index1;
          }
        }
      }
      return subsequence;
    };
    const get = function(array1, array2, match, context) {
      const innerContext = context || {};
      const matrix = lengthMatrix(array1, array2, match || defaultMatch, innerContext);
      return backtrack(matrix, array1, array2, innerContext);
    };
    const lcs = {
      get
    };
    const ARRAY_MOVE = 3;
    function arraysHaveMatchByRef(array1, array2, len1, len2) {
      for (let index1 = 0; index1 < len1; index1++) {
        const val1 = array1[index1];
        for (let index2 = 0; index2 < len2; index2++) {
          const val2 = array2[index2];
          if (index1 !== index2 && val1 === val2) {
            return true;
          }
        }
      }
    }
    function matchItems(array1, array2, index1, index2, context) {
      const value1 = array1[index1];
      const value2 = array2[index2];
      if (value1 === value2) {
        return true;
      }
      if (typeof value1 !== "object" || typeof value2 !== "object") {
        return false;
      }
      const objectHash = context.objectHash;
      if (!objectHash) {
        return context.matchByPosition && index1 === index2;
      }
      context.hashCache1 = context.hashCache1 || [];
      let hash1 = context.hashCache1[index1];
      if (typeof hash1 === "undefined") {
        context.hashCache1[index1] = hash1 = objectHash(value1, index1);
      }
      if (typeof hash1 === "undefined") {
        return false;
      }
      context.hashCache2 = context.hashCache2 || [];
      let hash2 = context.hashCache2[index2];
      if (typeof hash2 === "undefined") {
        context.hashCache2[index2] = hash2 = objectHash(value2, index2);
      }
      if (typeof hash2 === "undefined") {
        return false;
      }
      return hash1 === hash2;
    }
    const diffFilter$2 = function arraysDiffFilter(context) {
      if (!context.leftIsArray) {
        return;
      }
      const matchContext = {
        objectHash: context.options && context.options.objectHash,
        matchByPosition: context.options && context.options.matchByPosition
      };
      let commonHead = 0;
      let commonTail = 0;
      let index2;
      let index1;
      let index22;
      const array1 = context.left;
      const array2 = context.right;
      const len1 = array1.length;
      const len2 = array2.length;
      let child;
      if (len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== "boolean") {
        matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
      }
      while (commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext)) {
        index2 = commonHead;
        child = new DiffContext(array1[index2], array2[index2]);
        context.push(child, index2);
        commonHead++;
      }
      while (commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
        index1 = len1 - 1 - commonTail;
        index22 = len2 - 1 - commonTail;
        child = new DiffContext(array1[index1], array2[index22]);
        context.push(child, index22);
        commonTail++;
      }
      let result2;
      if (commonHead + commonTail === len1) {
        if (len1 === len2) {
          context.setResult(void 0).exit();
          return;
        }
        result2 = result2 || {
          _t: "a"
        };
        for (index2 = commonHead; index2 < len2 - commonTail; index2++) {
          result2[index2] = [array2[index2]];
        }
        context.setResult(result2).exit();
        return;
      }
      if (commonHead + commonTail === len2) {
        result2 = result2 || {
          _t: "a"
        };
        for (index2 = commonHead; index2 < len1 - commonTail; index2++) {
          result2[`_${index2}`] = [array1[index2], 0, 0];
        }
        context.setResult(result2).exit();
        return;
      }
      delete matchContext.hashCache1;
      delete matchContext.hashCache2;
      const trimmed1 = array1.slice(commonHead, len1 - commonTail);
      const trimmed2 = array2.slice(commonHead, len2 - commonTail);
      const seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);
      const removedItems = [];
      result2 = result2 || {
        _t: "a"
      };
      for (index2 = commonHead; index2 < len1 - commonTail; index2++) {
        if (seq.indices1.indexOf(index2 - commonHead) < 0) {
          result2[`_${index2}`] = [array1[index2], 0, 0];
          removedItems.push(index2);
        }
      }
      let detectMove = true;
      if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {
        detectMove = false;
      }
      let includeValueOnMove = false;
      if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {
        includeValueOnMove = true;
      }
      const removedItemsLength = removedItems.length;
      for (index2 = commonHead; index2 < len2 - commonTail; index2++) {
        const indexOnArray2 = seq.indices2.indexOf(index2 - commonHead);
        if (indexOnArray2 < 0) {
          let isMove = false;
          if (detectMove && removedItemsLength > 0) {
            for (let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
              index1 = removedItems[removeItemIndex1];
              if (matchItems(trimmed1, trimmed2, index1 - commonHead, index2 - commonHead, matchContext)) {
                result2[`_${index1}`].splice(1, 2, index2, ARRAY_MOVE);
                if (!includeValueOnMove) {
                  result2[`_${index1}`][0] = "";
                }
                index22 = index2;
                child = new DiffContext(array1[index1], array2[index22]);
                context.push(child, index22);
                removedItems.splice(removeItemIndex1, 1);
                isMove = true;
                break;
              }
            }
          }
          if (!isMove) {
            result2[index2] = [array2[index2]];
          }
        } else {
          index1 = seq.indices1[indexOnArray2] + commonHead;
          index22 = seq.indices2[indexOnArray2] + commonHead;
          child = new DiffContext(array1[index1], array2[index22]);
          context.push(child, index22);
        }
      }
      context.setResult(result2).exit();
    };
    diffFilter$2.filterName = "arrays";
    const compare = {
      numerically(a, b) {
        return a - b;
      },
      numericallyBy(name2) {
        return (a, b) => a[name2] - b[name2];
      }
    };
    const patchFilter$1 = function nestedPatchFilter(context) {
      if (!context.nested) {
        return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t !== "a") {
        return;
      }
      let index2;
      let index1;
      const delta = nestedDelta;
      const array = context.left;
      let toRemove = [];
      let toInsert = [];
      const toModify = [];
      for (index2 in delta) {
        if (index2 !== "_t") {
          if (index2[0] === "_") {
            const removedOrMovedIndex = index2;
            if (delta[removedOrMovedIndex][2] === 0 || delta[removedOrMovedIndex][2] === ARRAY_MOVE) {
              toRemove.push(parseInt(index2.slice(1), 10));
            } else {
              throw new Error(`only removal or move can be applied at original array indices, invalid diff type: ${delta[removedOrMovedIndex][2]}`);
            }
          } else {
            const numberIndex = index2;
            if (delta[numberIndex].length === 1) {
              toInsert.push({
                index: parseInt(numberIndex, 10),
                value: delta[numberIndex][0]
              });
            } else {
              toModify.push({
                index: parseInt(numberIndex, 10),
                delta: delta[numberIndex]
              });
            }
          }
        }
      }
      toRemove = toRemove.sort(compare.numerically);
      for (index2 = toRemove.length - 1; index2 >= 0; index2--) {
        index1 = toRemove[index2];
        const indexDiff = delta[`_${index1}`];
        const removedValue = array.splice(index1, 1)[0];
        if (indexDiff[2] === ARRAY_MOVE) {
          toInsert.push({
            index: indexDiff[1],
            value: removedValue
          });
        }
      }
      toInsert = toInsert.sort(compare.numericallyBy("index"));
      const toInsertLength = toInsert.length;
      for (index2 = 0; index2 < toInsertLength; index2++) {
        const insertion = toInsert[index2];
        array.splice(insertion.index, 0, insertion.value);
      }
      const toModifyLength = toModify.length;
      let child;
      if (toModifyLength > 0) {
        for (index2 = 0; index2 < toModifyLength; index2++) {
          const modification = toModify[index2];
          child = new PatchContext(array[modification.index], modification.delta);
          context.push(child, modification.index);
        }
      }
      if (!context.children) {
        context.setResult(array).exit();
        return;
      }
      context.exit();
    };
    patchFilter$1.filterName = "arrays";
    const collectChildrenPatchFilter = function collectChildrenPatchFilter2(context) {
      if (!context || !context.children) {
        return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t !== "a") {
        return;
      }
      const array = context.left;
      const length = context.children.length;
      let child;
      for (let index2 = 0; index2 < length; index2++) {
        child = context.children[index2];
        const arrayIndex = child.childName;
        array[arrayIndex] = child.result;
      }
      context.setResult(array).exit();
    };
    collectChildrenPatchFilter.filterName = "arraysCollectChildren";
    const reverseFilter$1 = function arraysReverseFilter(context) {
      if (!context.nested) {
        const nonNestedDelta = context.delta;
        if (nonNestedDelta[2] === ARRAY_MOVE) {
          const arrayMoveDelta = nonNestedDelta;
          context.newName = `_${arrayMoveDelta[1]}`;
          context.setResult([
            arrayMoveDelta[0],
            parseInt(context.childName.substring(1), 10),
            ARRAY_MOVE
          ]).exit();
        }
        return;
      }
      const nestedDelta = context.delta;
      if (nestedDelta._t !== "a") {
        return;
      }
      const arrayDelta = nestedDelta;
      let name2;
      let child;
      for (name2 in arrayDelta) {
        if (name2 === "_t") {
          continue;
        }
        child = new ReverseContext(arrayDelta[name2]);
        context.push(child, name2);
      }
      context.exit();
    };
    reverseFilter$1.filterName = "arrays";
    const reverseArrayDeltaIndex = (delta, index2, itemDelta) => {
      if (typeof index2 === "string" && index2[0] === "_") {
        return parseInt(index2.substring(1), 10);
      } else if (Array.isArray(itemDelta) && itemDelta[2] === 0) {
        return `_${index2}`;
      }
      let reverseIndex = +index2;
      for (const deltaIndex in delta) {
        const deltaItem = delta[deltaIndex];
        if (Array.isArray(deltaItem)) {
          if (deltaItem[2] === ARRAY_MOVE) {
            const moveFromIndex = parseInt(deltaIndex.substring(1), 10);
            const moveToIndex = deltaItem[1];
            if (moveToIndex === +index2) {
              return moveFromIndex;
            }
            if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
              reverseIndex++;
            } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {
              reverseIndex--;
            }
          } else if (deltaItem[2] === 0) {
            const deleteIndex = parseInt(deltaIndex.substring(1), 10);
            if (deleteIndex <= reverseIndex) {
              reverseIndex++;
            }
          } else if (deltaItem.length === 1 && parseInt(deltaIndex, 10) <= reverseIndex) {
            reverseIndex--;
          }
        }
      }
      return reverseIndex;
    };
    const collectChildrenReverseFilter = (context) => {
      if (!context || !context.children) {
        return;
      }
      const deltaWithChildren = context.delta;
      if (deltaWithChildren._t !== "a") {
        return;
      }
      const arrayDelta = deltaWithChildren;
      const length = context.children.length;
      let child;
      const delta = {
        _t: "a"
      };
      for (let index2 = 0; index2 < length; index2++) {
        child = context.children[index2];
        let name2 = child.newName;
        if (typeof name2 === "undefined") {
          name2 = reverseArrayDeltaIndex(arrayDelta, child.childName, child.result);
        }
        if (delta[name2] !== child.result) {
          delta[name2] = child.result;
        }
      }
      context.setResult(delta).exit();
    };
    collectChildrenReverseFilter.filterName = "arraysCollectChildren";
    const diffFilter$1 = function datesDiffFilter(context) {
      if (context.left instanceof Date) {
        if (context.right instanceof Date) {
          if (context.left.getTime() !== context.right.getTime()) {
            context.setResult([context.left, context.right]);
          } else {
            context.setResult(void 0);
          }
        } else {
          context.setResult([context.left, context.right]);
        }
        context.exit();
      } else if (context.right instanceof Date) {
        context.setResult([context.left, context.right]).exit();
      }
    };
    diffFilter$1.filterName = "dates";
    const TEXT_DIFF = 2;
    const DEFAULT_MIN_LENGTH = 60;
    let cachedDiffPatch = null;
    function getDiffMatchPatch(options2, required) {
      var _a2;
      if (!cachedDiffPatch) {
        let instance;
        if ((_a2 = options2 === null || options2 === void 0 ? void 0 : options2.textDiff) === null || _a2 === void 0 ? void 0 : _a2.diffMatchPatch) {
          instance = new options2.textDiff.diffMatchPatch();
        } else {
          if (!required) {
            return null;
          }
          const error2 = new Error("The diff-match-patch library was not provided. Pass the library in through the options or use the `jsondiffpatch/with-text-diffs` entry-point.");
          error2.diff_match_patch_not_found = true;
          throw error2;
        }
        cachedDiffPatch = {
          diff: function(txt1, txt2) {
            return instance.patch_toText(instance.patch_make(txt1, txt2));
          },
          patch: function(txt1, patch) {
            const results = instance.patch_apply(instance.patch_fromText(patch), txt1);
            for (let i2 = 0; i2 < results[1].length; i2++) {
              if (!results[1][i2]) {
                const error2 = new Error("text patch failed");
                error2.textPatchFailed = true;
              }
            }
            return results[0];
          }
        };
      }
      return cachedDiffPatch;
    }
    const diffFilter = function textsDiffFilter(context) {
      if (context.leftType !== "string") {
        return;
      }
      const left = context.left;
      const right = context.right;
      const minLength = context.options && context.options.textDiff && context.options.textDiff.minLength || DEFAULT_MIN_LENGTH;
      if (left.length < minLength || right.length < minLength) {
        context.setResult([left, right]).exit();
        return;
      }
      const diffMatchPatch = getDiffMatchPatch(context.options);
      if (!diffMatchPatch) {
        context.setResult([left, right]).exit();
        return;
      }
      const diff2 = diffMatchPatch.diff;
      context.setResult([diff2(left, right), 0, TEXT_DIFF]).exit();
    };
    diffFilter.filterName = "texts";
    const patchFilter = function textsPatchFilter(context) {
      if (context.nested) {
        return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta[2] !== TEXT_DIFF) {
        return;
      }
      const textDiffDelta = nonNestedDelta;
      const patch = getDiffMatchPatch(context.options, true).patch;
      context.setResult(patch(context.left, textDiffDelta[0])).exit();
    };
    patchFilter.filterName = "texts";
    const textDeltaReverse = function(delta) {
      let i2;
      let l;
      let line2;
      let lineTmp;
      let header2 = null;
      const headerRegex = /^@@ +-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;
      let lineHeader;
      const lines = delta.split("\n");
      for (i2 = 0, l = lines.length; i2 < l; i2++) {
        line2 = lines[i2];
        const lineStart = line2.slice(0, 1);
        if (lineStart === "@") {
          header2 = headerRegex.exec(line2);
          lineHeader = i2;
          lines[lineHeader] = "@@ -" + header2[3] + "," + header2[4] + " +" + header2[1] + "," + header2[2] + " @@";
        } else if (lineStart === "+") {
          lines[i2] = "-" + lines[i2].slice(1);
          if (lines[i2 - 1].slice(0, 1) === "+") {
            lineTmp = lines[i2];
            lines[i2] = lines[i2 - 1];
            lines[i2 - 1] = lineTmp;
          }
        } else if (lineStart === "-") {
          lines[i2] = "+" + lines[i2].slice(1);
        }
      }
      return lines.join("\n");
    };
    const reverseFilter = function textsReverseFilter(context) {
      if (context.nested) {
        return;
      }
      const nonNestedDelta = context.delta;
      if (nonNestedDelta[2] !== TEXT_DIFF) {
        return;
      }
      const textDiffDelta = nonNestedDelta;
      context.setResult([textDeltaReverse(textDiffDelta[0]), 0, TEXT_DIFF]).exit();
    };
    reverseFilter.filterName = "texts";
    class DiffPatcher {
      constructor(options2) {
        this.processor = new Processor(options2);
        this.processor.pipe(new Pipe("diff").append(collectChildrenDiffFilter, diffFilter$3, diffFilter$1, diffFilter, objectsDiffFilter, diffFilter$2).shouldHaveResult());
        this.processor.pipe(new Pipe("patch").append(collectChildrenPatchFilter$1, collectChildrenPatchFilter, patchFilter$3, patchFilter, patchFilter$2, patchFilter$1).shouldHaveResult());
        this.processor.pipe(new Pipe("reverse").append(collectChildrenReverseFilter$1, collectChildrenReverseFilter, reverseFilter$3, reverseFilter, reverseFilter$2, reverseFilter$1).shouldHaveResult());
      }
      options(options2) {
        return this.processor.options(options2);
      }
      diff(left, right) {
        return this.processor.process(new DiffContext(left, right));
      }
      patch(left, delta) {
        return this.processor.process(new PatchContext(left, delta));
      }
      reverse(delta) {
        return this.processor.process(new ReverseContext(delta));
      }
      unpatch(right, delta) {
        return this.patch(right, this.reverse(delta));
      }
      clone(value2) {
        return clone(value2);
      }
    }
    let defaultInstance$1;
    function diff$1(left, right) {
      if (!defaultInstance$1) {
        defaultInstance$1 = new DiffPatcher();
      }
      return defaultInstance$1.diff(left, right);
    }
    const trimUnderscore = (str2) => {
      if (str2.substring(0, 1) === "_") {
        return str2.slice(1);
      }
      return str2;
    };
    const arrayKeyToSortNumber = (key2) => {
      if (key2 === "_t") {
        return -1;
      } else {
        if (key2.substring(0, 1) === "_") {
          return parseInt(key2.slice(1), 10);
        } else {
          return parseInt(key2, 10) + 0.1;
        }
      }
    };
    const arrayKeyComparer = (key1, key2) => arrayKeyToSortNumber(key1) - arrayKeyToSortNumber(key2);
    class BaseFormatter {
      format(delta, left) {
        const context = {};
        this.prepareContext(context);
        const preparedContext = context;
        this.recurse(preparedContext, delta, left);
        return this.finalize(preparedContext);
      }
      prepareContext(context) {
        context.buffer = [];
        context.out = function(...args) {
          this.buffer.push(...args);
        };
      }
      typeFormattterNotFound(context, deltaType) {
        throw new Error(`cannot format delta type: ${deltaType}`);
      }
      /* eslint-disable @typescript-eslint/no-unused-vars */
      typeFormattterErrorFormatter(context, err2, delta, leftValue, key2, leftKey, movedFrom) {
      }
      /* eslint-enable @typescript-eslint/no-unused-vars */
      finalize({ buffer: buffer2 }) {
        if (Array.isArray(buffer2)) {
          return buffer2.join("");
        }
      }
      recurse(context, delta, left, key2, leftKey, movedFrom, isLast) {
        const useMoveOriginHere = delta && movedFrom;
        const leftValue = useMoveOriginHere ? movedFrom.value : left;
        if (typeof delta === "undefined" && typeof key2 === "undefined") {
          return void 0;
        }
        const type = this.getDeltaType(delta, movedFrom);
        const nodeType = type === "node" ? delta._t === "a" ? "array" : "object" : "";
        if (typeof key2 !== "undefined") {
          this.nodeBegin(context, key2, leftKey, type, nodeType, isLast);
        } else {
          this.rootBegin(context, type, nodeType);
        }
        let typeFormattter;
        try {
          typeFormattter = type !== "unknown" ? this[`format_${type}`] : this.typeFormattterNotFound(context, type);
          typeFormattter.call(this, context, delta, leftValue, key2, leftKey, movedFrom);
        } catch (err2) {
          this.typeFormattterErrorFormatter(context, err2, delta, leftValue, key2, leftKey, movedFrom);
          if (typeof console !== "undefined" && console.error) {
            console.error(err2.stack);
          }
        }
        if (typeof key2 !== "undefined") {
          this.nodeEnd(context, key2, leftKey, type, nodeType, isLast);
        } else {
          this.rootEnd(context, type, nodeType);
        }
      }
      formatDeltaChildren(context, delta, left) {
        this.forEachDeltaKey(delta, left, (key2, leftKey, movedFrom, isLast) => {
          this.recurse(context, delta[key2], left ? left[leftKey] : void 0, key2, leftKey, movedFrom, isLast);
        });
      }
      forEachDeltaKey(delta, left, fn2) {
        const keys = Object.keys(delta);
        const arrayKeys = delta._t === "a";
        const moveDestinations = {};
        let name2;
        if (typeof left !== "undefined") {
          for (name2 in left) {
            if (Object.prototype.hasOwnProperty.call(left, name2)) {
              if (typeof delta[name2] === "undefined" && (!arrayKeys || typeof delta[`_${name2}`] === "undefined")) {
                keys.push(name2);
              }
            }
          }
        }
        for (name2 in delta) {
          if (Object.prototype.hasOwnProperty.call(delta, name2)) {
            const value2 = delta[name2];
            if (Array.isArray(value2) && value2[2] === 3) {
              const movedDelta = value2;
              moveDestinations[`${movedDelta[1]}`] = {
                key: name2,
                value: left && left[parseInt(name2.substring(1), 10)]
              };
              if (this.includeMoveDestinations !== false) {
                if (typeof left === "undefined" && typeof delta[movedDelta[1]] === "undefined") {
                  keys.push(movedDelta[1].toString());
                }
              }
            }
          }
        }
        if (arrayKeys) {
          keys.sort(arrayKeyComparer);
        } else {
          keys.sort();
        }
        for (let index2 = 0, length = keys.length; index2 < length; index2++) {
          const key2 = keys[index2];
          if (arrayKeys && key2 === "_t") {
            continue;
          }
          const leftKey = arrayKeys ? parseInt(trimUnderscore(key2), 10) : key2;
          const isLast = index2 === length - 1;
          fn2(key2, leftKey, moveDestinations[leftKey], isLast);
        }
      }
      getDeltaType(delta, movedFrom) {
        if (typeof delta === "undefined") {
          if (typeof movedFrom !== "undefined") {
            return "movedestination";
          }
          return "unchanged";
        }
        if (Array.isArray(delta)) {
          if (delta.length === 1) {
            return "added";
          }
          if (delta.length === 2) {
            return "modified";
          }
          if (delta.length === 3 && delta[2] === 0) {
            return "deleted";
          }
          if (delta.length === 3 && delta[2] === 2) {
            return "textdiff";
          }
          if (delta.length === 3 && delta[2] === 3) {
            return "moved";
          }
        } else if (typeof delta === "object") {
          return "node";
        }
        return "unknown";
      }
      parseTextDiff(value2) {
        const output2 = [];
        const lines = value2.split("\n@@ ");
        for (let i2 = 0, l = lines.length; i2 < l; i2++) {
          const line2 = lines[i2];
          const lineOutput = {
            pieces: []
          };
          const location = /^(?:@@ )?[-+]?(\d+),(\d+)/.exec(line2).slice(1);
          lineOutput.location = {
            line: location[0],
            chr: location[1]
          };
          const pieces = line2.split("\n").slice(1);
          for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
            const piece = pieces[pieceIndex];
            if (!piece.length) {
              continue;
            }
            const pieceOutput = {
              type: "context"
            };
            if (piece.substring(0, 1) === "+") {
              pieceOutput.type = "added";
            } else if (piece.substring(0, 1) === "-") {
              pieceOutput.type = "deleted";
            }
            pieceOutput.text = piece.slice(1);
            lineOutput.pieces.push(pieceOutput);
          }
          output2.push(lineOutput);
        }
        return output2;
      }
    }
    class HtmlFormatter extends BaseFormatter {
      typeFormattterErrorFormatter(context, err2) {
        context.out(`<pre class="jsondiffpatch-error">${err2}</pre>`);
      }
      formatValue(context, value2) {
        context.out(`<pre>${htmlEscape(JSON.stringify(value2, null, 2))}</pre>`);
      }
      formatTextDiffString(context, value2) {
        const lines = this.parseTextDiff(value2);
        context.out('<ul class="jsondiffpatch-textdiff">');
        for (let i2 = 0, l = lines.length; i2 < l; i2++) {
          const line2 = lines[i2];
          context.out(`<li><div class="jsondiffpatch-textdiff-location"><span class="jsondiffpatch-textdiff-line-number">${line2.location.line}</span><span class="jsondiffpatch-textdiff-char">${line2.location.chr}</span></div><div class="jsondiffpatch-textdiff-line">`);
          const pieces = line2.pieces;
          for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
            const piece = pieces[pieceIndex];
            context.out(`<span class="jsondiffpatch-textdiff-${piece.type}">${htmlEscape(decodeURI(piece.text))}</span>`);
          }
          context.out("</div></li>");
        }
        context.out("</ul>");
      }
      rootBegin(context, type, nodeType) {
        const nodeClass = `jsondiffpatch-${type}${nodeType ? ` jsondiffpatch-child-node-type-${nodeType}` : ""}`;
        context.out(`<div class="jsondiffpatch-delta ${nodeClass}">`);
      }
      rootEnd(context) {
        context.out(`</div>${context.hasArrows ? `<script type="text/javascript">setTimeout(${adjustArrows.toString()},10);<\/script>` : ""}`);
      }
      nodeBegin(context, key2, leftKey, type, nodeType) {
        const nodeClass = `jsondiffpatch-${type}${nodeType ? ` jsondiffpatch-child-node-type-${nodeType}` : ""}`;
        context.out(`<li class="${nodeClass}" data-key="${leftKey}"><div class="jsondiffpatch-property-name">${leftKey}</div>`);
      }
      nodeEnd(context) {
        context.out("</li>");
      }
      format_unchanged(context, delta, left) {
        if (typeof left === "undefined") {
          return;
        }
        context.out('<div class="jsondiffpatch-value">');
        this.formatValue(context, left);
        context.out("</div>");
      }
      format_movedestination(context, delta, left) {
        if (typeof left === "undefined") {
          return;
        }
        context.out('<div class="jsondiffpatch-value">');
        this.formatValue(context, left);
        context.out("</div>");
      }
      format_node(context, delta, left) {
        const nodeType = delta._t === "a" ? "array" : "object";
        context.out(`<ul class="jsondiffpatch-node jsondiffpatch-node-type-${nodeType}">`);
        this.formatDeltaChildren(context, delta, left);
        context.out("</ul>");
      }
      format_added(context, delta) {
        context.out('<div class="jsondiffpatch-value">');
        this.formatValue(context, delta[0]);
        context.out("</div>");
      }
      format_modified(context, delta) {
        context.out('<div class="jsondiffpatch-value jsondiffpatch-left-value">');
        this.formatValue(context, delta[0]);
        context.out('</div><div class="jsondiffpatch-value jsondiffpatch-right-value">');
        this.formatValue(context, delta[1]);
        context.out("</div>");
      }
      format_deleted(context, delta) {
        context.out('<div class="jsondiffpatch-value">');
        this.formatValue(context, delta[0]);
        context.out("</div>");
      }
      format_moved(context, delta) {
        context.out('<div class="jsondiffpatch-value">');
        this.formatValue(context, delta[0]);
        context.out(`</div><div class="jsondiffpatch-moved-destination">${delta[1]}</div>`);
        context.out(
          /* jshint multistr: true */
          `<div class="jsondiffpatch-arrow" style="position: relative; left: -34px;">
          <svg width="30" height="60" style="position: absolute; display: none;">
          <defs>
              <marker id="markerArrow" markerWidth="8" markerHeight="8"
                 refx="2" refy="4"
                     orient="auto" markerUnits="userSpaceOnUse">
                  <path d="M1,1 L1,7 L7,4 L1,1" style="fill: #339;" />
              </marker>
          </defs>
          <path d="M30,0 Q-10,25 26,50"
            style="stroke: #88f; stroke-width: 2px; fill: none; stroke-opacity: 0.5; marker-end: url(#markerArrow);"
          ></path>
          </svg>
      </div>`
        );
        context.hasArrows = true;
      }
      format_textdiff(context, delta) {
        context.out('<div class="jsondiffpatch-value">');
        this.formatTextDiffString(context, delta[0]);
        context.out("</div>");
      }
    }
    function htmlEscape(text2) {
      let html = text2;
      const replacements = [
        [/&/g, "&amp;"],
        [/</g, "&lt;"],
        [/>/g, "&gt;"],
        [/'/g, "&apos;"],
        [/"/g, "&quot;"]
      ];
      for (let i2 = 0; i2 < replacements.length; i2++) {
        html = html.replace(replacements[i2][0], replacements[i2][1]);
      }
      return html;
    }
    const adjustArrows = function jsondiffpatchHtmlFormatterAdjustArrows(nodeArg) {
      const node2 = nodeArg || document;
      const getElementText = ({ textContent, innerText }) => textContent || innerText;
      const eachByQuery = (el, query2, fn2) => {
        const elems = el.querySelectorAll(query2);
        for (let i2 = 0, l = elems.length; i2 < l; i2++) {
          fn2(elems[i2]);
        }
      };
      const eachChildren = ({ children: children2 }, fn2) => {
        for (let i2 = 0, l = children2.length; i2 < l; i2++) {
          fn2(children2[i2], i2);
        }
      };
      eachByQuery(node2, ".jsondiffpatch-arrow", ({ parentNode, children: children2, style: style2 }) => {
        const arrowParent = parentNode;
        const svg2 = children2[0];
        const path = svg2.children[1];
        svg2.style.display = "none";
        const destination = getElementText(arrowParent.querySelector(".jsondiffpatch-moved-destination"));
        const container2 = arrowParent.parentNode;
        let destinationElem;
        eachChildren(container2, (child) => {
          if (child.getAttribute("data-key") === destination) {
            destinationElem = child;
          }
        });
        if (!destinationElem) {
          return;
        }
        try {
          const distance = destinationElem.offsetTop - arrowParent.offsetTop;
          svg2.setAttribute("height", `${Math.abs(distance) + 6}`);
          style2.top = `${-8 + (distance > 0 ? 0 : distance)}px`;
          const curve = distance > 0 ? `M30,0 Q-10,${Math.round(distance / 2)} 26,${distance - 4}` : `M30,${-distance} Q-10,${Math.round(-distance / 2)} 26,4`;
          path.setAttribute("d", curve);
          svg2.style.display = "";
        } catch (err2) {
        }
      });
    };
    let defaultInstance;
    function format(delta, left) {
      if (!defaultInstance) {
        defaultInstance = new HtmlFormatter();
      }
      return defaultInstance.format(delta, left);
    }
    const StateDiffView = ({
      before,
      after,
      className: className2
    }) => {
      const state_diff = diff$1(sanitizeKeys(before), sanitizeKeys(after));
      const html_result = format(state_diff) || "Unable to render differences";
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          dangerouslySetInnerHTML: { __html: unescapeNewlines(html_result) },
          className: clsx(className2)
        }
      );
    };
    function unescapeNewlines(obj) {
      if (typeof obj === "string") {
        return obj.replace(/\\n/g, "\n");
      }
      if (obj === null || typeof obj !== "object") {
        return obj;
      }
      if (Array.isArray(obj)) {
        return obj.map((item2) => unescapeNewlines(item2));
      }
      return Object.fromEntries(
        Object.entries(obj).map(([key2, value2]) => [
          key2,
          unescapeNewlines(value2)
        ])
      );
    }
    function sanitizeKeys(obj) {
      if (typeof obj !== "object" || obj === null) {
        return obj;
      }
      if (Array.isArray(obj)) {
        return obj.map((item2) => sanitizeKeys(item2));
      }
      return Object.fromEntries(
        Object.entries(obj).map(([key2, value2]) => [
          key2.replace(/</g, "&lt;").replace(/>/g, "&gt;"),
          sanitizeKeys(value2)
        ])
      );
    }
    function parseNpt(time) {
      if (typeof time === "number") {
        return time;
      } else if (typeof time === "string") {
        return time.split(":").reverse().map(parseFloat).reduce((sum, n, i2) => sum + n * Math.pow(60, i2));
      } else {
        return void 0;
      }
    }
    function debounce(f, delay) {
      let timeout;
      return function() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        clearTimeout(timeout);
        timeout = setTimeout(() => f.apply(this, args), delay);
      };
    }
    function throttle(f, interval) {
      let enableCall = true;
      return function() {
        if (!enableCall) return;
        enableCall = false;
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
        f.apply(this, args);
        setTimeout(() => enableCall = true, interval);
      };
    }
    class DummyLogger {
      log() {
      }
      debug() {
      }
      info() {
      }
      warn() {
      }
      error() {
      }
    }
    class PrefixedLogger {
      constructor(logger, prefix2) {
        this.logger = logger;
        this.prefix = prefix2;
      }
      log(message2) {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }
        this.logger.log(`${this.prefix}${message2}`, ...args);
      }
      debug(message2) {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }
        this.logger.debug(`${this.prefix}${message2}`, ...args);
      }
      info(message2) {
        for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
          args[_key3 - 1] = arguments[_key3];
        }
        this.logger.info(`${this.prefix}${message2}`, ...args);
      }
      warn(message2) {
        for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
          args[_key4 - 1] = arguments[_key4];
        }
        this.logger.warn(`${this.prefix}${message2}`, ...args);
      }
      error(message2) {
        for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
          args[_key5 - 1] = arguments[_key5];
        }
        this.logger.error(`${this.prefix}${message2}`, ...args);
      }
    }
    let wasm;
    const heap = new Array(128).fill(void 0);
    heap.push(void 0, null, true, false);
    function getObject(idx) {
      return heap[idx];
    }
    let heap_next = heap.length;
    function dropObject(idx) {
      if (idx < 132) return;
      heap[idx] = heap_next;
      heap_next = idx;
    }
    function takeObject(idx) {
      const ret = getObject(idx);
      dropObject(idx);
      return ret;
    }
    const cachedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", {
      ignoreBOM: true,
      fatal: true
    }) : {
      decode: () => {
        throw Error("TextDecoder not available");
      }
    };
    if (typeof TextDecoder !== "undefined") {
      cachedTextDecoder.decode();
    }
    let cachedUint8Memory0 = null;
    function getUint8Memory0() {
      if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) {
        cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer);
      }
      return cachedUint8Memory0;
    }
    function getStringFromWasm0(ptr, len) {
      ptr = ptr >>> 0;
      return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
    }
    function addHeapObject(obj) {
      if (heap_next === heap.length) heap.push(heap.length + 1);
      const idx = heap_next;
      heap_next = heap[idx];
      heap[idx] = obj;
      return idx;
    }
    function debugString(val) {
      const type = typeof val;
      if (type == "number" || type == "boolean" || val == null) {
        return `${val}`;
      }
      if (type == "string") {
        return `"${val}"`;
      }
      if (type == "symbol") {
        const description = val.description;
        if (description == null) {
          return "Symbol";
        } else {
          return `Symbol(${description})`;
        }
      }
      if (type == "function") {
        const name2 = val.name;
        if (typeof name2 == "string" && name2.length > 0) {
          return `Function(${name2})`;
        } else {
          return "Function";
        }
      }
      if (Array.isArray(val)) {
        const length = val.length;
        let debug = "[";
        if (length > 0) {
          debug += debugString(val[0]);
        }
        for (let i2 = 1; i2 < length; i2++) {
          debug += ", " + debugString(val[i2]);
        }
        debug += "]";
        return debug;
      }
      const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
      let className2;
      if (builtInMatches.length > 1) {
        className2 = builtInMatches[1];
      } else {
        return toString.call(val);
      }
      if (className2 == "Object") {
        try {
          return "Object(" + JSON.stringify(val) + ")";
        } catch (_) {
          return "Object";
        }
      }
      if (val instanceof Error) {
        return `${val.name}: ${val.message}
${val.stack}`;
      }
      return className2;
    }
    let WASM_VECTOR_LEN = 0;
    const cachedTextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : {
      encode: () => {
        throw Error("TextEncoder not available");
      }
    };
    const encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
      return cachedTextEncoder.encodeInto(arg, view);
    } : function(arg, view) {
      const buf = cachedTextEncoder.encode(arg);
      view.set(buf);
      return {
        read: arg.length,
        written: buf.length
      };
    };
    function passStringToWasm0(arg, malloc, realloc) {
      if (realloc === void 0) {
        const buf = cachedTextEncoder.encode(arg);
        const ptr2 = malloc(buf.length, 1) >>> 0;
        getUint8Memory0().subarray(ptr2, ptr2 + buf.length).set(buf);
        WASM_VECTOR_LEN = buf.length;
        return ptr2;
      }
      let len = arg.length;
      let ptr = malloc(len, 1) >>> 0;
      const mem = getUint8Memory0();
      let offset = 0;
      for (; offset < len; offset++) {
        const code2 = arg.charCodeAt(offset);
        if (code2 > 127) break;
        mem[ptr + offset] = code2;
      }
      if (offset !== len) {
        if (offset !== 0) {
          arg = arg.slice(offset);
        }
        ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
        const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
        const ret = encodeString(arg, view);
        offset += ret.written;
        ptr = realloc(ptr, len, offset, 1) >>> 0;
      }
      WASM_VECTOR_LEN = offset;
      return ptr;
    }
    let cachedInt32Memory0 = null;
    function getInt32Memory0() {
      if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) {
        cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
      }
      return cachedInt32Memory0;
    }
    function create$1(cols, rows, scrollback_limit) {
      const ret = wasm.create(cols, rows, scrollback_limit);
      return Vt.__wrap(ret);
    }
    let cachedUint32Memory0 = null;
    function getUint32Memory0() {
      if (cachedUint32Memory0 === null || cachedUint32Memory0.byteLength === 0) {
        cachedUint32Memory0 = new Uint32Array(wasm.memory.buffer);
      }
      return cachedUint32Memory0;
    }
    function getArrayU32FromWasm0(ptr, len) {
      ptr = ptr >>> 0;
      return getUint32Memory0().subarray(ptr / 4, ptr / 4 + len);
    }
    const VtFinalization = typeof FinalizationRegistry === "undefined" ? {
      register: () => {
      },
      unregister: () => {
      }
    } : new FinalizationRegistry((ptr) => wasm.__wbg_vt_free(ptr >>> 0));
    class Vt {
      static __wrap(ptr) {
        ptr = ptr >>> 0;
        const obj = Object.create(Vt.prototype);
        obj.__wbg_ptr = ptr;
        VtFinalization.register(obj, obj.__wbg_ptr, obj);
        return obj;
      }
      __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        VtFinalization.unregister(this);
        return ptr;
      }
      free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_vt_free(ptr);
      }
      /**
      * @param {string} s
      * @returns {any}
      */
      feed(s) {
        const ptr0 = passStringToWasm0(s, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.vt_feed(this.__wbg_ptr, ptr0, len0);
        return takeObject(ret);
      }
      /**
      * @param {number} cols
      * @param {number} rows
      * @returns {any}
      */
      resize(cols, rows) {
        const ret = wasm.vt_resize(this.__wbg_ptr, cols, rows);
        return takeObject(ret);
      }
      /**
      * @returns {string}
      */
      inspect() {
        let deferred1_0;
        let deferred1_1;
        try {
          const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
          wasm.vt_inspect(retptr, this.__wbg_ptr);
          var r0 = getInt32Memory0()[retptr / 4 + 0];
          var r1 = getInt32Memory0()[retptr / 4 + 1];
          deferred1_0 = r0;
          deferred1_1 = r1;
          return getStringFromWasm0(r0, r1);
        } finally {
          wasm.__wbindgen_add_to_stack_pointer(16);
          wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
        }
      }
      /**
      * @returns {Uint32Array}
      */
      getSize() {
        try {
          const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
          wasm.vt_getSize(retptr, this.__wbg_ptr);
          var r0 = getInt32Memory0()[retptr / 4 + 0];
          var r1 = getInt32Memory0()[retptr / 4 + 1];
          var v1 = getArrayU32FromWasm0(r0, r1).slice();
          wasm.__wbindgen_free(r0, r1 * 4, 4);
          return v1;
        } finally {
          wasm.__wbindgen_add_to_stack_pointer(16);
        }
      }
      /**
      * @param {number} n
      * @returns {any}
      */
      getLine(n) {
        const ret = wasm.vt_getLine(this.__wbg_ptr, n);
        return takeObject(ret);
      }
      /**
      * @returns {any}
      */
      getCursor() {
        const ret = wasm.vt_getCursor(this.__wbg_ptr);
        return takeObject(ret);
      }
    }
    async function __wbg_load(module2, imports) {
      if (typeof Response === "function" && module2 instanceof Response) {
        if (typeof WebAssembly.instantiateStreaming === "function") {
          try {
            return await WebAssembly.instantiateStreaming(module2, imports);
          } catch (e) {
            if (module2.headers.get("Content-Type") != "application/wasm") {
              console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
            } else {
              throw e;
            }
          }
        }
        const bytes = await module2.arrayBuffer();
        return await WebAssembly.instantiate(bytes, imports);
      } else {
        const instance = await WebAssembly.instantiate(module2, imports);
        if (instance instanceof WebAssembly.Instance) {
          return {
            instance,
            module: module2
          };
        } else {
          return instance;
        }
      }
    }
    function __wbg_get_imports() {
      const imports = {};
      imports.wbg = {};
      imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
        takeObject(arg0);
      };
      imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
        const ret = new Error(getStringFromWasm0(arg0, arg1));
        return addHeapObject(ret);
      };
      imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
        const ret = getObject(arg0);
        return addHeapObject(ret);
      };
      imports.wbg.__wbindgen_number_new = function(arg0) {
        const ret = arg0;
        return addHeapObject(ret);
      };
      imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) {
        const ret = BigInt.asUintN(64, arg0);
        return addHeapObject(ret);
      };
      imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
        const ret = getStringFromWasm0(arg0, arg1);
        return addHeapObject(ret);
      };
      imports.wbg.__wbg_set_f975102236d3c502 = function(arg0, arg1, arg2) {
        getObject(arg0)[takeObject(arg1)] = takeObject(arg2);
      };
      imports.wbg.__wbg_new_b525de17f44a8943 = function() {
        const ret = new Array();
        return addHeapObject(ret);
      };
      imports.wbg.__wbg_new_f841cc6f2098f4b5 = function() {
        const ret = /* @__PURE__ */ new Map();
        return addHeapObject(ret);
      };
      imports.wbg.__wbg_new_f9876326328f45ed = function() {
        const ret = new Object();
        return addHeapObject(ret);
      };
      imports.wbg.__wbindgen_is_string = function(arg0) {
        const ret = typeof getObject(arg0) === "string";
        return ret;
      };
      imports.wbg.__wbg_set_17224bc548dd1d7b = function(arg0, arg1, arg2) {
        getObject(arg0)[arg1 >>> 0] = takeObject(arg2);
      };
      imports.wbg.__wbg_set_388c4c6422704173 = function(arg0, arg1, arg2) {
        const ret = getObject(arg0).set(getObject(arg1), getObject(arg2));
        return addHeapObject(ret);
      };
      imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {
        const ret = debugString(getObject(arg1));
        const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len1 = WASM_VECTOR_LEN;
        getInt32Memory0()[arg0 / 4 + 1] = len1;
        getInt32Memory0()[arg0 / 4 + 0] = ptr1;
      };
      imports.wbg.__wbindgen_throw = function(arg0, arg1) {
        throw new Error(getStringFromWasm0(arg0, arg1));
      };
      return imports;
    }
    function __wbg_finalize_init(instance, module2) {
      wasm = instance.exports;
      __wbg_init.__wbindgen_wasm_module = module2;
      cachedInt32Memory0 = null;
      cachedUint32Memory0 = null;
      cachedUint8Memory0 = null;
      return wasm;
    }
    function initSync(module2) {
      if (wasm !== void 0) return wasm;
      const imports = __wbg_get_imports();
      if (!(module2 instanceof WebAssembly.Module)) {
        module2 = new WebAssembly.Module(module2);
      }
      const instance = new WebAssembly.Instance(module2, imports);
      return __wbg_finalize_init(instance, module2);
    }
    async function __wbg_init(input2) {
      if (wasm !== void 0) return wasm;
      const imports = __wbg_get_imports();
      if (typeof input2 === "string" || typeof Request === "function" && input2 instanceof Request || typeof URL === "function" && input2 instanceof URL) {
        input2 = fetch(input2);
      }
      const {
        instance,
        module: module2
      } = await __wbg_load(await input2, imports);
      return __wbg_finalize_init(instance, module2);
    }
    var exports = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      Vt,
      create: create$1,
      default: __wbg_init,
      initSync
    });
    const base64codes = [62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51];
    function getBase64Code(charCode) {
      return base64codes[charCode - 43];
    }
    function base64_decode(str2) {
      let missingOctets = str2.endsWith("==") ? 2 : str2.endsWith("=") ? 1 : 0;
      let n = str2.length;
      let result2 = new Uint8Array(3 * (n / 4));
      let buffer2;
      for (let i2 = 0, j2 = 0; i2 < n; i2 += 4, j2 += 3) {
        buffer2 = getBase64Code(str2.charCodeAt(i2)) << 18 | getBase64Code(str2.charCodeAt(i2 + 1)) << 12 | getBase64Code(str2.charCodeAt(i2 + 2)) << 6 | getBase64Code(str2.charCodeAt(i2 + 3));
        result2[j2] = buffer2 >> 16;
        result2[j2 + 1] = buffer2 >> 8 & 255;
        result2[j2 + 2] = buffer2 & 255;
      }
      return result2.subarray(0, result2.length - missingOctets);
    }
    const wasm_code = base64_decode(" ");
    var loadVt = async () => {
      await __wbg_init(wasm_code);
      return exports;
    };
    class Clock {
      constructor() {
        let speed = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 1;
        this.speed = speed;
        this.startTime = performance.now();
      }
      getTime() {
        return this.speed * (performance.now() - this.startTime) / 1e3;
      }
      setTime(time) {
        this.startTime = performance.now() - time / this.speed * 1e3;
      }
    }
    class NullClock {
      constructor() {
      }
      getTime(_speed) {
      }
      setTime(_time) {
      }
    }
    class Stream {
      constructor(input2, xfs) {
        this.input = typeof input2.next === "function" ? input2 : input2[Symbol.iterator]();
        this.xfs = xfs ?? [];
      }
      map(f) {
        return this.transform(Map$1(f));
      }
      flatMap(f) {
        return this.transform(FlatMap(f));
      }
      filter(f) {
        return this.transform(Filter(f));
      }
      take(n) {
        return this.transform(Take(n));
      }
      drop(n) {
        return this.transform(Drop(n));
      }
      transform(f) {
        return new Stream(this.input, this.xfs.concat([f]));
      }
      multiplex(other, comparator) {
        return new Stream(new Multiplexer(this[Symbol.iterator](), other[Symbol.iterator](), comparator));
      }
      toArray() {
        return Array.from(this);
      }
      [Symbol.iterator]() {
        let v = 0;
        let values = [];
        let flushed = false;
        const xf = compose(this.xfs, (val) => values.push(val));
        return {
          next: () => {
            if (v === values.length) {
              values = [];
              v = 0;
            }
            while (values.length === 0) {
              const next = this.input.next();
              if (next.done) {
                break;
              } else {
                xf.step(next.value);
              }
            }
            if (values.length === 0 && !flushed) {
              xf.flush();
              flushed = true;
            }
            if (values.length > 0) {
              return {
                done: false,
                value: values[v++]
              };
            } else {
              return {
                done: true
              };
            }
          }
        };
      }
    }
    function Map$1(f) {
      return (emit) => {
        return (input2) => {
          emit(f(input2));
        };
      };
    }
    function FlatMap(f) {
      return (emit) => {
        return (input2) => {
          f(input2).forEach(emit);
        };
      };
    }
    function Filter(f) {
      return (emit) => {
        return (input2) => {
          if (f(input2)) {
            emit(input2);
          }
        };
      };
    }
    function Take(n) {
      let c2 = 0;
      return (emit) => {
        return (input2) => {
          if (c2 < n) {
            emit(input2);
          }
          c2 += 1;
        };
      };
    }
    function Drop(n) {
      let c2 = 0;
      return (emit) => {
        return (input2) => {
          c2 += 1;
          if (c2 > n) {
            emit(input2);
          }
        };
      };
    }
    function compose(xfs, push2) {
      return xfs.reverse().reduce((next, curr) => {
        const xf = toXf(curr(next.step));
        return {
          step: xf.step,
          flush: () => {
            xf.flush();
            next.flush();
          }
        };
      }, toXf(push2));
    }
    function toXf(xf) {
      if (typeof xf === "function") {
        return {
          step: xf,
          flush: () => {
          }
        };
      } else {
        return xf;
      }
    }
    class Multiplexer {
      constructor(left, right, comparator) {
        this.left = left;
        this.right = right;
        this.comparator = comparator;
      }
      [Symbol.iterator]() {
        let leftItem;
        let rightItem;
        return {
          next: () => {
            if (leftItem === void 0 && this.left !== void 0) {
              const result2 = this.left.next();
              if (result2.done) {
                this.left = void 0;
              } else {
                leftItem = result2.value;
              }
            }
            if (rightItem === void 0 && this.right !== void 0) {
              const result2 = this.right.next();
              if (result2.done) {
                this.right = void 0;
              } else {
                rightItem = result2.value;
              }
            }
            if (leftItem === void 0 && rightItem === void 0) {
              return {
                done: true
              };
            } else if (leftItem === void 0) {
              const value2 = rightItem;
              rightItem = void 0;
              return {
                done: false,
                value: value2
              };
            } else if (rightItem === void 0) {
              const value2 = leftItem;
              leftItem = void 0;
              return {
                done: false,
                value: value2
              };
            } else if (this.comparator(leftItem, rightItem)) {
              const value2 = leftItem;
              leftItem = void 0;
              return {
                done: false,
                value: value2
              };
            } else {
              const value2 = rightItem;
              rightItem = void 0;
              return {
                done: false,
                value: value2
              };
            }
          }
        };
      }
    }
    async function parse$2(data) {
      let header2;
      let events;
      if (data instanceof Response) {
        const text2 = await data.text();
        const result2 = parseJsonl(text2);
        if (result2 !== void 0) {
          header2 = result2.header;
          events = result2.events;
        } else {
          header2 = JSON.parse(text2);
        }
      } else if (typeof data === "object" && typeof data.version === "number") {
        header2 = data;
      } else if (Array.isArray(data)) {
        header2 = data[0];
        events = data.slice(1, data.length);
      } else {
        throw "invalid data";
      }
      if (header2.version === 1) {
        return parseAsciicastV1(header2);
      } else if (header2.version === 2) {
        return parseAsciicastV2(header2, events);
      } else {
        throw `asciicast v${header2.version} format not supported`;
      }
    }
    function parseJsonl(jsonl) {
      const lines = jsonl.split("\n");
      let header2;
      try {
        header2 = JSON.parse(lines[0]);
      } catch (_error) {
        return;
      }
      const events = new Stream(lines).drop(1).filter((l) => l[0] === "[").map(JSON.parse).toArray();
      return {
        header: header2,
        events
      };
    }
    function parseAsciicastV1(data) {
      let time = 0;
      const events = new Stream(data.stdout).map((e) => {
        time += e[0];
        return [time, "o", e[1]];
      });
      return {
        cols: data.width,
        rows: data.height,
        events
      };
    }
    function parseAsciicastV2(header2, events) {
      return {
        cols: header2.width,
        rows: header2.height,
        theme: parseTheme$1(header2.theme),
        events,
        idleTimeLimit: header2.idle_time_limit
      };
    }
    function parseTheme$1(theme2) {
      const colorRegex = /^#[0-9A-Fa-f]{6}$/;
      const paletteRegex = /^(#[0-9A-Fa-f]{6}:){7,}#[0-9A-Fa-f]{6}$/;
      const fg = theme2 == null ? void 0 : theme2.fg;
      const bg = theme2 == null ? void 0 : theme2.bg;
      const palette = theme2 == null ? void 0 : theme2.palette;
      if (colorRegex.test(fg) && colorRegex.test(bg) && paletteRegex.test(palette)) {
        return {
          foreground: fg,
          background: bg,
          palette: palette.split(":")
        };
      }
    }
    function unparseAsciicastV2(recording2) {
      const header2 = JSON.stringify({
        version: 2,
        width: recording2.cols,
        height: recording2.rows
      });
      const events = recording2.events.map(JSON.stringify).join("\n");
      return `${header2}
${events}
`;
    }
    function recording(src, _ref, _ref2) {
      let {
        feed,
        resize,
        onInput,
        onMarker,
        now: now2,
        setTimeout: setTimeout2,
        setState,
        logger
      } = _ref;
      let {
        idleTimeLimit,
        startAt,
        loop,
        posterTime,
        markers: markers_,
        pauseOnMarkers,
        cols: initialCols,
        rows: initialRows
      } = _ref2;
      let cols;
      let rows;
      let events;
      let markers;
      let duration;
      let effectiveStartAt;
      let eventTimeoutId;
      let nextEventIndex = 0;
      let lastEventTime = 0;
      let startTime;
      let pauseElapsedTime;
      let playCount = 0;
      async function init() {
        const {
          parser: parser2,
          minFrameTime,
          inputOffset,
          dumpFilename,
          encoding = "utf-8"
        } = src;
        const recording2 = prepare(await parser2(await doFetch(src), {
          encoding
        }), logger, {
          idleTimeLimit,
          startAt,
          minFrameTime,
          inputOffset,
          markers_
        });
        ({
          cols,
          rows,
          events,
          duration,
          effectiveStartAt
        } = recording2);
        initialCols = initialCols ?? cols;
        initialRows = initialRows ?? rows;
        if (events.length === 0) {
          throw "recording is missing events";
        }
        if (dumpFilename !== void 0) {
          dump(recording2, dumpFilename);
        }
        const poster = posterTime !== void 0 ? getPoster(posterTime) : void 0;
        markers = events.filter((e) => e[1] === "m").map((e) => [e[0], e[2].label]);
        return {
          cols,
          rows,
          duration,
          theme: recording2.theme,
          poster,
          markers
        };
      }
      function doFetch(_ref3) {
        let {
          url,
          data,
          fetchOpts = {}
        } = _ref3;
        if (typeof url === "string") {
          return doFetchOne(url, fetchOpts);
        } else if (Array.isArray(url)) {
          return Promise.all(url.map((url2) => doFetchOne(url2, fetchOpts)));
        } else if (data !== void 0) {
          if (typeof data === "function") {
            data = data();
          }
          if (!(data instanceof Promise)) {
            data = Promise.resolve(data);
          }
          return data.then((value2) => {
            if (typeof value2 === "string" || value2 instanceof ArrayBuffer) {
              return new Response(value2);
            } else {
              return value2;
            }
          });
        } else {
          throw "failed fetching recording file: url/data missing in src";
        }
      }
      async function doFetchOne(url, fetchOpts) {
        const response = await fetch(url, fetchOpts);
        if (!response.ok) {
          throw `failed fetching recording from ${url}: ${response.status} ${response.statusText}`;
        }
        return response;
      }
      function delay(targetTime) {
        let delay2 = targetTime * 1e3 - (now2() - startTime);
        if (delay2 < 0) {
          delay2 = 0;
        }
        return delay2;
      }
      function scheduleNextEvent() {
        const nextEvent = events[nextEventIndex];
        if (nextEvent) {
          eventTimeoutId = setTimeout2(runNextEvent, delay(nextEvent[0]));
        } else {
          onEnd();
        }
      }
      function runNextEvent() {
        let event = events[nextEventIndex];
        let elapsedWallTime;
        do {
          lastEventTime = event[0];
          nextEventIndex++;
          const stop = executeEvent2(event);
          if (stop) {
            return;
          }
          event = events[nextEventIndex];
          elapsedWallTime = now2() - startTime;
        } while (event && elapsedWallTime > event[0] * 1e3);
        scheduleNextEvent();
      }
      function cancelNextEvent() {
        clearTimeout(eventTimeoutId);
        eventTimeoutId = null;
      }
      function executeEvent2(event) {
        const [time, type, data] = event;
        if (type === "o") {
          feed(data);
        } else if (type === "i") {
          onInput(data);
        } else if (type === "r") {
          const [cols2, rows2] = data.split("x");
          resize(cols2, rows2);
        } else if (type === "m") {
          onMarker(data);
          if (pauseOnMarkers) {
            pause();
            pauseElapsedTime = time * 1e3;
            setState("idle", {
              reason: "paused"
            });
            return true;
          }
        }
        return false;
      }
      function onEnd() {
        cancelNextEvent();
        playCount++;
        if (loop === true || typeof loop === "number" && playCount < loop) {
          nextEventIndex = 0;
          startTime = now2();
          feed("\x1Bc");
          resizeTerminalToInitialSize();
          scheduleNextEvent();
        } else {
          pauseElapsedTime = duration * 1e3;
          setState("ended");
        }
      }
      function play() {
        if (eventTimeoutId) throw "already playing";
        if (events[nextEventIndex] === void 0) throw "already ended";
        if (effectiveStartAt !== null) {
          seek(effectiveStartAt);
        }
        resume();
        return true;
      }
      function pause() {
        if (!eventTimeoutId) return true;
        cancelNextEvent();
        pauseElapsedTime = now2() - startTime;
        return true;
      }
      function resume() {
        startTime = now2() - pauseElapsedTime;
        pauseElapsedTime = null;
        scheduleNextEvent();
      }
      function seek(where) {
        const isPlaying = !!eventTimeoutId;
        pause();
        const currentTime = (pauseElapsedTime ?? 0) / 1e3;
        if (typeof where === "string") {
          if (where === "<<") {
            where = currentTime - 5;
          } else if (where === ">>") {
            where = currentTime + 5;
          } else if (where === "<<<") {
            where = currentTime - 0.1 * duration;
          } else if (where === ">>>") {
            where = currentTime + 0.1 * duration;
          } else if (where[where.length - 1] === "%") {
            where = parseFloat(where.substring(0, where.length - 1)) / 100 * duration;
          }
        } else if (typeof where === "object") {
          if (where.marker === "prev") {
            where = findMarkerTimeBefore(currentTime) ?? 0;
            if (isPlaying && currentTime - where < 1) {
              where = findMarkerTimeBefore(where) ?? 0;
            }
          } else if (where.marker === "next") {
            where = findMarkerTimeAfter(currentTime) ?? duration;
          } else if (typeof where.marker === "number") {
            const marker = markers[where.marker];
            if (marker === void 0) {
              throw `invalid marker index: ${where.marker}`;
            } else {
              where = marker[0];
            }
          }
        }
        const targetTime = Math.min(Math.max(where, 0), duration);
        if (targetTime < lastEventTime) {
          feed("\x1Bc");
          resizeTerminalToInitialSize();
          nextEventIndex = 0;
          lastEventTime = 0;
        }
        let event = events[nextEventIndex];
        while (event && event[0] <= targetTime) {
          if (event[1] === "o") {
            executeEvent2(event);
          }
          lastEventTime = event[0];
          event = events[++nextEventIndex];
        }
        pauseElapsedTime = targetTime * 1e3;
        effectiveStartAt = null;
        if (isPlaying) {
          resume();
        }
        return true;
      }
      function findMarkerTimeBefore(time) {
        if (markers.length == 0) return;
        let i2 = 0;
        let marker = markers[i2];
        let lastMarkerTimeBefore;
        while (marker && marker[0] < time) {
          lastMarkerTimeBefore = marker[0];
          marker = markers[++i2];
        }
        return lastMarkerTimeBefore;
      }
      function findMarkerTimeAfter(time) {
        if (markers.length == 0) return;
        let i2 = markers.length - 1;
        let marker = markers[i2];
        let firstMarkerTimeAfter;
        while (marker && marker[0] > time) {
          firstMarkerTimeAfter = marker[0];
          marker = markers[--i2];
        }
        return firstMarkerTimeAfter;
      }
      function step(n) {
        if (n === void 0) {
          n = 1;
        }
        let nextEvent;
        let targetIndex;
        if (n > 0) {
          let index2 = nextEventIndex;
          nextEvent = events[index2];
          for (let i2 = 0; i2 < n; i2++) {
            while (nextEvent !== void 0 && nextEvent[1] !== "o") {
              nextEvent = events[++index2];
            }
            if (nextEvent !== void 0 && nextEvent[1] === "o") {
              targetIndex = index2;
            }
          }
        } else {
          let index2 = Math.max(nextEventIndex - 2, 0);
          nextEvent = events[index2];
          for (let i2 = n; i2 < 0; i2++) {
            while (nextEvent !== void 0 && nextEvent[1] !== "o") {
              nextEvent = events[--index2];
            }
            if (nextEvent !== void 0 && nextEvent[1] === "o") {
              targetIndex = index2;
            }
          }
          if (targetIndex !== void 0) {
            feed("\x1Bc");
            resizeTerminalToInitialSize();
            nextEventIndex = 0;
          }
        }
        if (targetIndex === void 0) return;
        while (nextEventIndex <= targetIndex) {
          nextEvent = events[nextEventIndex++];
          if (nextEvent[1] === "o") {
            executeEvent2(nextEvent);
          }
        }
        lastEventTime = nextEvent[0];
        pauseElapsedTime = lastEventTime * 1e3;
        effectiveStartAt = null;
        if (events[targetIndex + 1] === void 0) {
          onEnd();
        }
      }
      function restart() {
        if (eventTimeoutId) throw "still playing";
        if (events[nextEventIndex] !== void 0) throw "not ended";
        seek(0);
        resume();
        return true;
      }
      function getPoster(time) {
        return events.filter((e) => e[0] < time && e[1] === "o").map((e) => e[2]);
      }
      function getCurrentTime() {
        if (eventTimeoutId) {
          return (now2() - startTime) / 1e3;
        } else {
          return (pauseElapsedTime ?? 0) / 1e3;
        }
      }
      function resizeTerminalToInitialSize() {
        resize(initialCols, initialRows);
      }
      return {
        init,
        play,
        pause,
        seek,
        step,
        restart,
        stop: pause,
        getCurrentTime
      };
    }
    function batcher(logger) {
      let minFrameTime = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1 / 60;
      let prevEvent;
      return (emit) => {
        let ic = 0;
        let oc = 0;
        return {
          step: (event) => {
            ic++;
            if (prevEvent === void 0) {
              prevEvent = event;
              return;
            }
            if (event[1] === "o" && prevEvent[1] === "o" && event[0] - prevEvent[0] < minFrameTime) {
              prevEvent[2] += event[2];
            } else {
              emit(prevEvent);
              prevEvent = event;
              oc++;
            }
          },
          flush: () => {
            if (prevEvent !== void 0) {
              emit(prevEvent);
              oc++;
            }
            logger.debug(`batched ${ic} frames to ${oc} frames`);
          }
        };
      };
    }
    function prepare(recording2, logger, _ref4) {
      let {
        startAt = 0,
        idleTimeLimit,
        minFrameTime,
        inputOffset,
        markers_
      } = _ref4;
      let {
        events
      } = recording2;
      if (!(events instanceof Stream)) {
        events = new Stream(events);
      }
      idleTimeLimit = idleTimeLimit ?? recording2.idleTimeLimit ?? Infinity;
      const limiterOutput = {
        offset: 0
      };
      events = events.transform(batcher(logger, minFrameTime)).map(timeLimiter(idleTimeLimit, startAt, limiterOutput)).map(markerWrapper());
      if (markers_ !== void 0) {
        markers_ = new Stream(markers_).map(normalizeMarker);
        events = events.filter((e) => e[1] !== "m").multiplex(markers_, (a, b) => a[0] < b[0]).map(markerWrapper());
      }
      events = events.toArray();
      if (inputOffset !== void 0) {
        events = events.map((e) => e[1] === "i" ? [e[0] + inputOffset, e[1], e[2]] : e);
        events.sort((a, b) => a[0] - b[0]);
      }
      const duration = events[events.length - 1][0];
      const effectiveStartAt = startAt - limiterOutput.offset;
      return {
        ...recording2,
        events,
        duration,
        effectiveStartAt
      };
    }
    function normalizeMarker(m) {
      return typeof m === "number" ? [m, "m", ""] : [m[0], "m", m[1]];
    }
    function timeLimiter(idleTimeLimit, startAt, output2) {
      let prevT = 0;
      let shift2 = 0;
      return function(e) {
        const delay = e[0] - prevT;
        const delta = delay - idleTimeLimit;
        prevT = e[0];
        if (delta > 0) {
          shift2 += delta;
          if (e[0] < startAt) {
            output2.offset += delta;
          }
        }
        return [e[0] - shift2, e[1], e[2]];
      };
    }
    function markerWrapper() {
      let i2 = 0;
      return function(e) {
        if (e[1] === "m") {
          return [e[0], e[1], {
            index: i2++,
            time: e[0],
            label: e[2]
          }];
        } else {
          return e;
        }
      };
    }
    function dump(recording2, filename2) {
      const link2 = document.createElement("a");
      const events = recording2.events.map((e) => e[1] === "m" ? [e[0], e[1], e[2].label] : e);
      const asciicast = unparseAsciicastV2({
        ...recording2,
        events
      });
      link2.href = URL.createObjectURL(new Blob([asciicast], {
        type: "text/plain"
      }));
      link2.download = filename2;
      link2.click();
    }
    function clock(_ref, _ref2, _ref3) {
      let {
        hourColor = 3,
        minuteColor = 4,
        separatorColor = 9
      } = _ref;
      let {
        feed
      } = _ref2;
      let {
        cols = 5,
        rows = 1
      } = _ref3;
      const middleRow = Math.floor(rows / 2);
      const leftPad = Math.floor(cols / 2) - 2;
      const setupCursor = `\x1B[?25l\x1B[1m\x1B[${middleRow}B`;
      let intervalId;
      const getCurrentTime = () => {
        const d = /* @__PURE__ */ new Date();
        const h = d.getHours();
        const m = d.getMinutes();
        const seqs = [];
        seqs.push("\r");
        for (let i2 = 0; i2 < leftPad; i2++) {
          seqs.push(" ");
        }
        seqs.push(`\x1B[3${hourColor}m`);
        if (h < 10) {
          seqs.push("0");
        }
        seqs.push(`${h}`);
        seqs.push(`\x1B[3${separatorColor};5m:\x1B[25m`);
        seqs.push(`\x1B[3${minuteColor}m`);
        if (m < 10) {
          seqs.push("0");
        }
        seqs.push(`${m}`);
        return seqs;
      };
      const updateTime = () => {
        getCurrentTime().forEach(feed);
      };
      return {
        init: () => {
          const duration = 24 * 60;
          const poster = [setupCursor].concat(getCurrentTime());
          return {
            cols,
            rows,
            duration,
            poster
          };
        },
        play: () => {
          feed(setupCursor);
          updateTime();
          intervalId = setInterval(updateTime, 1e3);
          return true;
        },
        stop: () => {
          clearInterval(intervalId);
        },
        getCurrentTime: () => {
          const d = /* @__PURE__ */ new Date();
          return d.getHours() * 60 + d.getMinutes();
        }
      };
    }
    function random(src, _ref) {
      let {
        feed,
        setTimeout: setTimeout2
      } = _ref;
      const base2 = " ".charCodeAt(0);
      const range = "~".charCodeAt(0) - base2;
      let timeoutId;
      const schedule = () => {
        const t2 = Math.pow(5, Math.random() * 4);
        timeoutId = setTimeout2(print, t2);
      };
      const print = () => {
        schedule();
        const char = String.fromCharCode(base2 + Math.floor(Math.random() * range));
        feed(char);
      };
      return () => {
        schedule();
        return () => clearInterval(timeoutId);
      };
    }
    function benchmark(_ref, _ref2) {
      let {
        url,
        iterations = 10
      } = _ref;
      let {
        feed,
        setState,
        now: now2
      } = _ref2;
      let data;
      let byteCount = 0;
      return {
        async init() {
          const recording2 = await parse$2(await fetch(url));
          const {
            cols,
            rows,
            events
          } = recording2;
          data = Array.from(events).filter((_ref3) => {
            let [_time, type, _text] = _ref3;
            return type === "o";
          }).map((_ref4) => {
            let [time, _type, text2] = _ref4;
            return [time, text2];
          });
          const duration = data[data.length - 1][0];
          for (const [_, text2] of data) {
            byteCount += new Blob([text2]).size;
          }
          return {
            cols,
            rows,
            duration
          };
        },
        play() {
          const startTime = now2();
          for (let i2 = 0; i2 < iterations; i2++) {
            for (const [_, text2] of data) {
              feed(text2);
            }
            feed("\x1Bc");
          }
          const endTime = now2();
          const duration = (endTime - startTime) / 1e3;
          const throughput = byteCount * iterations / duration;
          const throughputMbs = byteCount / (1024 * 1024) * iterations / duration;
          console.info("benchmark: result", {
            byteCount,
            iterations,
            duration,
            throughput,
            throughputMbs
          });
          setTimeout(() => {
            setState("stopped", {
              reason: "ended"
            });
          }, 0);
          return true;
        }
      };
    }
    class Queue {
      constructor() {
        this.items = [];
        this.onPush = void 0;
      }
      push(item2) {
        this.items.push(item2);
        if (this.onPush !== void 0) {
          this.onPush(this.popAll());
          this.onPush = void 0;
        }
      }
      popAll() {
        if (this.items.length > 0) {
          const items = this.items;
          this.items = [];
          return items;
        } else {
          const thiz = this;
          return new Promise((resolve) => {
            thiz.onPush = resolve;
          });
        }
      }
    }
    function getBuffer(bufferTime, feed, resize, setTime, baseStreamTime, minFrameTime, logger) {
      const execute = executeEvent(feed, resize);
      if (bufferTime === 0) {
        logger.debug("using no buffer");
        return nullBuffer(execute);
      } else {
        bufferTime = bufferTime ?? {};
        let getBufferTime;
        if (typeof bufferTime === "number") {
          logger.debug(`using fixed time buffer (${bufferTime} ms)`);
          getBufferTime = (_latency) => bufferTime;
        } else if (typeof bufferTime === "function") {
          logger.debug("using custom dynamic buffer");
          getBufferTime = bufferTime({
            logger
          });
        } else {
          logger.debug("using adaptive buffer", bufferTime);
          getBufferTime = adaptiveBufferTimeProvider({
            logger
          }, bufferTime);
        }
        return buffer(getBufferTime, execute, setTime, logger, baseStreamTime ?? 0, minFrameTime);
      }
    }
    function nullBuffer(execute) {
      return {
        pushEvent(event) {
          execute(event[1], event[2]);
        },
        pushText(text2) {
          execute("o", text2);
        },
        stop() {
        }
      };
    }
    function executeEvent(feed, resize) {
      return function(code2, data) {
        if (code2 === "o") {
          feed(data);
        } else if (code2 === "r") {
          resize(data.cols, data.rows);
        }
      };
    }
    function buffer(getBufferTime, execute, setTime, logger, baseStreamTime) {
      let minFrameTime = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : 1 / 60;
      let epoch = performance.now() - baseStreamTime * 1e3;
      let bufferTime = getBufferTime(0);
      const queue = new Queue();
      minFrameTime *= 1e3;
      let prevElapsedStreamTime = -minFrameTime;
      let stop = false;
      function elapsedWallTime() {
        return performance.now() - epoch;
      }
      setTimeout(async () => {
        while (!stop) {
          const events = await queue.popAll();
          if (stop) return;
          for (const event of events) {
            const elapsedStreamTime = event[0] * 1e3 + bufferTime;
            if (elapsedStreamTime - prevElapsedStreamTime < minFrameTime) {
              execute(event[1], event[2]);
              continue;
            }
            const delay = elapsedStreamTime - elapsedWallTime();
            if (delay > 0) {
              await sleep(delay);
              if (stop) return;
            }
            setTime(event[0]);
            execute(event[1], event[2]);
            prevElapsedStreamTime = elapsedStreamTime;
          }
        }
      }, 0);
      return {
        pushEvent(event) {
          let latency = elapsedWallTime() - event[0] * 1e3;
          if (latency < 0) {
            logger.debug(`correcting epoch by ${latency} ms`);
            epoch += latency;
            latency = 0;
          }
          bufferTime = getBufferTime(latency);
          queue.push(event);
        },
        pushText(text2) {
          queue.push([elapsedWallTime() / 1e3, "o", text2]);
        },
        stop() {
          stop = true;
          queue.push(void 0);
        }
      };
    }
    function sleep(t2) {
      return new Promise((resolve) => {
        setTimeout(resolve, t2);
      });
    }
    function adaptiveBufferTimeProvider(_ref, _ref2) {
      let {
        logger
      } = _ref;
      let {
        minTime = 25,
        maxLevel = 100,
        interval = 50,
        windowSize = 20,
        smoothingFactor = 0.2,
        minImprovementDuration = 1e3
      } = _ref2;
      let bufferLevel = 0;
      let bufferTime = calcBufferTime(bufferLevel);
      let latencies = [];
      let maxJitter = 0;
      let jitterRange = 0;
      let improvementTs = null;
      function calcBufferTime(level) {
        if (level === 0) {
          return minTime;
        } else {
          return interval * level;
        }
      }
      return (latency) => {
        latencies.push(latency);
        if (latencies.length < windowSize) {
          return bufferTime;
        }
        latencies = latencies.slice(-windowSize);
        const currentMinJitter = min(latencies);
        const currentMaxJitter = max(latencies);
        const currentJitterRange = currentMaxJitter - currentMinJitter;
        maxJitter = currentMaxJitter * smoothingFactor + maxJitter * (1 - smoothingFactor);
        jitterRange = currentJitterRange * smoothingFactor + jitterRange * (1 - smoothingFactor);
        const minBufferTime = maxJitter + jitterRange;
        if (latency > bufferTime) {
          logger.debug("buffer underrun", {
            latency,
            maxJitter,
            jitterRange,
            bufferTime
          });
        }
        if (bufferLevel < maxLevel && minBufferTime > bufferTime) {
          bufferTime = calcBufferTime(bufferLevel += 1);
          logger.debug(`jitter increased, raising bufferTime`, {
            latency,
            maxJitter,
            jitterRange,
            bufferTime
          });
        } else if (bufferLevel > 1 && minBufferTime < calcBufferTime(bufferLevel - 2) || bufferLevel == 1 && minBufferTime < calcBufferTime(bufferLevel - 1)) {
          if (improvementTs === null) {
            improvementTs = performance.now();
          } else if (performance.now() - improvementTs > minImprovementDuration) {
            improvementTs = performance.now();
            bufferTime = calcBufferTime(bufferLevel -= 1);
            logger.debug(`jitter decreased, lowering bufferTime`, {
              latency,
              maxJitter,
              jitterRange,
              bufferTime
            });
          }
          return bufferTime;
        }
        improvementTs = null;
        return bufferTime;
      };
    }
    function min(numbers) {
      return numbers.reduce((prev, cur2) => cur2 < prev ? cur2 : prev);
    }
    function max(numbers) {
      return numbers.reduce((prev, cur2) => cur2 > prev ? cur2 : prev);
    }
    const ONE_SEC_IN_USEC = 1e6;
    function alisHandler(logger) {
      const outputDecoder = new TextDecoder();
      const inputDecoder = new TextDecoder();
      let handler = parseMagicString;
      let lastEventTime;
      function parseMagicString(buffer2) {
        const text2 = new TextDecoder().decode(buffer2);
        if (text2 === "ALiS") {
          handler = parseInitFrame;
        } else {
          throw "not an ALiS v1 live stream";
        }
      }
      function parseInitFrame(buffer2) {
        const view = new BinaryReader(new DataView(buffer2));
        const type = view.getUint8();
        if (type !== 1) throw `expected init (0x01) frame, got ${type}`;
        let time = view.decodeVarUint();
        lastEventTime = time;
        time = time / ONE_SEC_IN_USEC;
        const cols = view.decodeVarUint();
        const rows = view.decodeVarUint();
        const themeFormat = view.getUint8();
        let theme2;
        if (themeFormat === 8) {
          const len = (2 + 8) * 3;
          theme2 = parseTheme(new Uint8Array(buffer2, view.offset, len));
          view.forward(len);
        } else if (themeFormat === 16) {
          const len = (2 + 16) * 3;
          theme2 = parseTheme(new Uint8Array(buffer2, view.offset, len));
          view.forward(len);
        } else if (themeFormat !== 0) {
          logger.warn(`alis: unsupported theme format (${themeFormat})`);
          socket.close();
          return;
        }
        const initLen = view.decodeVarUint();
        let init;
        if (initLen > 0) {
          init = outputDecoder.decode(new Uint8Array(buffer2, view.offset, initLen));
        }
        handler = parseEventFrame;
        return {
          time,
          term: {
            size: {
              cols,
              rows
            },
            theme: theme2,
            init
          }
        };
      }
      function parseEventFrame(buffer2) {
        const view = new BinaryReader(new DataView(buffer2));
        const type = view.getUint8();
        if (type === 111) {
          const relTime = view.decodeVarUint();
          lastEventTime += relTime;
          const len = view.decodeVarUint();
          const text2 = outputDecoder.decode(new Uint8Array(buffer2, view.offset, len));
          return [lastEventTime / ONE_SEC_IN_USEC, "o", text2];
        } else if (type === 105) {
          const relTime = view.decodeVarUint();
          lastEventTime += relTime;
          const len = view.decodeVarUint();
          const text2 = inputDecoder.decode(new Uint8Array(buffer2, view.offset, len));
          return [lastEventTime / ONE_SEC_IN_USEC, "i", text2];
        } else if (type === 114) {
          const relTime = view.decodeVarUint();
          lastEventTime += relTime;
          const cols = view.decodeVarUint();
          const rows = view.decodeVarUint();
          return [lastEventTime / ONE_SEC_IN_USEC, "r", {
            cols,
            rows
          }];
        } else if (type === 109) {
          const relTime = view.decodeVarUint();
          lastEventTime += relTime;
          const len = view.decodeVarUint();
          const decoder = new TextDecoder();
          const text2 = decoder.decode(new Uint8Array(buffer2, view.offset, len));
          return [lastEventTime / ONE_SEC_IN_USEC, "m", text2];
        } else if (type === 4) {
          handler = parseInitFrame;
          return false;
        } else {
          logger.debug(`alis: unknown frame type: ${type}`);
        }
      }
      return function(buffer2) {
        return handler(buffer2);
      };
    }
    function parseTheme(arr2) {
      const colorCount = arr2.length / 3;
      const foreground = hexColor(arr2[0], arr2[1], arr2[2]);
      const background = hexColor(arr2[3], arr2[4], arr2[5]);
      const palette = [];
      for (let i2 = 2; i2 < colorCount; i2++) {
        palette.push(hexColor(arr2[i2 * 3], arr2[i2 * 3 + 1], arr2[i2 * 3 + 2]));
      }
      return {
        foreground,
        background,
        palette
      };
    }
    function hexColor(r2, g, b) {
      return `#${byteToHex(r2)}${byteToHex(g)}${byteToHex(b)}`;
    }
    function byteToHex(value2) {
      return value2.toString(16).padStart(2, "0");
    }
    class BinaryReader {
      constructor(inner) {
        let offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
        this.inner = inner;
        this.offset = offset;
      }
      forward(delta) {
        this.offset += delta;
      }
      getUint8() {
        const value2 = this.inner.getUint8(this.offset);
        this.offset += 1;
        return value2;
      }
      decodeVarUint() {
        let number2 = 0;
        let shift2 = 0;
        let byte = this.getUint8();
        while (byte > 127) {
          byte &= 127;
          number2 += byte << shift2;
          shift2 += 7;
          byte = this.getUint8();
        }
        return number2 + (byte << shift2);
      }
    }
    function jsonHandler() {
      let parse2 = parseHeader;
      function parseHeader(buffer2) {
        const header2 = JSON.parse(buffer2);
        if (header2.version !== 2) {
          throw "not an asciicast v2 stream";
        }
        parse2 = parseEvent;
        return {
          time: 0,
          term: {
            size: {
              cols: header2.width,
              rows: header2.height
            }
          }
        };
      }
      function parseEvent(buffer2) {
        const event = JSON.parse(buffer2);
        if (event[1] === "r") {
          const [cols, rows] = event[2].split("x");
          return [event[0], "r", {
            cols,
            rows
          }];
        } else {
          return event;
        }
      }
      return function(buffer2) {
        return parse2(buffer2);
      };
    }
    function rawHandler() {
      const outputDecoder = new TextDecoder();
      let parse2 = parseSize;
      function parseSize(buffer2) {
        const text2 = outputDecoder.decode(buffer2, {
          stream: true
        });
        const [cols, rows] = sizeFromResizeSeq(text2) ?? sizeFromScriptStartMessage(text2) ?? [80, 24];
        parse2 = parseOutput;
        return {
          time: 0,
          term: {
            size: {
              cols,
              rows
            },
            init: text2
          }
        };
      }
      function parseOutput(buffer2) {
        return outputDecoder.decode(buffer2, {
          stream: true
        });
      }
      return function(buffer2) {
        return parse2(buffer2);
      };
    }
    function sizeFromResizeSeq(text2) {
      const match = text2.match(/\x1b\[8;(\d+);(\d+)t/);
      if (match !== null) {
        return [parseInt(match[2], 10), parseInt(match[1], 10)];
      }
    }
    function sizeFromScriptStartMessage(text2) {
      const match = text2.match(/\[.*COLUMNS="(\d{1,3})" LINES="(\d{1,3})".*\]/);
      if (match !== null) {
        return [parseInt(match[1], 10), parseInt(match[2], 10)];
      }
    }
    function exponentialDelay(attempt) {
      return Math.min(500 * Math.pow(2, attempt), 5e3);
    }
    function websocket(_ref, _ref2) {
      let {
        url,
        bufferTime,
        reconnectDelay = exponentialDelay,
        minFrameTime
      } = _ref;
      let {
        feed,
        reset,
        resize,
        setState,
        logger
      } = _ref2;
      logger = new PrefixedLogger(logger, "websocket: ");
      let socket2;
      let buf;
      let clock2 = new NullClock();
      let reconnectAttempt = 0;
      let successfulConnectionTimeout;
      let stop = false;
      let wasOnline = false;
      let initTimeout;
      function connect() {
        socket2 = new WebSocket(url, ["v1.alis", "v2.asciicast", "raw"]);
        socket2.binaryType = "arraybuffer";
        socket2.onopen = () => {
          const proto = socket2.protocol || "raw";
          logger.info("opened");
          logger.info(`activating ${proto} protocol handler`);
          if (proto === "v1.alis") {
            socket2.onmessage = onMessage(alisHandler(logger));
          } else if (proto === "v2.asciicast") {
            socket2.onmessage = onMessage(jsonHandler());
          } else if (proto === "raw") {
            socket2.onmessage = onMessage(rawHandler());
          }
          successfulConnectionTimeout = setTimeout(() => {
            reconnectAttempt = 0;
          }, 1e3);
        };
        socket2.onclose = (event) => {
          clearTimeout(initTimeout);
          stopBuffer();
          if (stop || event.code === 1e3 || event.code === 1005) {
            logger.info("closed");
            setState("ended", {
              message: "Stream ended"
            });
          } else if (event.code === 1002) {
            logger.debug(`close reason: ${event.reason}`);
            setState("ended", {
              message: "Err: Player not compatible with the server"
            });
          } else {
            clearTimeout(successfulConnectionTimeout);
            const delay = reconnectDelay(reconnectAttempt++);
            logger.info(`unclean close, reconnecting in ${delay}...`);
            setState("loading");
            setTimeout(connect, delay);
          }
        };
        wasOnline = false;
      }
      function onMessage(handler) {
        initTimeout = setTimeout(enterOfflineMode, 5e3);
        return function(event) {
          const result2 = handler(event.data);
          if (buf) {
            if (Array.isArray(result2)) {
              buf.pushEvent(result2);
            } else if (typeof result2 === "string") {
              buf.pushText(result2);
            } else if (result2 === false) {
              enterOfflineMode();
            } else if (result2 !== void 0) {
              throw `unexpected value from protocol handler: ${result2}`;
            }
          } else {
            if (typeof result2 === "object" && !Array.isArray(result2)) {
              const {
                time,
                term
              } = result2;
              const {
                size,
                init,
                theme: theme2
              } = term;
              const {
                cols,
                rows
              } = size;
              enterOnlineMode(cols, rows, time, init, theme2);
              clearTimeout(initTimeout);
            } else if (result2 === void 0) {
              clearTimeout(initTimeout);
              initTimeout = setTimeout(enterOfflineMode, 1e3);
            } else {
              clearTimeout(initTimeout);
              throw `unexpected value from protocol handler: ${result2}`;
            }
          }
        };
      }
      function enterOnlineMode(cols, rows, time, init, theme2) {
        logger.info(`stream init (${cols}x${rows} @${time})`);
        setState("playing");
        stopBuffer();
        buf = getBuffer(bufferTime, feed, resize, (t2) => clock2.setTime(t2), time, minFrameTime, logger);
        reset(cols, rows, init, theme2);
        clock2 = new Clock();
        wasOnline = true;
        if (typeof time === "number") {
          clock2.setTime(time);
        }
      }
      function enterOfflineMode() {
        stopBuffer();
        if (wasOnline) {
          logger.info("stream ended");
          setState("offline", {
            message: "Stream ended"
          });
        } else {
          logger.info("stream offline");
          setState("offline", {
            message: "Stream offline"
          });
        }
        clock2 = new NullClock();
      }
      function stopBuffer() {
        if (buf) buf.stop();
        buf = null;
      }
      return {
        play: () => {
          connect();
        },
        stop: () => {
          stop = true;
          stopBuffer();
          if (socket2 !== void 0) socket2.close();
        },
        getCurrentTime: () => clock2.getTime()
      };
    }
    function eventsource(_ref, _ref2) {
      let {
        url,
        bufferTime,
        minFrameTime
      } = _ref;
      let {
        feed,
        reset,
        setState,
        logger
      } = _ref2;
      logger = new PrefixedLogger(logger, "eventsource: ");
      let es;
      let buf;
      let clock2 = new NullClock();
      function initBuffer(baseStreamTime) {
        if (buf !== void 0) buf.stop();
        buf = getBuffer(bufferTime, feed, (t2) => clock2.setTime(t2), baseStreamTime, minFrameTime, logger);
      }
      return {
        play: () => {
          es = new EventSource(url);
          es.addEventListener("open", () => {
            logger.info("opened");
            initBuffer();
          });
          es.addEventListener("error", (e) => {
            logger.info("errored");
            logger.debug({
              e
            });
            setState("loading");
          });
          es.addEventListener("message", (event) => {
            const e = JSON.parse(event.data);
            if (Array.isArray(e)) {
              buf.pushEvent(e);
            } else if (e.cols !== void 0 || e.width !== void 0) {
              const cols = e.cols ?? e.width;
              const rows = e.rows ?? e.height;
              logger.debug(`vt reset (${cols}x${rows})`);
              setState("playing");
              initBuffer(e.time);
              reset(cols, rows, e.init ?? void 0);
              clock2 = new Clock();
              if (typeof e.time === "number") {
                clock2.setTime(e.time);
              }
            } else if (e.state === "offline") {
              logger.info("stream offline");
              setState("offline", {
                message: "Stream offline"
              });
              clock2 = new NullClock();
            }
          });
          es.addEventListener("done", () => {
            logger.info("closed");
            es.close();
            setState("ended", {
              message: "Stream ended"
            });
          });
        },
        stop: () => {
          if (buf !== void 0) buf.stop();
          if (es !== void 0) es.close();
        },
        getCurrentTime: () => clock2.getTime()
      };
    }
    async function parse$1(responses, _ref) {
      let {
        encoding
      } = _ref;
      const textDecoder = new TextDecoder(encoding);
      let cols;
      let rows;
      let timing = (await responses[0].text()).split("\n").filter((line2) => line2.length > 0).map((line2) => line2.split(" "));
      if (timing[0].length < 3) {
        timing = timing.map((entry2) => ["O", entry2[0], entry2[1]]);
      }
      const buffer2 = await responses[1].arrayBuffer();
      const array = new Uint8Array(buffer2);
      const dataOffset = array.findIndex((byte) => byte == 10) + 1;
      const header2 = textDecoder.decode(array.subarray(0, dataOffset));
      const sizeMatch = header2.match(/COLUMNS="(\d+)" LINES="(\d+)"/);
      if (sizeMatch !== null) {
        cols = parseInt(sizeMatch[1], 10);
        rows = parseInt(sizeMatch[2], 10);
      }
      const stdout = {
        array,
        cursor: dataOffset
      };
      let stdin = stdout;
      if (responses[2] !== void 0) {
        const buffer3 = await responses[2].arrayBuffer();
        const array2 = new Uint8Array(buffer3);
        stdin = {
          array: array2,
          cursor: dataOffset
        };
      }
      const events = [];
      let time = 0;
      for (const entry2 of timing) {
        time += parseFloat(entry2[1]);
        if (entry2[0] === "O") {
          const count = parseInt(entry2[2], 10);
          const bytes = stdout.array.subarray(stdout.cursor, stdout.cursor + count);
          const text2 = textDecoder.decode(bytes);
          events.push([time, "o", text2]);
          stdout.cursor += count;
        } else if (entry2[0] === "I") {
          const count = parseInt(entry2[2], 10);
          const bytes = stdin.array.subarray(stdin.cursor, stdin.cursor + count);
          const text2 = textDecoder.decode(bytes);
          events.push([time, "i", text2]);
          stdin.cursor += count;
        } else if (entry2[0] === "S" && entry2[2] === "SIGWINCH") {
          const cols2 = parseInt(entry2[4].slice(5), 10);
          const rows2 = parseInt(entry2[3].slice(5), 10);
          events.push([time, "r", `${cols2}x${rows2}`]);
        } else if (entry2[0] === "H" && entry2[2] === "COLUMNS") {
          cols = parseInt(entry2[3], 10);
        } else if (entry2[0] === "H" && entry2[2] === "LINES") {
          rows = parseInt(entry2[3], 10);
        }
      }
      cols = cols ?? 80;
      rows = rows ?? 24;
      return {
        cols,
        rows,
        events
      };
    }
    async function parse(response, _ref) {
      let {
        encoding
      } = _ref;
      const textDecoder = new TextDecoder(encoding);
      const buffer2 = await response.arrayBuffer();
      const array = new Uint8Array(buffer2);
      const firstFrame = parseFrame(array);
      const baseTime = firstFrame.time;
      const firstFrameText = textDecoder.decode(firstFrame.data);
      const sizeMatch = firstFrameText.match(/\x1b\[8;(\d+);(\d+)t/);
      const events = [];
      let cols = 80;
      let rows = 24;
      if (sizeMatch !== null) {
        cols = parseInt(sizeMatch[2], 10);
        rows = parseInt(sizeMatch[1], 10);
      }
      let cursor = 0;
      let frame = parseFrame(array);
      while (frame !== void 0) {
        const time = frame.time - baseTime;
        const text2 = textDecoder.decode(frame.data);
        events.push([time, "o", text2]);
        cursor += frame.len;
        frame = parseFrame(array.subarray(cursor));
      }
      return {
        cols,
        rows,
        events
      };
    }
    function parseFrame(array) {
      if (array.length < 13) return;
      const time = parseTimestamp(array.subarray(0, 8));
      const len = parseNumber(array.subarray(8, 12));
      const data = array.subarray(12, 12 + len);
      return {
        time,
        data,
        len: len + 12
      };
    }
    function parseNumber(array) {
      return array[0] + array[1] * 256 + array[2] * 256 * 256 + array[3] * 256 * 256 * 256;
    }
    function parseTimestamp(array) {
      const sec = parseNumber(array.subarray(0, 4));
      const usec = parseNumber(array.subarray(4, 8));
      return sec + usec / 1e6;
    }
    const vt = loadVt();
    class State {
      constructor(core) {
        this.core = core;
        this.driver = core.driver;
      }
      onEnter(data) {
      }
      init() {
      }
      play() {
      }
      pause() {
      }
      togglePlay() {
      }
      seek(where) {
        return false;
      }
      step(n) {
      }
      stop() {
        this.driver.stop();
      }
    }
    class UninitializedState extends State {
      async init() {
        try {
          await this.core._initializeDriver();
          return this.core._setState("idle");
        } catch (e) {
          this.core._setState("errored");
          throw e;
        }
      }
      async play() {
        this.core._dispatchEvent("play");
        const idleState = await this.init();
        await idleState.doPlay();
      }
      async togglePlay() {
        await this.play();
      }
      async seek(where) {
        const idleState = await this.init();
        return await idleState.seek(where);
      }
      async step(n) {
        const idleState = await this.init();
        await idleState.step(n);
      }
      stop() {
      }
    }
    class Idle extends State {
      onEnter(_ref) {
        let {
          reason,
          message: message2
        } = _ref;
        this.core._dispatchEvent("idle", {
          message: message2
        });
        if (reason === "paused") {
          this.core._dispatchEvent("pause");
        }
      }
      async play() {
        this.core._dispatchEvent("play");
        await this.doPlay();
      }
      async doPlay() {
        const stop = await this.driver.play();
        if (stop === true) {
          this.core._setState("playing");
        } else if (typeof stop === "function") {
          this.core._setState("playing");
          this.driver.stop = stop;
        }
      }
      async togglePlay() {
        await this.play();
      }
      seek(where) {
        return this.driver.seek(where);
      }
      step(n) {
        this.driver.step(n);
      }
    }
    class PlayingState extends State {
      onEnter() {
        this.core._dispatchEvent("playing");
      }
      pause() {
        if (this.driver.pause() === true) {
          this.core._setState("idle", {
            reason: "paused"
          });
        }
      }
      togglePlay() {
        this.pause();
      }
      seek(where) {
        return this.driver.seek(where);
      }
    }
    class LoadingState extends State {
      onEnter() {
        this.core._dispatchEvent("loading");
      }
    }
    class OfflineState extends State {
      onEnter(_ref2) {
        let {
          message: message2
        } = _ref2;
        this.core._dispatchEvent("offline", {
          message: message2
        });
      }
    }
    class EndedState extends State {
      onEnter(_ref3) {
        let {
          message: message2
        } = _ref3;
        this.core._dispatchEvent("ended", {
          message: message2
        });
      }
      async play() {
        this.core._dispatchEvent("play");
        if (await this.driver.restart()) {
          this.core._setState("playing");
        }
      }
      async togglePlay() {
        await this.play();
      }
      seek(where) {
        if (this.driver.seek(where) === true) {
          this.core._setState("idle");
          return true;
        }
        return false;
      }
    }
    class ErroredState extends State {
      onEnter() {
        this.core._dispatchEvent("errored");
      }
    }
    class Core {
      constructor(src, opts) {
        this.src = src;
        this.logger = opts.logger;
        this.state = new UninitializedState(this);
        this.stateName = "uninitialized";
        this.driver = null;
        this.changedLines = /* @__PURE__ */ new Set();
        this.cursor = void 0;
        this.duration = void 0;
        this.cols = opts.cols;
        this.rows = opts.rows;
        this.speed = opts.speed ?? 1;
        this.loop = opts.loop;
        this.idleTimeLimit = opts.idleTimeLimit;
        this.preload = opts.preload;
        this.startAt = parseNpt(opts.startAt);
        this.poster = this._parsePoster(opts.poster);
        this.markers = this._normalizeMarkers(opts.markers);
        this.pauseOnMarkers = opts.pauseOnMarkers;
        this.commandQueue = Promise.resolve();
        this.eventHandlers = /* @__PURE__ */ new Map([["ended", []], ["errored", []], ["idle", []], ["init", []], ["input", []], ["loading", []], ["marker", []], ["offline", []], ["pause", []], ["play", []], ["playing", []], ["reset", []], ["resize", []], ["seeked", []], ["terminalUpdate", []]]);
      }
      async init() {
        this.wasm = await vt;
        const feed = this._feed.bind(this);
        const onInput = (data) => {
          this._dispatchEvent("input", {
            data
          });
        };
        const onMarker = (_ref4) => {
          let {
            index: index2,
            time,
            label: label2
          } = _ref4;
          this._dispatchEvent("marker", {
            index: index2,
            time,
            label: label2
          });
        };
        const now2 = this._now.bind(this);
        const reset = this._resetVt.bind(this);
        const resize = this._resizeVt.bind(this);
        const setState = this._setState.bind(this);
        const posterTime = this.poster.type === "npt" ? this.poster.value : void 0;
        this.driver = getDriver(this.src)({
          feed,
          onInput,
          onMarker,
          reset,
          resize,
          now: now2,
          setTimeout: (f, t2) => setTimeout(f, t2 / this.speed),
          setInterval: (f, t2) => setInterval(f, t2 / this.speed),
          setState,
          logger: this.logger
        }, {
          cols: this.cols,
          rows: this.rows,
          idleTimeLimit: this.idleTimeLimit,
          startAt: this.startAt,
          loop: this.loop,
          posterTime,
          markers: this.markers,
          pauseOnMarkers: this.pauseOnMarkers
        });
        if (typeof this.driver === "function") {
          this.driver = {
            play: this.driver
          };
        }
        if (this.preload || posterTime !== void 0) {
          this._withState((state) => state.init());
        }
        const poster = this.poster.type === "text" ? this._renderPoster(this.poster.value) : void 0;
        const config2 = {
          isPausable: !!this.driver.pause,
          isSeekable: !!this.driver.seek,
          poster
        };
        if (this.driver.init === void 0) {
          this.driver.init = () => {
            return {};
          };
        }
        if (this.driver.pause === void 0) {
          this.driver.pause = () => {
          };
        }
        if (this.driver.seek === void 0) {
          this.driver.seek = (where) => false;
        }
        if (this.driver.step === void 0) {
          this.driver.step = (n) => {
          };
        }
        if (this.driver.stop === void 0) {
          this.driver.stop = () => {
          };
        }
        if (this.driver.restart === void 0) {
          this.driver.restart = () => {
          };
        }
        if (this.driver.getCurrentTime === void 0) {
          const play = this.driver.play;
          let clock2 = new NullClock();
          this.driver.play = () => {
            clock2 = new Clock(this.speed);
            return play();
          };
          this.driver.getCurrentTime = () => clock2.getTime();
        }
        return config2;
      }
      play() {
        return this._withState((state) => state.play());
      }
      pause() {
        return this._withState((state) => state.pause());
      }
      togglePlay() {
        return this._withState((state) => state.togglePlay());
      }
      seek(where) {
        return this._withState(async (state) => {
          if (await state.seek(where)) {
            this._dispatchEvent("seeked");
          }
        });
      }
      step(n) {
        return this._withState((state) => state.step(n));
      }
      stop() {
        return this._withState((state) => state.stop());
      }
      getChanges() {
        const changes = {};
        if (this.changedLines.size > 0) {
          const lines = /* @__PURE__ */ new Map();
          const rows = this.vt.rows;
          for (const i2 of this.changedLines) {
            if (i2 < rows) {
              lines.set(i2, {
                id: i2,
                segments: this.vt.getLine(i2)
              });
            }
          }
          this.changedLines.clear();
          changes.lines = lines;
        }
        if (this.cursor === void 0 && this.vt) {
          this.cursor = this.vt.getCursor() ?? false;
          changes.cursor = this.cursor;
        }
        return changes;
      }
      getCurrentTime() {
        return this.driver.getCurrentTime();
      }
      getRemainingTime() {
        if (typeof this.duration === "number") {
          return this.duration - Math.min(this.getCurrentTime(), this.duration);
        }
      }
      getProgress() {
        if (typeof this.duration === "number") {
          return Math.min(this.getCurrentTime(), this.duration) / this.duration;
        }
      }
      getDuration() {
        return this.duration;
      }
      addEventListener(eventName, handler) {
        this.eventHandlers.get(eventName).push(handler);
      }
      _dispatchEvent(eventName) {
        let data = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        for (const h of this.eventHandlers.get(eventName)) {
          h(data);
        }
      }
      _withState(f) {
        return this._enqueueCommand(() => f(this.state));
      }
      _enqueueCommand(f) {
        this.commandQueue = this.commandQueue.then(f);
        return this.commandQueue;
      }
      _setState(newState) {
        let data = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        if (this.stateName === newState) return this.state;
        this.stateName = newState;
        if (newState === "playing") {
          this.state = new PlayingState(this);
        } else if (newState === "idle") {
          this.state = new Idle(this);
        } else if (newState === "loading") {
          this.state = new LoadingState(this);
        } else if (newState === "ended") {
          this.state = new EndedState(this);
        } else if (newState === "offline") {
          this.state = new OfflineState(this);
        } else if (newState === "errored") {
          this.state = new ErroredState(this);
        } else {
          throw `invalid state: ${newState}`;
        }
        this.state.onEnter(data);
        return this.state;
      }
      _feed(data) {
        this._doFeed(data);
        this._dispatchEvent("terminalUpdate");
      }
      _doFeed(data) {
        const affectedLines = this.vt.feed(data);
        affectedLines.forEach((i2) => this.changedLines.add(i2));
        this.cursor = void 0;
      }
      _now() {
        return performance.now() * this.speed;
      }
      async _initializeDriver() {
        const meta2 = await this.driver.init();
        this.cols = this.cols ?? meta2.cols ?? 80;
        this.rows = this.rows ?? meta2.rows ?? 24;
        this.duration = this.duration ?? meta2.duration;
        this.markers = this._normalizeMarkers(meta2.markers) ?? this.markers ?? [];
        if (this.cols === 0) {
          this.cols = 80;
        }
        if (this.rows === 0) {
          this.rows = 24;
        }
        this._initializeVt(this.cols, this.rows);
        const poster = meta2.poster !== void 0 ? this._renderPoster(meta2.poster) : void 0;
        this._dispatchEvent("init", {
          cols: this.cols,
          rows: this.rows,
          duration: this.duration,
          markers: this.markers,
          theme: meta2.theme,
          poster
        });
      }
      _resetVt(cols, rows) {
        let init = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : void 0;
        let theme2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : void 0;
        this.cols = cols;
        this.rows = rows;
        this.cursor = void 0;
        this._initializeVt(cols, rows);
        if (init !== void 0 && init !== "") {
          this._doFeed(init);
        }
        this._dispatchEvent("reset", {
          cols,
          rows,
          theme: theme2
        });
      }
      _resizeVt(cols, rows) {
        if (cols === this.vt.cols && rows === this.vt.rows) return;
        const affectedLines = this.vt.resize(cols, rows);
        affectedLines.forEach((i2) => this.changedLines.add(i2));
        this.cursor = void 0;
        this.vt.cols = cols;
        this.vt.rows = rows;
        this.logger.debug(`core: vt resize (${cols}x${rows})`);
        this._dispatchEvent("resize", {
          cols,
          rows
        });
      }
      _initializeVt(cols, rows) {
        this.logger.debug(`core: vt init (${cols}x${rows})`);
        this.vt = this.wasm.create(cols, rows, true, 100);
        this.vt.cols = cols;
        this.vt.rows = rows;
        this.changedLines.clear();
        for (let i2 = 0; i2 < rows; i2++) {
          this.changedLines.add(i2);
        }
      }
      _parsePoster(poster) {
        if (typeof poster !== "string") return {};
        if (poster.substring(0, 16) == "data:text/plain,") {
          return {
            type: "text",
            value: [poster.substring(16)]
          };
        } else if (poster.substring(0, 4) == "npt:") {
          return {
            type: "npt",
            value: parseNpt(poster.substring(4))
          };
        }
        return {};
      }
      _renderPoster(poster) {
        const cols = this.cols ?? 80;
        const rows = this.rows ?? 24;
        this.logger.debug(`core: poster init (${cols}x${rows})`);
        const vt2 = this.wasm.create(cols, rows, false, 0);
        poster.forEach((text2) => vt2.feed(text2));
        const cursor = vt2.getCursor() ?? false;
        const lines = [];
        for (let i2 = 0; i2 < rows; i2++) {
          lines.push({
            id: i2,
            segments: vt2.getLine(i2)
          });
        }
        return {
          cursor,
          lines
        };
      }
      _normalizeMarkers(markers) {
        if (Array.isArray(markers)) {
          return markers.map((m) => typeof m === "number" ? [m, ""] : m);
        }
      }
    }
    const DRIVERS = /* @__PURE__ */ new Map([["benchmark", benchmark], ["clock", clock], ["eventsource", eventsource], ["random", random], ["recording", recording], ["websocket", websocket]]);
    const PARSERS = /* @__PURE__ */ new Map([["asciicast", parse$2], ["typescript", parse$1], ["ttyrec", parse]]);
    function getDriver(src) {
      if (typeof src === "function") return src;
      if (typeof src === "string") {
        if (src.substring(0, 5) == "ws://" || src.substring(0, 6) == "wss://") {
          src = {
            driver: "websocket",
            url: src
          };
        } else if (src.substring(0, 6) == "clock:") {
          src = {
            driver: "clock"
          };
        } else if (src.substring(0, 7) == "random:") {
          src = {
            driver: "random"
          };
        } else if (src.substring(0, 10) == "benchmark:") {
          src = {
            driver: "benchmark",
            url: src.substring(10)
          };
        } else {
          src = {
            driver: "recording",
            url: src
          };
        }
      }
      if (src.driver === void 0) {
        src.driver = "recording";
      }
      if (src.driver == "recording") {
        if (src.parser === void 0) {
          src.parser = "asciicast";
        }
        if (typeof src.parser === "string") {
          if (PARSERS.has(src.parser)) {
            src.parser = PARSERS.get(src.parser);
          } else {
            throw `unknown parser: ${src.parser}`;
          }
        }
      }
      if (DRIVERS.has(src.driver)) {
        const driver = DRIVERS.get(src.driver);
        return (callbacks, opts) => driver(src, callbacks, opts);
      } else {
        throw `unsupported driver: ${JSON.stringify(src)}`;
      }
    }
    const sharedConfig = {};
    function setHydrateContext(context) {
      sharedConfig.context = context;
    }
    const equalFn = (a, b) => a === b;
    const $PROXY = Symbol("solid-proxy");
    const $TRACK = Symbol("solid-track");
    const signalOptions = {
      equals: equalFn
    };
    let runEffects = runQueue;
    const STALE = 1;
    const PENDING = 2;
    const UNOWNED = {
      owned: null,
      cleanups: null,
      context: null,
      owner: null
    };
    var Owner = null;
    let Transition = null;
    let Listener = null;
    let Updates = null;
    let Effects = null;
    let ExecCount = 0;
    function createRoot(fn2, detachedOwner) {
      const listener = Listener, owner = Owner, unowned = fn2.length === 0, root2 = unowned ? UNOWNED : {
        owned: null,
        cleanups: null,
        context: null,
        owner: detachedOwner === void 0 ? owner : detachedOwner
      }, updateFn = unowned ? fn2 : () => fn2(() => untrack(() => cleanNode(root2)));
      Owner = root2;
      Listener = null;
      try {
        return runUpdates(updateFn, true);
      } finally {
        Listener = listener;
        Owner = owner;
      }
    }
    function createSignal(value2, options2) {
      options2 = options2 ? Object.assign({}, signalOptions, options2) : signalOptions;
      const s = {
        value: value2,
        observers: null,
        observerSlots: null,
        comparator: options2.equals || void 0
      };
      const setter = (value3) => {
        if (typeof value3 === "function") {
          value3 = value3(s.value);
        }
        return writeSignal(s, value3);
      };
      return [readSignal.bind(s), setter];
    }
    function createRenderEffect(fn2, value2, options2) {
      const c2 = createComputation(fn2, value2, false, STALE);
      updateComputation(c2);
    }
    function createEffect(fn2, value2, options2) {
      runEffects = runUserEffects;
      const c2 = createComputation(fn2, value2, false, STALE);
      c2.user = true;
      Effects ? Effects.push(c2) : updateComputation(c2);
    }
    function createMemo(fn2, value2, options2) {
      options2 = options2 ? Object.assign({}, signalOptions, options2) : signalOptions;
      const c2 = createComputation(fn2, value2, true, 0);
      c2.observers = null;
      c2.observerSlots = null;
      c2.comparator = options2.equals || void 0;
      updateComputation(c2);
      return readSignal.bind(c2);
    }
    function batch(fn2) {
      return runUpdates(fn2, false);
    }
    function untrack(fn2) {
      if (Listener === null) return fn2();
      const listener = Listener;
      Listener = null;
      try {
        return fn2();
      } finally {
        Listener = listener;
      }
    }
    function onMount(fn2) {
      createEffect(() => untrack(fn2));
    }
    function onCleanup(fn2) {
      if (Owner === null) ;
      else if (Owner.cleanups === null) Owner.cleanups = [fn2];
      else Owner.cleanups.push(fn2);
      return fn2;
    }
    function getListener() {
      return Listener;
    }
    function children(fn2) {
      const children2 = createMemo(fn2);
      const memo = createMemo(() => resolveChildren(children2()));
      memo.toArray = () => {
        const c2 = memo();
        return Array.isArray(c2) ? c2 : c2 != null ? [c2] : [];
      };
      return memo;
    }
    function readSignal() {
      const runningTransition = Transition;
      if (this.sources && (this.state || runningTransition)) {
        if (this.state === STALE || runningTransition) updateComputation(this);
        else {
          const updates = Updates;
          Updates = null;
          runUpdates(() => lookUpstream(this), false);
          Updates = updates;
        }
      }
      if (Listener) {
        const sSlot = this.observers ? this.observers.length : 0;
        if (!Listener.sources) {
          Listener.sources = [this];
          Listener.sourceSlots = [sSlot];
        } else {
          Listener.sources.push(this);
          Listener.sourceSlots.push(sSlot);
        }
        if (!this.observers) {
          this.observers = [Listener];
          this.observerSlots = [Listener.sources.length - 1];
        } else {
          this.observers.push(Listener);
          this.observerSlots.push(Listener.sources.length - 1);
        }
      }
      return this.value;
    }
    function writeSignal(node2, value2, isComp) {
      let current = node2.value;
      if (!node2.comparator || !node2.comparator(current, value2)) {
        node2.value = value2;
        if (node2.observers && node2.observers.length) {
          runUpdates(() => {
            for (let i2 = 0; i2 < node2.observers.length; i2 += 1) {
              const o = node2.observers[i2];
              const TransitionRunning = Transition && Transition.running;
              if (TransitionRunning && Transition.disposed.has(o)) ;
              if (TransitionRunning && !o.tState || !TransitionRunning && !o.state) {
                if (o.pure) Updates.push(o);
                else Effects.push(o);
                if (o.observers) markDownstream(o);
              }
              if (TransitionRunning) ;
              else o.state = STALE;
            }
            if (Updates.length > 1e6) {
              Updates = [];
              if (false) ;
              throw new Error();
            }
          }, false);
        }
      }
      return value2;
    }
    function updateComputation(node2) {
      if (!node2.fn) return;
      cleanNode(node2);
      const owner = Owner, listener = Listener, time = ExecCount;
      Listener = Owner = node2;
      runComputation(node2, node2.value, time);
      Listener = listener;
      Owner = owner;
    }
    function runComputation(node2, value2, time) {
      let nextValue;
      try {
        nextValue = node2.fn(value2);
      } catch (err2) {
        if (node2.pure) {
          {
            node2.state = STALE;
            node2.owned && node2.owned.forEach(cleanNode);
            node2.owned = null;
          }
        }
        handleError(err2);
      }
      if (!node2.updatedAt || node2.updatedAt <= time) {
        if (node2.updatedAt != null && "observers" in node2) {
          writeSignal(node2, nextValue);
        } else node2.value = nextValue;
        node2.updatedAt = time;
      }
    }
    function createComputation(fn2, init, pure, state = STALE, options2) {
      const c2 = {
        fn: fn2,
        state,
        updatedAt: null,
        owned: null,
        sources: null,
        sourceSlots: null,
        cleanups: null,
        value: init,
        owner: Owner,
        context: null,
        pure
      };
      if (Owner === null) ;
      else if (Owner !== UNOWNED) {
        {
          if (!Owner.owned) Owner.owned = [c2];
          else Owner.owned.push(c2);
        }
      }
      return c2;
    }
    function runTop(node2) {
      const runningTransition = Transition;
      if (node2.state === 0 || runningTransition) return;
      if (node2.state === PENDING || runningTransition) return lookUpstream(node2);
      if (node2.suspense && untrack(node2.suspense.inFallback)) return node2.suspense.effects.push(node2);
      const ancestors = [node2];
      while ((node2 = node2.owner) && (!node2.updatedAt || node2.updatedAt < ExecCount)) {
        if (node2.state || runningTransition) ancestors.push(node2);
      }
      for (let i2 = ancestors.length - 1; i2 >= 0; i2--) {
        node2 = ancestors[i2];
        if (node2.state === STALE || runningTransition) {
          updateComputation(node2);
        } else if (node2.state === PENDING || runningTransition) {
          const updates = Updates;
          Updates = null;
          runUpdates(() => lookUpstream(node2, ancestors[0]), false);
          Updates = updates;
        }
      }
    }
    function runUpdates(fn2, init) {
      if (Updates) return fn2();
      let wait = false;
      if (!init) Updates = [];
      if (Effects) wait = true;
      else Effects = [];
      ExecCount++;
      try {
        const res = fn2();
        completeUpdates(wait);
        return res;
      } catch (err2) {
        if (!wait) Effects = null;
        Updates = null;
        handleError(err2);
      }
    }
    function completeUpdates(wait) {
      if (Updates) {
        runQueue(Updates);
        Updates = null;
      }
      if (wait) return;
      const e = Effects;
      Effects = null;
      if (e.length) runUpdates(() => runEffects(e), false);
    }
    function runQueue(queue) {
      for (let i2 = 0; i2 < queue.length; i2++) runTop(queue[i2]);
    }
    function runUserEffects(queue) {
      let i2, userLength = 0;
      for (i2 = 0; i2 < queue.length; i2++) {
        const e = queue[i2];
        if (!e.user) runTop(e);
        else queue[userLength++] = e;
      }
      if (sharedConfig.context) setHydrateContext();
      for (i2 = 0; i2 < userLength; i2++) runTop(queue[i2]);
    }
    function lookUpstream(node2, ignore) {
      const runningTransition = Transition;
      node2.state = 0;
      for (let i2 = 0; i2 < node2.sources.length; i2 += 1) {
        const source2 = node2.sources[i2];
        if (source2.sources) {
          if (source2.state === STALE || runningTransition) {
            if (source2 !== ignore) runTop(source2);
          } else if (source2.state === PENDING || runningTransition) lookUpstream(source2, ignore);
        }
      }
    }
    function markDownstream(node2) {
      const runningTransition = Transition;
      for (let i2 = 0; i2 < node2.observers.length; i2 += 1) {
        const o = node2.observers[i2];
        if (!o.state || runningTransition) {
          o.state = PENDING;
          if (o.pure) Updates.push(o);
          else Effects.push(o);
          o.observers && markDownstream(o);
        }
      }
    }
    function cleanNode(node2) {
      let i2;
      if (node2.sources) {
        while (node2.sources.length) {
          const source2 = node2.sources.pop(), index2 = node2.sourceSlots.pop(), obs = source2.observers;
          if (obs && obs.length) {
            const n = obs.pop(), s = source2.observerSlots.pop();
            if (index2 < obs.length) {
              n.sourceSlots[s] = index2;
              obs[index2] = n;
              source2.observerSlots[index2] = s;
            }
          }
        }
      }
      if (node2.owned) {
        for (i2 = 0; i2 < node2.owned.length; i2++) cleanNode(node2.owned[i2]);
        node2.owned = null;
      }
      if (node2.cleanups) {
        for (i2 = 0; i2 < node2.cleanups.length; i2++) node2.cleanups[i2]();
        node2.cleanups = null;
      }
      node2.state = 0;
      node2.context = null;
    }
    function castError(err2) {
      if (err2 instanceof Error || typeof err2 === "string") return err2;
      return new Error("Unknown error");
    }
    function handleError(err2) {
      err2 = castError(err2);
      throw err2;
    }
    function resolveChildren(children2) {
      if (typeof children2 === "function" && !children2.length) return resolveChildren(children2());
      if (Array.isArray(children2)) {
        const results = [];
        for (let i2 = 0; i2 < children2.length; i2++) {
          const result2 = resolveChildren(children2[i2]);
          Array.isArray(result2) ? results.push.apply(results, result2) : results.push(result2);
        }
        return results;
      }
      return children2;
    }
    const FALLBACK = Symbol("fallback");
    function dispose(d) {
      for (let i2 = 0; i2 < d.length; i2++) d[i2]();
    }
    function mapArray(list2, mapFn, options2 = {}) {
      let items = [], mapped = [], disposers = [], len = 0, indexes = mapFn.length > 1 ? [] : null;
      onCleanup(() => dispose(disposers));
      return () => {
        let newItems = list2() || [], i2, j2;
        newItems[$TRACK];
        return untrack(() => {
          let newLen = newItems.length, newIndices, newIndicesNext, temp, tempdisposers, tempIndexes, start, end, newEnd, item2;
          if (newLen === 0) {
            if (len !== 0) {
              dispose(disposers);
              disposers = [];
              items = [];
              mapped = [];
              len = 0;
              indexes && (indexes = []);
            }
            if (options2.fallback) {
              items = [FALLBACK];
              mapped[0] = createRoot((disposer) => {
                disposers[0] = disposer;
                return options2.fallback();
              });
              len = 1;
            }
          } else if (len === 0) {
            mapped = new Array(newLen);
            for (j2 = 0; j2 < newLen; j2++) {
              items[j2] = newItems[j2];
              mapped[j2] = createRoot(mapper);
            }
            len = newLen;
          } else {
            temp = new Array(newLen);
            tempdisposers = new Array(newLen);
            indexes && (tempIndexes = new Array(newLen));
            for (start = 0, end = Math.min(len, newLen); start < end && items[start] === newItems[start]; start++) ;
            for (end = len - 1, newEnd = newLen - 1; end >= start && newEnd >= start && items[end] === newItems[newEnd]; end--, newEnd--) {
              temp[newEnd] = mapped[end];
              tempdisposers[newEnd] = disposers[end];
              indexes && (tempIndexes[newEnd] = indexes[end]);
            }
            newIndices = /* @__PURE__ */ new Map();
            newIndicesNext = new Array(newEnd + 1);
            for (j2 = newEnd; j2 >= start; j2--) {
              item2 = newItems[j2];
              i2 = newIndices.get(item2);
              newIndicesNext[j2] = i2 === void 0 ? -1 : i2;
              newIndices.set(item2, j2);
            }
            for (i2 = start; i2 <= end; i2++) {
              item2 = items[i2];
              j2 = newIndices.get(item2);
              if (j2 !== void 0 && j2 !== -1) {
                temp[j2] = mapped[i2];
                tempdisposers[j2] = disposers[i2];
                indexes && (tempIndexes[j2] = indexes[i2]);
                j2 = newIndicesNext[j2];
                newIndices.set(item2, j2);
              } else disposers[i2]();
            }
            for (j2 = start; j2 < newLen; j2++) {
              if (j2 in temp) {
                mapped[j2] = temp[j2];
                disposers[j2] = tempdisposers[j2];
                if (indexes) {
                  indexes[j2] = tempIndexes[j2];
                  indexes[j2](j2);
                }
              } else mapped[j2] = createRoot(mapper);
            }
            mapped = mapped.slice(0, len = newLen);
            items = newItems.slice(0);
          }
          return mapped;
        });
        function mapper(disposer) {
          disposers[j2] = disposer;
          if (indexes) {
            const [s, set] = createSignal(j2);
            indexes[j2] = set;
            return mapFn(newItems[j2], s);
          }
          return mapFn(newItems[j2]);
        }
      };
    }
    function indexArray(list2, mapFn, options2 = {}) {
      let items = [], mapped = [], disposers = [], signals = [], len = 0, i2;
      onCleanup(() => dispose(disposers));
      return () => {
        const newItems = list2() || [];
        newItems[$TRACK];
        return untrack(() => {
          if (newItems.length === 0) {
            if (len !== 0) {
              dispose(disposers);
              disposers = [];
              items = [];
              mapped = [];
              len = 0;
              signals = [];
            }
            if (options2.fallback) {
              items = [FALLBACK];
              mapped[0] = createRoot((disposer) => {
                disposers[0] = disposer;
                return options2.fallback();
              });
              len = 1;
            }
            return mapped;
          }
          if (items[0] === FALLBACK) {
            disposers[0]();
            disposers = [];
            items = [];
            mapped = [];
            len = 0;
          }
          for (i2 = 0; i2 < newItems.length; i2++) {
            if (i2 < items.length && items[i2] !== newItems[i2]) {
              signals[i2](() => newItems[i2]);
            } else if (i2 >= items.length) {
              mapped[i2] = createRoot(mapper);
            }
          }
          for (; i2 < items.length; i2++) {
            disposers[i2]();
          }
          len = signals.length = disposers.length = newItems.length;
          items = newItems.slice(0);
          return mapped = mapped.slice(0, len);
        });
        function mapper(disposer) {
          disposers[i2] = disposer;
          const [s, set] = createSignal(newItems[i2]);
          signals[i2] = set;
          return mapFn(s, i2);
        }
      };
    }
    function createComponent(Comp, props) {
      return untrack(() => Comp(props || {}));
    }
    function trueFn() {
      return true;
    }
    const propTraps = {
      get(_, property, receiver) {
        if (property === $PROXY) return receiver;
        return _.get(property);
      },
      has(_, property) {
        if (property === $PROXY) return true;
        return _.has(property);
      },
      set: trueFn,
      deleteProperty: trueFn,
      getOwnPropertyDescriptor(_, property) {
        return {
          configurable: true,
          enumerable: true,
          get() {
            return _.get(property);
          },
          set: trueFn,
          deleteProperty: trueFn
        };
      },
      ownKeys(_) {
        return _.keys();
      }
    };
    function resolveSource(s) {
      return !(s = typeof s === "function" ? s() : s) ? {} : s;
    }
    function mergeProps(...sources) {
      let proxy = false;
      for (let i2 = 0; i2 < sources.length; i2++) {
        const s = sources[i2];
        proxy = proxy || !!s && $PROXY in s;
        sources[i2] = typeof s === "function" ? (proxy = true, createMemo(s)) : s;
      }
      if (proxy) {
        return new Proxy({
          get(property) {
            for (let i2 = sources.length - 1; i2 >= 0; i2--) {
              const v = resolveSource(sources[i2])[property];
              if (v !== void 0) return v;
            }
          },
          has(property) {
            for (let i2 = sources.length - 1; i2 >= 0; i2--) {
              if (property in resolveSource(sources[i2])) return true;
            }
            return false;
          },
          keys() {
            const keys = [];
            for (let i2 = 0; i2 < sources.length; i2++) keys.push(...Object.keys(resolveSource(sources[i2])));
            return [...new Set(keys)];
          }
        }, propTraps);
      }
      const target2 = {};
      for (let i2 = sources.length - 1; i2 >= 0; i2--) {
        if (sources[i2]) {
          const descriptors = Object.getOwnPropertyDescriptors(sources[i2]);
          for (const key2 in descriptors) {
            if (key2 in target2) continue;
            Object.defineProperty(target2, key2, {
              enumerable: true,
              get() {
                for (let i3 = sources.length - 1; i3 >= 0; i3--) {
                  const v = (sources[i3] || {})[key2];
                  if (v !== void 0) return v;
                }
              }
            });
          }
        }
      }
      return target2;
    }
    function For(props) {
      const fallback = "fallback" in props && {
        fallback: () => props.fallback
      };
      return createMemo(mapArray(() => props.each, props.children, fallback || void 0));
    }
    function Index(props) {
      const fallback = "fallback" in props && {
        fallback: () => props.fallback
      };
      return createMemo(indexArray(() => props.each, props.children, fallback || void 0));
    }
    function Show(props) {
      let strictEqual = false;
      const keyed = props.keyed;
      const condition = createMemo(() => props.when, void 0, {
        equals: (a, b) => strictEqual ? a === b : !a === !b
      });
      return createMemo(() => {
        const c2 = condition();
        if (c2) {
          const child = props.children;
          const fn2 = typeof child === "function" && child.length > 0;
          strictEqual = keyed || fn2;
          return fn2 ? untrack(() => child(c2)) : child;
        }
        return props.fallback;
      }, void 0, void 0);
    }
    function Switch(props) {
      let strictEqual = false;
      let keyed = false;
      const equals = (a, b) => a[0] === b[0] && (strictEqual ? a[1] === b[1] : !a[1] === !b[1]) && a[2] === b[2];
      const conditions = children(() => props.children), evalConditions = createMemo(() => {
        let conds = conditions();
        if (!Array.isArray(conds)) conds = [conds];
        for (let i2 = 0; i2 < conds.length; i2++) {
          const c2 = conds[i2].when;
          if (c2) {
            keyed = !!conds[i2].keyed;
            return [i2, c2, conds[i2]];
          }
        }
        return [-1];
      }, void 0, {
        equals
      });
      return createMemo(() => {
        const [index2, when, cond] = evalConditions();
        if (index2 < 0) return props.fallback;
        const c2 = cond.children;
        const fn2 = typeof c2 === "function" && c2.length > 0;
        strictEqual = keyed || fn2;
        return fn2 ? untrack(() => c2(when)) : c2;
      }, void 0, void 0);
    }
    function Match(props) {
      return props;
    }
    function reconcileArrays(parentNode, a, b) {
      let bLength = b.length, aEnd = a.length, bEnd = bLength, aStart = 0, bStart = 0, after = a[aEnd - 1].nextSibling, map2 = null;
      while (aStart < aEnd || bStart < bEnd) {
        if (a[aStart] === b[bStart]) {
          aStart++;
          bStart++;
          continue;
        }
        while (a[aEnd - 1] === b[bEnd - 1]) {
          aEnd--;
          bEnd--;
        }
        if (aEnd === aStart) {
          const node2 = bEnd < bLength ? bStart ? b[bStart - 1].nextSibling : b[bEnd - bStart] : after;
          while (bStart < bEnd) parentNode.insertBefore(b[bStart++], node2);
        } else if (bEnd === bStart) {
          while (aStart < aEnd) {
            if (!map2 || !map2.has(a[aStart])) a[aStart].remove();
            aStart++;
          }
        } else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
          const node2 = a[--aEnd].nextSibling;
          parentNode.insertBefore(b[bStart++], a[aStart++].nextSibling);
          parentNode.insertBefore(b[--bEnd], node2);
          a[aEnd] = b[bEnd];
        } else {
          if (!map2) {
            map2 = /* @__PURE__ */ new Map();
            let i2 = bStart;
            while (i2 < bEnd) map2.set(b[i2], i2++);
          }
          const index2 = map2.get(a[aStart]);
          if (index2 != null) {
            if (bStart < index2 && index2 < bEnd) {
              let i2 = aStart, sequence = 1, t2;
              while (++i2 < aEnd && i2 < bEnd) {
                if ((t2 = map2.get(a[i2])) == null || t2 !== index2 + sequence) break;
                sequence++;
              }
              if (sequence > index2 - bStart) {
                const node2 = a[aStart];
                while (bStart < index2) parentNode.insertBefore(b[bStart++], node2);
              } else parentNode.replaceChild(b[bStart++], a[aStart++]);
            } else aStart++;
          } else a[aStart++].remove();
        }
      }
    }
    const $$EVENTS = "_$DX_DELEGATE";
    function render(code2, element, init, options2 = {}) {
      let disposer;
      createRoot((dispose2) => {
        disposer = dispose2;
        element === document ? code2() : insert(element, code2(), element.firstChild ? null : void 0, init);
      }, options2.owner);
      return () => {
        disposer();
        element.textContent = "";
      };
    }
    function template(html, check, isSVG) {
      const t2 = document.createElement("template");
      t2.innerHTML = html;
      let node2 = t2.content.firstChild;
      return node2;
    }
    function delegateEvents(eventNames, document2 = window.document) {
      const e = document2[$$EVENTS] || (document2[$$EVENTS] = /* @__PURE__ */ new Set());
      for (let i2 = 0, l = eventNames.length; i2 < l; i2++) {
        const name2 = eventNames[i2];
        if (!e.has(name2)) {
          e.add(name2);
          document2.addEventListener(name2, eventHandler);
        }
      }
    }
    function setAttribute(node2, name2, value2) {
      node2.removeAttribute(name2);
    }
    function className(node2, value2) {
      if (value2 == null) node2.removeAttribute("class");
      else node2.className = value2;
    }
    function addEventListener(node2, name2, handler, delegate) {
      {
        if (Array.isArray(handler)) {
          node2[`$$${name2}`] = handler[0];
          node2[`$$${name2}Data`] = handler[1];
        } else node2[`$$${name2}`] = handler;
      }
    }
    function style(node2, value2, prev) {
      if (!value2) return prev ? setAttribute(node2, "style") : value2;
      const nodeStyle = node2.style;
      if (typeof value2 === "string") return nodeStyle.cssText = value2;
      typeof prev === "string" && (nodeStyle.cssText = prev = void 0);
      prev || (prev = {});
      value2 || (value2 = {});
      let v, s;
      for (s in prev) {
        value2[s] == null && nodeStyle.removeProperty(s);
        delete prev[s];
      }
      for (s in value2) {
        v = value2[s];
        if (v !== prev[s]) {
          nodeStyle.setProperty(s, v);
          prev[s] = v;
        }
      }
      return prev;
    }
    function use(fn2, element, arg) {
      return untrack(() => fn2(element, arg));
    }
    function insert(parent, accessor, marker, initial) {
      if (marker !== void 0 && !initial) initial = [];
      if (typeof accessor !== "function") return insertExpression(parent, accessor, initial, marker);
      createRenderEffect((current) => insertExpression(parent, accessor(), current, marker), initial);
    }
    function eventHandler(e) {
      const key2 = `$$${e.type}`;
      let node2 = e.composedPath && e.composedPath()[0] || e.target;
      if (e.target !== node2) {
        Object.defineProperty(e, "target", {
          configurable: true,
          value: node2
        });
      }
      Object.defineProperty(e, "currentTarget", {
        configurable: true,
        get() {
          return node2 || document;
        }
      });
      if (sharedConfig.registry && !sharedConfig.done) {
        sharedConfig.done = true;
        document.querySelectorAll("[id^=pl-]").forEach((elem) => {
          while (elem && elem.nodeType !== 8 && elem.nodeValue !== "pl-" + e) {
            let x2 = elem.nextSibling;
            elem.remove();
            elem = x2;
          }
          elem && elem.remove();
        });
      }
      while (node2) {
        const handler = node2[key2];
        if (handler && !node2.disabled) {
          const data = node2[`${key2}Data`];
          data !== void 0 ? handler.call(node2, data, e) : handler.call(node2, e);
          if (e.cancelBubble) return;
        }
        node2 = node2._$host || node2.parentNode || node2.host;
      }
    }
    function insertExpression(parent, value2, current, marker, unwrapArray) {
      if (sharedConfig.context && !current) current = [...parent.childNodes];
      while (typeof current === "function") current = current();
      if (value2 === current) return current;
      const t2 = typeof value2, multi = marker !== void 0;
      parent = multi && current[0] && current[0].parentNode || parent;
      if (t2 === "string" || t2 === "number") {
        if (sharedConfig.context) return current;
        if (t2 === "number") value2 = value2.toString();
        if (multi) {
          let node2 = current[0];
          if (node2 && node2.nodeType === 3) {
            node2.data = value2;
          } else node2 = document.createTextNode(value2);
          current = cleanChildren(parent, current, marker, node2);
        } else {
          if (current !== "" && typeof current === "string") {
            current = parent.firstChild.data = value2;
          } else current = parent.textContent = value2;
        }
      } else if (value2 == null || t2 === "boolean") {
        if (sharedConfig.context) return current;
        current = cleanChildren(parent, current, marker);
      } else if (t2 === "function") {
        createRenderEffect(() => {
          let v = value2();
          while (typeof v === "function") v = v();
          current = insertExpression(parent, v, current, marker);
        });
        return () => current;
      } else if (Array.isArray(value2)) {
        const array = [];
        const currentArray = current && Array.isArray(current);
        if (normalizeIncomingArray(array, value2, current, unwrapArray)) {
          createRenderEffect(() => current = insertExpression(parent, array, current, marker, true));
          return () => current;
        }
        if (sharedConfig.context) {
          if (!array.length) return current;
          for (let i2 = 0; i2 < array.length; i2++) {
            if (array[i2].parentNode) return current = array;
          }
        }
        if (array.length === 0) {
          current = cleanChildren(parent, current, marker);
          if (multi) return current;
        } else if (currentArray) {
          if (current.length === 0) {
            appendNodes(parent, array, marker);
          } else reconcileArrays(parent, current, array);
        } else {
          current && cleanChildren(parent);
          appendNodes(parent, array);
        }
        current = array;
      } else if (value2 instanceof Node) {
        if (sharedConfig.context && value2.parentNode) return current = multi ? [value2] : value2;
        if (Array.isArray(current)) {
          if (multi) return current = cleanChildren(parent, current, marker, value2);
          cleanChildren(parent, current, null, value2);
        } else if (current == null || current === "" || !parent.firstChild) {
          parent.appendChild(value2);
        } else parent.replaceChild(value2, parent.firstChild);
        current = value2;
      } else ;
      return current;
    }
    function normalizeIncomingArray(normalized, array, current, unwrap2) {
      let dynamic = false;
      for (let i2 = 0, len = array.length; i2 < len; i2++) {
        let item2 = array[i2], prev = current && current[i2];
        if (item2 instanceof Node) {
          normalized.push(item2);
        } else if (item2 == null || item2 === true || item2 === false) ;
        else if (Array.isArray(item2)) {
          dynamic = normalizeIncomingArray(normalized, item2, prev) || dynamic;
        } else if (typeof item2 === "function") {
          if (unwrap2) {
            while (typeof item2 === "function") item2 = item2();
            dynamic = normalizeIncomingArray(normalized, Array.isArray(item2) ? item2 : [item2], Array.isArray(prev) ? prev : [prev]) || dynamic;
          } else {
            normalized.push(item2);
            dynamic = true;
          }
        } else {
          const value2 = String(item2);
          if (prev && prev.nodeType === 3 && prev.data === value2) {
            normalized.push(prev);
          } else normalized.push(document.createTextNode(value2));
        }
      }
      return dynamic;
    }
    function appendNodes(parent, array, marker = null) {
      for (let i2 = 0, len = array.length; i2 < len; i2++) parent.insertBefore(array[i2], marker);
    }
    function cleanChildren(parent, current, marker, replacement) {
      if (marker === void 0) return parent.textContent = "";
      const node2 = replacement || document.createTextNode("");
      if (current.length) {
        let inserted = false;
        for (let i2 = current.length - 1; i2 >= 0; i2--) {
          const el = current[i2];
          if (node2 !== el) {
            const isParent2 = el.parentNode === parent;
            if (!inserted && !i2) isParent2 ? parent.replaceChild(node2, el) : parent.insertBefore(node2, marker);
            else isParent2 && el.remove();
          } else inserted = true;
        }
      } else parent.insertBefore(node2, marker);
      return [node2];
    }
    const $RAW = Symbol("store-raw"), $NODE = Symbol("store-node"), $NAME = Symbol("store-name");
    function wrap$1(value2, name2) {
      let p = value2[$PROXY];
      if (!p) {
        Object.defineProperty(value2, $PROXY, {
          value: p = new Proxy(value2, proxyTraps$1)
        });
        if (!Array.isArray(value2)) {
          const keys = Object.keys(value2), desc = Object.getOwnPropertyDescriptors(value2);
          for (let i2 = 0, l = keys.length; i2 < l; i2++) {
            const prop = keys[i2];
            if (desc[prop].get) {
              Object.defineProperty(value2, prop, {
                enumerable: desc[prop].enumerable,
                get: desc[prop].get.bind(p)
              });
            }
          }
        }
      }
      return p;
    }
    function isWrappable(obj) {
      let proto;
      return obj != null && typeof obj === "object" && (obj[$PROXY] || !(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype || Array.isArray(obj));
    }
    function unwrap(item2, set = /* @__PURE__ */ new Set()) {
      let result2, unwrapped, v, prop;
      if (result2 = item2 != null && item2[$RAW]) return result2;
      if (!isWrappable(item2) || set.has(item2)) return item2;
      if (Array.isArray(item2)) {
        if (Object.isFrozen(item2)) item2 = item2.slice(0);
        else set.add(item2);
        for (let i2 = 0, l = item2.length; i2 < l; i2++) {
          v = item2[i2];
          if ((unwrapped = unwrap(v, set)) !== v) item2[i2] = unwrapped;
        }
      } else {
        if (Object.isFrozen(item2)) item2 = Object.assign({}, item2);
        else set.add(item2);
        const keys = Object.keys(item2), desc = Object.getOwnPropertyDescriptors(item2);
        for (let i2 = 0, l = keys.length; i2 < l; i2++) {
          prop = keys[i2];
          if (desc[prop].get) continue;
          v = item2[prop];
          if ((unwrapped = unwrap(v, set)) !== v) item2[prop] = unwrapped;
        }
      }
      return item2;
    }
    function getDataNodes(target2) {
      let nodes = target2[$NODE];
      if (!nodes) Object.defineProperty(target2, $NODE, {
        value: nodes = {}
      });
      return nodes;
    }
    function getDataNode(nodes, property, value2) {
      return nodes[property] || (nodes[property] = createDataNode(value2));
    }
    function proxyDescriptor$1(target2, property) {
      const desc = Reflect.getOwnPropertyDescriptor(target2, property);
      if (!desc || desc.get || !desc.configurable || property === $PROXY || property === $NODE || property === $NAME) return desc;
      delete desc.value;
      delete desc.writable;
      desc.get = () => target2[$PROXY][property];
      return desc;
    }
    function trackSelf(target2) {
      if (getListener()) {
        const nodes = getDataNodes(target2);
        (nodes._ || (nodes._ = createDataNode()))();
      }
    }
    function ownKeys(target2) {
      trackSelf(target2);
      return Reflect.ownKeys(target2);
    }
    function createDataNode(value2) {
      const [s, set] = createSignal(value2, {
        equals: false,
        internal: true
      });
      s.$ = set;
      return s;
    }
    const proxyTraps$1 = {
      get(target2, property, receiver) {
        if (property === $RAW) return target2;
        if (property === $PROXY) return receiver;
        if (property === $TRACK) {
          trackSelf(target2);
          return receiver;
        }
        const nodes = getDataNodes(target2);
        const tracked = nodes.hasOwnProperty(property);
        let value2 = tracked ? nodes[property]() : target2[property];
        if (property === $NODE || property === "__proto__") return value2;
        if (!tracked) {
          const desc = Object.getOwnPropertyDescriptor(target2, property);
          if (getListener() && (typeof value2 !== "function" || target2.hasOwnProperty(property)) && !(desc && desc.get)) value2 = getDataNode(nodes, property, value2)();
        }
        return isWrappable(value2) ? wrap$1(value2) : value2;
      },
      has(target2, property) {
        if (property === $RAW || property === $PROXY || property === $TRACK || property === $NODE || property === "__proto__") return true;
        this.get(target2, property, target2);
        return property in target2;
      },
      set() {
        return true;
      },
      deleteProperty() {
        return true;
      },
      ownKeys,
      getOwnPropertyDescriptor: proxyDescriptor$1
    };
    function setProperty(state, property, value2, deleting = false) {
      if (!deleting && state[property] === value2) return;
      const prev = state[property], len = state.length;
      if (value2 === void 0) delete state[property];
      else state[property] = value2;
      let nodes = getDataNodes(state), node2;
      if (node2 = getDataNode(nodes, property, prev)) node2.$(() => value2);
      if (Array.isArray(state) && state.length !== len) (node2 = getDataNode(nodes, "length", len)) && node2.$(state.length);
      (node2 = nodes._) && node2.$();
    }
    function mergeStoreNode(state, value2) {
      const keys = Object.keys(value2);
      for (let i2 = 0; i2 < keys.length; i2 += 1) {
        const key2 = keys[i2];
        setProperty(state, key2, value2[key2]);
      }
    }
    function updateArray(current, next) {
      if (typeof next === "function") next = next(current);
      next = unwrap(next);
      if (Array.isArray(next)) {
        if (current === next) return;
        let i2 = 0, len = next.length;
        for (; i2 < len; i2++) {
          const value2 = next[i2];
          if (current[i2] !== value2) setProperty(current, i2, value2);
        }
        setProperty(current, "length", len);
      } else mergeStoreNode(current, next);
    }
    function updatePath(current, path, traversed = []) {
      let part, prev = current;
      if (path.length > 1) {
        part = path.shift();
        const partType = typeof part, isArray = Array.isArray(current);
        if (Array.isArray(part)) {
          for (let i2 = 0; i2 < part.length; i2++) {
            updatePath(current, [part[i2]].concat(path), traversed);
          }
          return;
        } else if (isArray && partType === "function") {
          for (let i2 = 0; i2 < current.length; i2++) {
            if (part(current[i2], i2)) updatePath(current, [i2].concat(path), traversed);
          }
          return;
        } else if (isArray && partType === "object") {
          const {
            from = 0,
            to: to2 = current.length - 1,
            by = 1
          } = part;
          for (let i2 = from; i2 <= to2; i2 += by) {
            updatePath(current, [i2].concat(path), traversed);
          }
          return;
        } else if (path.length > 1) {
          updatePath(current[part], path, [part].concat(traversed));
          return;
        }
        prev = current[part];
        traversed = [part].concat(traversed);
      }
      let value2 = path[0];
      if (typeof value2 === "function") {
        value2 = value2(prev, traversed);
        if (value2 === prev) return;
      }
      if (part === void 0 && value2 == void 0) return;
      value2 = unwrap(value2);
      if (part === void 0 || isWrappable(prev) && isWrappable(value2) && !Array.isArray(value2)) {
        mergeStoreNode(prev, value2);
      } else setProperty(current, part, value2);
    }
    function createStore(...[store, options2]) {
      const unwrappedStore = unwrap(store || {});
      const isArray = Array.isArray(unwrappedStore);
      const wrappedStore = wrap$1(unwrappedStore);
      function setStore(...args) {
        batch(() => {
          isArray && args.length === 1 ? updateArray(unwrappedStore, args[0]) : updatePath(unwrappedStore, args);
        });
      }
      return [wrappedStore, setStore];
    }
    const $ROOT = Symbol("store-root");
    function applyState(target2, parent, property, merge, key2) {
      const previous = parent[property];
      if (target2 === previous) return;
      if (!isWrappable(target2) || !isWrappable(previous) || key2 && target2[key2] !== previous[key2]) {
        if (target2 !== previous) {
          if (property === $ROOT) return target2;
          setProperty(parent, property, target2);
        }
        return;
      }
      if (Array.isArray(target2)) {
        if (target2.length && previous.length && (!merge || key2 && target2[0] && target2[0][key2] != null)) {
          let i2, j2, start, end, newEnd, item2, newIndicesNext, keyVal;
          for (start = 0, end = Math.min(previous.length, target2.length); start < end && (previous[start] === target2[start] || key2 && previous[start] && target2[start] && previous[start][key2] === target2[start][key2]); start++) {
            applyState(target2[start], previous, start, merge, key2);
          }
          const temp = new Array(target2.length), newIndices = /* @__PURE__ */ new Map();
          for (end = previous.length - 1, newEnd = target2.length - 1; end >= start && newEnd >= start && (previous[end] === target2[newEnd] || key2 && previous[start] && target2[start] && previous[end][key2] === target2[newEnd][key2]); end--, newEnd--) {
            temp[newEnd] = previous[end];
          }
          if (start > newEnd || start > end) {
            for (j2 = start; j2 <= newEnd; j2++) setProperty(previous, j2, target2[j2]);
            for (; j2 < target2.length; j2++) {
              setProperty(previous, j2, temp[j2]);
              applyState(target2[j2], previous, j2, merge, key2);
            }
            if (previous.length > target2.length) setProperty(previous, "length", target2.length);
            return;
          }
          newIndicesNext = new Array(newEnd + 1);
          for (j2 = newEnd; j2 >= start; j2--) {
            item2 = target2[j2];
            keyVal = key2 && item2 ? item2[key2] : item2;
            i2 = newIndices.get(keyVal);
            newIndicesNext[j2] = i2 === void 0 ? -1 : i2;
            newIndices.set(keyVal, j2);
          }
          for (i2 = start; i2 <= end; i2++) {
            item2 = previous[i2];
            keyVal = key2 && item2 ? item2[key2] : item2;
            j2 = newIndices.get(keyVal);
            if (j2 !== void 0 && j2 !== -1) {
              temp[j2] = previous[i2];
              j2 = newIndicesNext[j2];
              newIndices.set(keyVal, j2);
            }
          }
          for (j2 = start; j2 < target2.length; j2++) {
            if (j2 in temp) {
              setProperty(previous, j2, temp[j2]);
              applyState(target2[j2], previous, j2, merge, key2);
            } else setProperty(previous, j2, target2[j2]);
          }
        } else {
          for (let i2 = 0, len = target2.length; i2 < len; i2++) {
            applyState(target2[i2], previous, i2, merge, key2);
          }
        }
        if (previous.length > target2.length) setProperty(previous, "length", target2.length);
        return;
      }
      const targetKeys = Object.keys(target2);
      for (let i2 = 0, len = targetKeys.length; i2 < len; i2++) {
        applyState(target2[targetKeys[i2]], previous, targetKeys[i2], merge, key2);
      }
      const previousKeys = Object.keys(previous);
      for (let i2 = 0, len = previousKeys.length; i2 < len; i2++) {
        if (target2[previousKeys[i2]] === void 0) setProperty(previous, previousKeys[i2], void 0);
      }
    }
    function reconcile(value2, options2 = {}) {
      const {
        merge,
        key: key2 = "id"
      } = options2, v = unwrap(value2);
      return (state) => {
        if (!isWrappable(state) || !isWrappable(v)) return v;
        const res = applyState(v, {
          [$ROOT]: state
        }, $ROOT, merge, key2);
        return res === void 0 ? state : res;
      };
    }
    const _tmpl$$9 = /* @__PURE__ */ template(`<span></span>`);
    var Segment = (props) => {
      const codePoint = createMemo(() => {
        if (props.text.length == 1) {
          const cp = props.text.codePointAt(0);
          if (cp >= 9600 && cp <= 9631 || cp == 57520 || cp == 57522) {
            return cp;
          }
        }
      });
      const text2 = createMemo(() => codePoint() ? " " : props.text);
      const style$12 = createMemo(() => buildStyle(props.pen, props.offset, props.width));
      const className$1 = createMemo(() => buildClassName(props.pen, codePoint(), props.extraClass));
      return (() => {
        const _el$ = _tmpl$$9.cloneNode(true);
        insert(_el$, text2);
        createRenderEffect((_p$) => {
          const _v$ = className$1(), _v$2 = style$12();
          _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
          _p$._v$2 = style(_el$, _v$2, _p$._v$2);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0
        });
        return _el$;
      })();
    };
    function buildClassName(attrs, codePoint, extraClass) {
      const fgClass = colorClass(attrs.get("fg"), attrs.get("bold"), "fg-");
      const bgClass = colorClass(attrs.get("bg"), false, "bg-");
      let cls = extraClass ?? "";
      if (codePoint !== void 0) {
        cls += ` cp-${codePoint.toString(16)}`;
      }
      if (fgClass) {
        cls += " " + fgClass;
      }
      if (bgClass) {
        cls += " " + bgClass;
      }
      if (attrs.has("bold")) {
        cls += " ap-bright";
      }
      if (attrs.has("faint")) {
        cls += " ap-faint";
      }
      if (attrs.has("italic")) {
        cls += " ap-italic";
      }
      if (attrs.has("underline")) {
        cls += " ap-underline";
      }
      if (attrs.has("blink")) {
        cls += " ap-blink";
      }
      if (attrs.get("inverse")) {
        cls += " ap-inverse";
      }
      return cls;
    }
    function colorClass(color, intense, prefix2) {
      if (typeof color === "number") {
        if (intense && color < 8) {
          color += 8;
        }
        return `${prefix2}${color}`;
      }
    }
    function buildStyle(attrs, offset, width) {
      const fg = attrs.get("fg");
      const bg = attrs.get("bg");
      let style2 = {
        "--offset": offset,
        width: `${width + 0.01}ch`
      };
      if (typeof fg === "string") {
        style2["--fg"] = fg;
      }
      if (typeof bg === "string") {
        style2["--bg"] = bg;
      }
      return style2;
    }
    const _tmpl$$8 = /* @__PURE__ */ template(`<span class="ap-line" role="paragraph"></span>`);
    var Line = (props) => {
      const segments = () => {
        if (typeof props.cursor === "number") {
          const segs = [];
          let len = 0;
          let i2 = 0;
          while (i2 < props.segments.length && len + props.segments[i2].text.length - 1 < props.cursor) {
            const seg = props.segments[i2];
            segs.push(seg);
            len += seg.text.length;
            i2++;
          }
          if (i2 < props.segments.length) {
            const seg = props.segments[i2];
            const pos2 = props.cursor - len;
            if (pos2 > 0) {
              segs.push({
                ...seg,
                text: seg.text.substring(0, pos2)
              });
            }
            segs.push({
              ...seg,
              text: seg.text[pos2],
              offset: seg.offset + pos2,
              extraClass: "ap-cursor"
            });
            if (pos2 < seg.text.length - 1) {
              segs.push({
                ...seg,
                text: seg.text.substring(pos2 + 1),
                offset: seg.offset + pos2 + 1
              });
            }
            i2++;
            while (i2 < props.segments.length) {
              const seg2 = props.segments[i2];
              segs.push(seg2);
              i2++;
            }
          }
          return segs;
        } else {
          return props.segments;
        }
      };
      return (() => {
        const _el$ = _tmpl$$8.cloneNode(true);
        insert(_el$, createComponent(Index, {
          get each() {
            return segments();
          },
          children: (s) => createComponent(Segment, mergeProps(s))
        }));
        return _el$;
      })();
    };
    const _tmpl$$7 = /* @__PURE__ */ template(`<pre class="ap-terminal" aria-live="polite" tabindex="0"></pre>`);
    var Terminal = (props) => {
      const lineHeight = () => props.lineHeight ?? 1.3333333333;
      const style$12 = createMemo(() => {
        return {
          width: `${props.cols}ch`,
          height: `${lineHeight() * props.rows}em`,
          "font-size": `${(props.scale || 1) * 100}%`,
          "font-family": props.fontFamily,
          "--term-line-height": `${lineHeight()}em`,
          "--term-cols": props.cols
        };
      });
      const cursorCol = createMemo(() => {
        var _a2;
        return (_a2 = props.cursor) == null ? void 0 : _a2[0];
      });
      const cursorRow = createMemo(() => {
        var _a2;
        return (_a2 = props.cursor) == null ? void 0 : _a2[1];
      });
      return (() => {
        const _el$ = _tmpl$$7.cloneNode(true);
        const _ref$ = props.ref;
        typeof _ref$ === "function" ? use(_ref$, _el$) : props.ref = _el$;
        insert(_el$, createComponent(For, {
          get each() {
            return props.lines;
          },
          children: (line2, i2) => createComponent(Line, {
            get segments() {
              return line2.segments;
            },
            get cursor() {
              return createMemo(() => i2() === cursorRow())() ? cursorCol() : null;
            }
          })
        }));
        createRenderEffect((_p$) => {
          const _v$ = !!(props.blink || props.cursorHold), _v$2 = !!props.blink, _v$3 = style$12();
          _v$ !== _p$._v$ && _el$.classList.toggle("ap-cursor-on", _p$._v$ = _v$);
          _v$2 !== _p$._v$2 && _el$.classList.toggle("ap-blink", _p$._v$2 = _v$2);
          _p$._v$3 = style(_el$, _v$3, _p$._v$3);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0,
          _v$3: void 0
        });
        return _el$;
      })();
    };
    const _tmpl$$6 = /* @__PURE__ */ template(`<svg version="1.1" viewBox="0 0 12 12" class="ap-icon" aria-label="Pause" role="button"><path d="M1,0 L4,0 L4,12 L1,12 Z"></path><path d="M8,0 L11,0 L11,12 L8,12 Z"></path></svg>`), _tmpl$2 = /* @__PURE__ */ template(`<svg version="1.1" viewBox="0 0 12 12" class="ap-icon" aria-label="Play" role="button"><path d="M1,0 L11,6 L1,12 Z"></path></svg>`), _tmpl$3 = /* @__PURE__ */ template(`<span class="ap-button ap-playback-button" tabindex="0"></span>`), _tmpl$4 = /* @__PURE__ */ template(`<span class="ap-bar"><span class="ap-gutter ap-gutter-empty"></span><span class="ap-gutter ap-gutter-full"></span></span>`), _tmpl$5 = /* @__PURE__ */ template(`<div class="ap-control-bar"><span class="ap-timer" aria-readonly="true" role="textbox" tabindex="0"><span class="ap-time-elapsed"></span><span class="ap-time-remaining"></span></span><span class="ap-progressbar"></span><span class="ap-button ap-kbd-button ap-tooltip-container" aria-label="Show keyboard shortcuts" role="button" tabindex="0"><svg version="1.1" viewBox="6 8 14 16" class="ap-icon"><path d="M0.938 8.313h22.125c0.5 0 0.938 0.438 0.938 0.938v13.5c0 0.5-0.438 0.938-0.938 0.938h-22.125c-0.5 0-0.938-0.438-0.938-0.938v-13.5c0-0.5 0.438-0.938 0.938-0.938zM1.594 22.063h20.813v-12.156h-20.813v12.156zM3.844 11.188h1.906v1.938h-1.906v-1.938zM7.469 11.188h1.906v1.938h-1.906v-1.938zM11.031 11.188h1.938v1.938h-1.938v-1.938zM14.656 11.188h1.875v1.938h-1.875v-1.938zM18.25 11.188h1.906v1.938h-1.906v-1.938zM5.656 15.031h1.938v1.938h-1.938v-1.938zM9.281 16.969v-1.938h1.906v1.938h-1.906zM12.875 16.969v-1.938h1.906v1.938h-1.906zM18.406 16.969h-1.938v-1.938h1.938v1.938zM16.531 20.781h-9.063v-1.906h9.063v1.906z"></path></svg><span class="ap-tooltip">Keyboard shortcuts (?)</span></span><span class="ap-button ap-fullscreen-button ap-tooltip-container" aria-label="Toggle fullscreen mode" role="button" tabindex="0"><svg version="1.1" viewBox="0 0 12 12" class="ap-icon ap-icon-fullscreen-on"><path d="M12,0 L7,0 L9,2 L7,4 L8,5 L10,3 L12,5 Z"></path><path d="M0,12 L0,7 L2,9 L4,7 L5,8 L3,10 L5,12 Z"></path></svg><svg version="1.1" viewBox="0 0 12 12" class="ap-icon ap-icon-fullscreen-off"><path d="M7,5 L7,0 L9,2 L11,0 L12,1 L10,3 L12,5 Z"></path><path d="M5,7 L0,7 L2,9 L0,11 L1,12 L3,10 L5,12 Z"></path></svg><span class="ap-tooltip">Fullscreen (f)</span></span></div>`), _tmpl$6 = /* @__PURE__ */ template(`<span class="ap-marker-container ap-tooltip-container"><span class="ap-marker"></span><span class="ap-tooltip"></span></span>`);
    function formatTime(seconds) {
      let s = Math.floor(seconds);
      const d = Math.floor(s / 86400);
      s %= 86400;
      const h = Math.floor(s / 3600);
      s %= 3600;
      const m = Math.floor(s / 60);
      s %= 60;
      if (d > 0) {
        return `${zeroPad(d)}:${zeroPad(h)}:${zeroPad(m)}:${zeroPad(s)}`;
      } else if (h > 0) {
        return `${zeroPad(h)}:${zeroPad(m)}:${zeroPad(s)}`;
      } else {
        return `${zeroPad(m)}:${zeroPad(s)}`;
      }
    }
    function zeroPad(n) {
      return n < 10 ? `0${n}` : n.toString();
    }
    var ControlBar = (props) => {
      const e = (f) => {
        return (e2) => {
          e2.preventDefault();
          f(e2);
        };
      };
      const currentTime = () => typeof props.currentTime === "number" ? formatTime(props.currentTime) : "--:--";
      const remainingTime = () => typeof props.remainingTime === "number" ? "-" + formatTime(props.remainingTime) : currentTime();
      const markers = createMemo(() => typeof props.duration === "number" ? props.markers.filter((m) => m[0] < props.duration) : []);
      const markerPosition = (m) => `${m[0] / props.duration * 100}%`;
      const markerText = (m) => {
        if (m[1] === "") {
          return formatTime(m[0]);
        } else {
          return `${formatTime(m[0])} - ${m[1]}`;
        }
      };
      const isPastMarker = (m) => typeof props.currentTime === "number" ? m[0] <= props.currentTime : false;
      const gutterBarStyle = () => {
        return {
          transform: `scaleX(${props.progress || 0}`
        };
      };
      const calcPosition = (e2) => {
        const barWidth = e2.currentTarget.offsetWidth;
        const rect = e2.currentTarget.getBoundingClientRect();
        const mouseX = e2.clientX - rect.left;
        const pos2 = Math.max(0, mouseX / barWidth);
        return `${pos2 * 100}%`;
      };
      const [mouseDown2, setMouseDown] = createSignal(false);
      const throttledSeek = throttle(props.onSeekClick, 50);
      const onMouseDown = (e2) => {
        if (e2._marker) return;
        if (e2.altKey || e2.shiftKey || e2.metaKey || e2.ctrlKey || e2.button !== 0) return;
        setMouseDown(true);
        props.onSeekClick(calcPosition(e2));
      };
      const seekToMarker = (index2) => {
        return e(() => {
          props.onSeekClick({
            marker: index2
          });
        });
      };
      const onMove = (e2) => {
        if (e2.altKey || e2.shiftKey || e2.metaKey || e2.ctrlKey) return;
        if (mouseDown2()) {
          throttledSeek(calcPosition(e2));
        }
      };
      const onDocumentMouseUp = () => {
        setMouseDown(false);
      };
      document.addEventListener("mouseup", onDocumentMouseUp);
      onCleanup(() => {
        document.removeEventListener("mouseup", onDocumentMouseUp);
      });
      return (() => {
        const _el$ = _tmpl$5.cloneNode(true), _el$5 = _el$.firstChild, _el$6 = _el$5.firstChild, _el$7 = _el$6.nextSibling, _el$8 = _el$5.nextSibling, _el$12 = _el$8.nextSibling, _el$13 = _el$12.nextSibling;
        const _ref$ = props.ref;
        typeof _ref$ === "function" ? use(_ref$, _el$) : props.ref = _el$;
        insert(_el$, createComponent(Show, {
          get when() {
            return props.isPausable;
          },
          get children() {
            const _el$2 = _tmpl$3.cloneNode(true);
            addEventListener(_el$2, "click", e(props.onPlayClick));
            insert(_el$2, createComponent(Switch, {
              get children() {
                return [createComponent(Match, {
                  get when() {
                    return props.isPlaying;
                  },
                  get children() {
                    return _tmpl$$6.cloneNode(true);
                  }
                }), createComponent(Match, {
                  get when() {
                    return !props.isPlaying;
                  },
                  get children() {
                    return _tmpl$2.cloneNode(true);
                  }
                })];
              }
            }));
            return _el$2;
          }
        }), _el$5);
        insert(_el$6, currentTime);
        insert(_el$7, remainingTime);
        insert(_el$8, createComponent(Show, {
          get when() {
            return typeof props.progress === "number" || props.isSeekable;
          },
          get children() {
            const _el$9 = _tmpl$4.cloneNode(true), _el$10 = _el$9.firstChild, _el$11 = _el$10.nextSibling;
            _el$9.$$mousemove = onMove;
            _el$9.$$mousedown = onMouseDown;
            insert(_el$9, createComponent(For, {
              get each() {
                return markers();
              },
              children: (m, i2) => (() => {
                const _el$14 = _tmpl$6.cloneNode(true), _el$15 = _el$14.firstChild, _el$16 = _el$15.nextSibling;
                _el$14.$$mousedown = (e2) => {
                  e2._marker = true;
                };
                addEventListener(_el$14, "click", seekToMarker(i2()));
                insert(_el$16, () => markerText(m));
                createRenderEffect((_p$) => {
                  const _v$ = markerPosition(m), _v$2 = !!isPastMarker(m);
                  _v$ !== _p$._v$ && _el$14.style.setProperty("left", _p$._v$ = _v$);
                  _v$2 !== _p$._v$2 && _el$15.classList.toggle("ap-marker-past", _p$._v$2 = _v$2);
                  return _p$;
                }, {
                  _v$: void 0,
                  _v$2: void 0
                });
                return _el$14;
              })()
            }), null);
            createRenderEffect((_$p) => style(_el$11, gutterBarStyle(), _$p));
            return _el$9;
          }
        }));
        addEventListener(_el$12, "click", e(props.onHelpClick));
        addEventListener(_el$13, "click", e(props.onFullscreenClick));
        createRenderEffect(() => _el$.classList.toggle("ap-seekable", !!props.isSeekable));
        return _el$;
      })();
    };
    delegateEvents(["click", "mousedown", "mousemove"]);
    const _tmpl$$5 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-error"><span>💥</span></div>`);
    var ErrorOverlay = (props) => {
      return _tmpl$$5.cloneNode(true);
    };
    const _tmpl$$4 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-loading"><span class="ap-loader"></span></div>`);
    var LoaderOverlay = (props) => {
      return _tmpl$$4.cloneNode(true);
    };
    const _tmpl$$3 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-info"><span></span></div>`);
    var InfoOverlay = (props) => {
      const style$12 = () => {
        return {
          "font-family": props.fontFamily
        };
      };
      return (() => {
        const _el$ = _tmpl$$3.cloneNode(true), _el$2 = _el$.firstChild;
        insert(_el$2, () => props.message);
        createRenderEffect((_$p) => style(_el$2, style$12(), _$p));
        return _el$;
      })();
    };
    const _tmpl$$2 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-start"><div class="ap-play-button"><div><span><svg version="1.1" viewBox="0 0 1000.0 1000.0" class="ap-icon"><defs><mask id="small-triangle-mask"><rect width="100%" height="100%" fill="white"></rect><polygon points="700.0 500.0, 400.00000000000006 326.7949192431122, 399.9999999999999 673.2050807568877" fill="black"></polygon></mask></defs><polygon points="1000.0 500.0, 250.0000000000001 66.98729810778059, 249.99999999999977 933.0127018922192" mask="url(#small-triangle-mask)" fill="white" class="ap-play-btn-fill"></polygon><polyline points="673.2050807568878 400.0, 326.7949192431123 600.0" stroke="white" stroke-width="90" class="ap-play-btn-stroke"></polyline></svg></span></div></div></div>`);
    var StartOverlay = (props) => {
      const e = (f) => {
        return (e2) => {
          e2.preventDefault();
          f(e2);
        };
      };
      return (() => {
        const _el$ = _tmpl$$2.cloneNode(true);
        addEventListener(_el$, "click", e(props.onClick));
        return _el$;
      })();
    };
    delegateEvents(["click"]);
    const _tmpl$$1 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-help"><div><div><p>Keyboard shortcuts</p><ul><li><kbd>space</kbd> - pause / resume</li><li><kbd>f</kbd> - toggle fullscreen mode</li><li><kbd>←</kbd> / <kbd>→</kbd> - rewind / fast-forward by 5 seconds</li><li><kbd>Shift</kbd> + <kbd>←</kbd> / <kbd>→</kbd> - rewind / fast-forward by 10%</li><li><kbd>[</kbd> / <kbd>]</kbd> - jump to the previous / next marker</li><li><kbd>0</kbd>, <kbd>1</kbd>, <kbd>2</kbd> ... <kbd>9</kbd> - jump to 0%, 10%, 20% ... 90%</li><li><kbd>,</kbd> / <kbd>.</kbd> - step back / forward, a frame at a time (when paused)</li><li><kbd>?</kbd> - toggle this help popup</li></ul></div></div></div>`);
    var HelpOverlay = (props) => {
      const style$12 = () => {
        return {
          "font-family": props.fontFamily
        };
      };
      const e = (f) => {
        return (e2) => {
          e2.preventDefault();
          f(e2);
        };
      };
      return (() => {
        const _el$ = _tmpl$$1.cloneNode(true), _el$2 = _el$.firstChild;
        addEventListener(_el$, "click", e(props.onClose));
        _el$2.$$click = (e2) => {
          e2.stopPropagation();
        };
        createRenderEffect((_$p) => style(_el$, style$12(), _$p));
        return _el$;
      })();
    };
    delegateEvents(["click"]);
    const _tmpl$ = /* @__PURE__ */ template(`<div class="ap-wrapper" tabindex="-1"><div></div></div>`);
    const CONTROL_BAR_HEIGHT = 32;
    var Player = (props) => {
      const logger = props.logger;
      const core = props.core;
      const autoPlay = props.autoPlay;
      const [state, setState] = createStore({
        lines: [],
        cursor: void 0,
        charW: props.charW,
        charH: props.charH,
        bordersW: props.bordersW,
        bordersH: props.bordersH,
        containerW: 0,
        containerH: 0,
        isPausable: true,
        isSeekable: true,
        isFullscreen: false,
        currentTime: null,
        remainingTime: null,
        progress: null,
        blink: true,
        cursorHold: false
      });
      const [isPlaying, setIsPlaying] = createSignal(false);
      const [overlay, setOverlay] = createSignal(!autoPlay ? "start" : null);
      const [infoMessage, setInfoMessage] = createSignal(null);
      const [terminalSize, setTerminalSize] = createSignal({
        cols: props.cols,
        rows: props.rows
      }, {
        equals: (newVal, oldVal) => newVal.cols === oldVal.cols && newVal.rows === oldVal.rows
      });
      const [duration, setDuration] = createSignal(void 0);
      const [markers, setMarkers] = createStore([]);
      const [userActive, setUserActive] = createSignal(false);
      const [isHelpVisible, setIsHelpVisible] = createSignal(false);
      const [originalTheme, setOriginalTheme] = createSignal(void 0);
      const terminalCols = createMemo(() => terminalSize().cols || 80);
      const terminalRows = createMemo(() => terminalSize().rows || 24);
      const controlBarHeight = () => props.controls === false ? 0 : CONTROL_BAR_HEIGHT;
      const controlsVisible = () => props.controls === true || props.controls === "auto" && userActive();
      let frameRequestId;
      let userActivityTimeoutId;
      let timeUpdateIntervalId;
      let blinkIntervalId;
      let wrapperRef;
      let playerRef;
      let terminalRef;
      let controlBarRef;
      let resizeObserver;
      function onPlaying() {
        updateTerminal();
        startBlinking();
        startTimeUpdates();
      }
      function onStopped() {
        stopBlinking();
        stopTimeUpdates();
        updateTime();
      }
      function resize(size_) {
        batch(() => {
          if (size_.rows < terminalSize().rows) {
            setState("lines", state.lines.slice(0, size_.rows));
          }
          setTerminalSize(size_);
        });
      }
      function setPoster(poster) {
        if (poster !== void 0 && !autoPlay) {
          setState({
            lines: poster.lines,
            cursor: poster.cursor
          });
        }
      }
      core.addEventListener("init", (_ref) => {
        let {
          cols,
          rows,
          duration: duration2,
          theme: theme3,
          poster,
          markers: markers2
        } = _ref;
        batch(() => {
          resize({
            cols,
            rows
          });
          setDuration(duration2);
          setOriginalTheme(theme3);
          setMarkers(markers2);
          setPoster(poster);
        });
      });
      core.addEventListener("play", () => {
        setOverlay(null);
      });
      core.addEventListener("playing", () => {
        batch(() => {
          setIsPlaying(true);
          setOverlay(null);
          onPlaying();
        });
      });
      core.addEventListener("idle", () => {
        batch(() => {
          setIsPlaying(false);
          onStopped();
        });
      });
      core.addEventListener("loading", () => {
        batch(() => {
          setIsPlaying(false);
          onStopped();
          setOverlay("loader");
        });
      });
      core.addEventListener("offline", (_ref2) => {
        let {
          message: message2
        } = _ref2;
        batch(() => {
          setIsPlaying(false);
          onStopped();
          if (message2 !== void 0) {
            setInfoMessage(message2);
            setOverlay("info");
          }
        });
      });
      let renderCount = 0;
      core.addEventListener("ended", (_ref3) => {
        let {
          message: message2
        } = _ref3;
        batch(() => {
          setIsPlaying(false);
          onStopped();
          if (message2 !== void 0) {
            setInfoMessage(message2);
            setOverlay("info");
          }
        });
        logger.debug(`view: render count: ${renderCount}`);
      });
      core.addEventListener("errored", () => {
        setOverlay("error");
      });
      core.addEventListener("resize", resize);
      core.addEventListener("reset", (_ref4) => {
        let {
          cols,
          rows,
          theme: theme3
        } = _ref4;
        batch(() => {
          resize({
            cols,
            rows
          });
          setOriginalTheme(theme3);
          updateTerminal();
        });
      });
      core.addEventListener("seeked", () => {
        updateTime();
      });
      core.addEventListener("terminalUpdate", () => {
        if (frameRequestId === void 0) {
          frameRequestId = requestAnimationFrame(updateTerminal);
        }
      });
      const setupResizeObserver = () => {
        resizeObserver = new ResizeObserver(debounce((_entries) => {
          setState({
            containerW: wrapperRef.offsetWidth,
            containerH: wrapperRef.offsetHeight
          });
          wrapperRef.dispatchEvent(new CustomEvent("resize", {
            detail: {
              el: playerRef
            }
          }));
        }, 10));
        resizeObserver.observe(wrapperRef);
      };
      onMount(async () => {
        logger.info("view: mounted");
        logger.debug("view: font measurements", {
          charW: state.charW,
          charH: state.charH
        });
        setupResizeObserver();
        const {
          isPausable,
          isSeekable,
          poster
        } = await core.init();
        batch(() => {
          setState({
            isPausable,
            isSeekable,
            containerW: wrapperRef.offsetWidth,
            containerH: wrapperRef.offsetHeight
          });
          setPoster(poster);
        });
        if (autoPlay) {
          core.play();
        }
      });
      onCleanup(() => {
        core.stop();
        stopBlinking();
        stopTimeUpdates();
        resizeObserver.disconnect();
      });
      const updateTerminal = async () => {
        const changes = await core.getChanges();
        batch(() => {
          if (changes.lines !== void 0) {
            changes.lines.forEach((line2, i2) => {
              setState("lines", i2, reconcile(line2));
            });
          }
          if (changes.cursor !== void 0) {
            setState("cursor", reconcile(changes.cursor));
          }
          setState("cursorHold", true);
        });
        frameRequestId = void 0;
        renderCount += 1;
      };
      const terminalElementSize = createMemo(() => {
        const terminalW = state.charW * terminalCols() + state.bordersW;
        const terminalH = state.charH * terminalRows() + state.bordersH;
        let fit = props.fit ?? "width";
        if (fit === "both" || state.isFullscreen) {
          const containerRatio = state.containerW / (state.containerH - controlBarHeight());
          const terminalRatio = terminalW / terminalH;
          if (containerRatio > terminalRatio) {
            fit = "height";
          } else {
            fit = "width";
          }
        }
        if (fit === false || fit === "none") {
          return {};
        } else if (fit === "width") {
          const scale = state.containerW / terminalW;
          return {
            scale,
            width: state.containerW,
            height: terminalH * scale + controlBarHeight()
          };
        } else if (fit === "height") {
          const scale = (state.containerH - controlBarHeight()) / terminalH;
          return {
            scale,
            width: terminalW * scale,
            height: state.containerH
          };
        } else {
          throw `unsupported fit mode: ${fit}`;
        }
      });
      const onFullscreenChange = () => {
        setState("isFullscreen", document.fullscreenElement ?? document.webkitFullscreenElement);
      };
      const toggleFullscreen = () => {
        if (state.isFullscreen) {
          (document.exitFullscreen ?? document.webkitExitFullscreen ?? (() => {
          })).apply(document);
        } else {
          (wrapperRef.requestFullscreen ?? wrapperRef.webkitRequestFullscreen ?? (() => {
          })).apply(wrapperRef);
        }
      };
      const toggleHelp = () => {
        if (isHelpVisible()) {
          setIsHelpVisible(false);
        } else {
          core.pause();
          setIsHelpVisible(true);
        }
      };
      const onKeyDown = (e) => {
        if (e.altKey || e.metaKey || e.ctrlKey) {
          return;
        }
        if (e.key == " ") {
          core.togglePlay();
        } else if (e.key == ",") {
          core.step(-1);
          updateTime();
        } else if (e.key == ".") {
          core.step();
          updateTime();
        } else if (e.key == "f") {
          toggleFullscreen();
        } else if (e.key == "[") {
          core.seek({
            marker: "prev"
          });
        } else if (e.key == "]") {
          core.seek({
            marker: "next"
          });
        } else if (e.key.charCodeAt(0) >= 48 && e.key.charCodeAt(0) <= 57) {
          const pos2 = (e.key.charCodeAt(0) - 48) / 10;
          core.seek(`${pos2 * 100}%`);
        } else if (e.key == "?") {
          toggleHelp();
        } else if (e.key == "ArrowLeft") {
          if (e.shiftKey) {
            core.seek("<<<");
          } else {
            core.seek("<<");
          }
        } else if (e.key == "ArrowRight") {
          if (e.shiftKey) {
            core.seek(">>>");
          } else {
            core.seek(">>");
          }
        } else if (e.key == "Escape") {
          setIsHelpVisible(false);
        } else {
          return;
        }
        e.stopPropagation();
        e.preventDefault();
      };
      const wrapperOnMouseMove = () => {
        if (state.isFullscreen) {
          onUserActive(true);
        }
      };
      const playerOnMouseLeave = () => {
        if (!state.isFullscreen) {
          onUserActive(false);
        }
      };
      const startTimeUpdates = () => {
        timeUpdateIntervalId = setInterval(updateTime, 100);
      };
      const stopTimeUpdates = () => {
        clearInterval(timeUpdateIntervalId);
      };
      const updateTime = async () => {
        const currentTime = await core.getCurrentTime();
        const remainingTime = await core.getRemainingTime();
        const progress2 = await core.getProgress();
        setState({
          currentTime,
          remainingTime,
          progress: progress2
        });
      };
      const startBlinking = () => {
        blinkIntervalId = setInterval(() => {
          setState((state2) => {
            const changes = {
              blink: !state2.blink
            };
            if (changes.blink) {
              changes.cursorHold = false;
            }
            return changes;
          });
        }, 500);
      };
      const stopBlinking = () => {
        clearInterval(blinkIntervalId);
        setState("blink", true);
      };
      const onUserActive = (show) => {
        clearTimeout(userActivityTimeoutId);
        if (show) {
          userActivityTimeoutId = setTimeout(() => onUserActive(false), 2e3);
        }
        setUserActive(show);
      };
      const theme2 = createMemo(() => {
        const name2 = props.theme || "auto/asciinema";
        if (name2.slice(0, 5) === "auto/") {
          return {
            name: name2.slice(5),
            colors: originalTheme()
          };
        } else {
          return {
            name: name2
          };
        }
      });
      const playerStyle = () => {
        const style2 = {};
        if ((props.fit === false || props.fit === "none") && props.terminalFontSize !== void 0) {
          if (props.terminalFontSize === "small") {
            style2["font-size"] = "12px";
          } else if (props.terminalFontSize === "medium") {
            style2["font-size"] = "18px";
          } else if (props.terminalFontSize === "big") {
            style2["font-size"] = "24px";
          } else {
            style2["font-size"] = props.terminalFontSize;
          }
        }
        const size = terminalElementSize();
        if (size.width !== void 0) {
          style2["width"] = `${size.width}px`;
          style2["height"] = `${size.height}px`;
        }
        const themeColors = theme2().colors;
        if (themeColors !== void 0) {
          style2["--term-color-foreground"] = themeColors.foreground;
          style2["--term-color-background"] = themeColors.background;
          themeColors.palette.forEach((color, i2) => {
            style2[`--term-color-${i2}`] = color;
          });
        }
        return style2;
      };
      const playerClass = () => `ap-player asciinema-player-theme-${theme2().name}`;
      const terminalScale = () => {
        var _a2;
        return (_a2 = terminalElementSize()) == null ? void 0 : _a2.scale;
      };
      const el = (() => {
        const _el$ = _tmpl$.cloneNode(true), _el$2 = _el$.firstChild;
        const _ref$ = wrapperRef;
        typeof _ref$ === "function" ? use(_ref$, _el$) : wrapperRef = _el$;
        _el$.addEventListener("webkitfullscreenchange", onFullscreenChange);
        _el$.addEventListener("fullscreenchange", onFullscreenChange);
        _el$.$$mousemove = wrapperOnMouseMove;
        _el$.$$keydown = onKeyDown;
        const _ref$2 = playerRef;
        typeof _ref$2 === "function" ? use(_ref$2, _el$2) : playerRef = _el$2;
        _el$2.$$mousemove = () => onUserActive(true);
        _el$2.addEventListener("mouseleave", playerOnMouseLeave);
        insert(_el$2, createComponent(Terminal, {
          get cols() {
            return terminalCols();
          },
          get rows() {
            return terminalRows();
          },
          get scale() {
            return terminalScale();
          },
          get blink() {
            return state.blink;
          },
          get lines() {
            return state.lines;
          },
          get cursor() {
            return state.cursor;
          },
          get cursorHold() {
            return state.cursorHold;
          },
          get fontFamily() {
            return props.terminalFontFamily;
          },
          get lineHeight() {
            return props.terminalLineHeight;
          },
          ref(r$) {
            const _ref$3 = terminalRef;
            typeof _ref$3 === "function" ? _ref$3(r$) : terminalRef = r$;
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return props.controls !== false;
          },
          get children() {
            return createComponent(ControlBar, {
              get duration() {
                return duration();
              },
              get currentTime() {
                return state.currentTime;
              },
              get remainingTime() {
                return state.remainingTime;
              },
              get progress() {
                return state.progress;
              },
              markers,
              get isPlaying() {
                return isPlaying();
              },
              get isPausable() {
                return state.isPausable;
              },
              get isSeekable() {
                return state.isSeekable;
              },
              onPlayClick: () => core.togglePlay(),
              onFullscreenClick: toggleFullscreen,
              onHelpClick: toggleHelp,
              onSeekClick: (pos2) => core.seek(pos2),
              ref(r$) {
                const _ref$4 = controlBarRef;
                typeof _ref$4 === "function" ? _ref$4(r$) : controlBarRef = r$;
              }
            });
          }
        }), null);
        insert(_el$2, createComponent(Switch, {
          get children() {
            return [createComponent(Match, {
              get when() {
                return overlay() == "start";
              },
              get children() {
                return createComponent(StartOverlay, {
                  onClick: () => core.play()
                });
              }
            }), createComponent(Match, {
              get when() {
                return overlay() == "loader";
              },
              get children() {
                return createComponent(LoaderOverlay, {});
              }
            }), createComponent(Match, {
              get when() {
                return overlay() == "info";
              },
              get children() {
                return createComponent(InfoOverlay, {
                  get message() {
                    return infoMessage();
                  },
                  get fontFamily() {
                    return props.terminalFontFamily;
                  }
                });
              }
            }), createComponent(Match, {
              get when() {
                return overlay() == "error";
              },
              get children() {
                return createComponent(ErrorOverlay, {});
              }
            })];
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return isHelpVisible();
          },
          get children() {
            return createComponent(HelpOverlay, {
              get fontFamily() {
                return props.terminalFontFamily;
              },
              onClose: () => setIsHelpVisible(false)
            });
          }
        }), null);
        createRenderEffect((_p$) => {
          const _v$ = !!controlsVisible(), _v$2 = playerClass(), _v$3 = playerStyle();
          _v$ !== _p$._v$ && _el$.classList.toggle("ap-hud", _p$._v$ = _v$);
          _v$2 !== _p$._v$2 && className(_el$2, _p$._v$2 = _v$2);
          _p$._v$3 = style(_el$2, _v$3, _p$._v$3);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0,
          _v$3: void 0
        });
        return _el$;
      })();
      return el;
    };
    delegateEvents(["keydown", "mousemove"]);
    function mount(core, elem) {
      let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      const metrics = measureTerminal(opts.terminalFontFamily, opts.terminalLineHeight);
      const props = {
        core,
        logger: opts.logger,
        cols: opts.cols,
        rows: opts.rows,
        fit: opts.fit,
        controls: opts.controls ?? "auto",
        autoPlay: opts.autoPlay ?? opts.autoplay,
        terminalFontSize: opts.terminalFontSize,
        terminalFontFamily: opts.terminalFontFamily,
        terminalLineHeight: opts.terminalLineHeight,
        theme: opts.theme,
        ...metrics
      };
      let el;
      const dispose2 = render(() => {
        el = createComponent(Player, props);
        return el;
      }, elem);
      const player = {
        el,
        dispose: dispose2,
        getCurrentTime: () => core.getCurrentTime(),
        getDuration: () => core.getDuration(),
        play: () => core.play(),
        pause: () => core.pause(),
        seek: (pos2) => core.seek(pos2)
      };
      player.addEventListener = (name2, callback) => {
        return core.addEventListener(name2, callback.bind(player));
      };
      return player;
    }
    function measureTerminal(fontFamily, lineHeight) {
      const cols = 80;
      const rows = 24;
      const div = document.createElement("div");
      div.style.height = "0px";
      div.style.overflow = "hidden";
      div.style.fontSize = "15px";
      document.body.appendChild(div);
      let el;
      const dispose2 = render(() => {
        el = createComponent(Terminal, {
          cols,
          rows,
          lineHeight,
          fontFamily,
          lines: []
        });
        return el;
      }, div);
      const metrics = {
        charW: el.clientWidth / cols,
        charH: el.clientHeight / rows,
        bordersW: el.offsetWidth - el.clientWidth,
        bordersH: el.offsetHeight - el.clientHeight
      };
      dispose2();
      document.body.removeChild(div);
      return metrics;
    }
    const CORE_OPTS = ["cols", "idleTimeLimit", "loop", "markers", "pauseOnMarkers", "poster", "preload", "rows", "speed", "startAt"];
    const UI_OPTS = ["autoPlay", "autoplay", "cols", "controls", "fit", "rows", "terminalFontFamily", "terminalFontSize", "terminalLineHeight", "theme"];
    function coreOpts(inputOpts) {
      let overrides = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      const opts = Object.fromEntries(Object.entries(inputOpts).filter((_ref) => {
        let [key2] = _ref;
        return CORE_OPTS.includes(key2);
      }));
      return {
        ...opts,
        ...overrides
      };
    }
    function uiOpts(inputOpts) {
      let overrides = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      const opts = Object.fromEntries(Object.entries(inputOpts).filter((_ref2) => {
        let [key2] = _ref2;
        return UI_OPTS.includes(key2);
      }));
      return {
        ...opts,
        ...overrides
      };
    }
    function create(src, elem) {
      let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      const logger = opts.logger ?? new DummyLogger();
      const core = new Core(src, coreOpts(opts, {
        logger
      }));
      return mount(core, elem, uiOpts(opts, {
        logger
      }));
    }
    const AsciinemaPlayer = ({
      id,
      rows,
      cols,
      inputUrl,
      outputUrl,
      timingUrl,
      fit,
      speed,
      autoPlay,
      loop,
      theme: theme2,
      idleTimeLimit = 2,
      style: style2
    }) => {
      const playerContainerRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        if (!playerContainerRef.current) return;
        const player = create(
          {
            url: [timingUrl, outputUrl, inputUrl],
            parser: "typescript"
          },
          playerContainerRef.current,
          {
            rows,
            cols,
            autoPlay,
            loop,
            theme: theme2,
            speed,
            idleTimeLimit,
            fit
          }
        );
        player.play();
        return () => {
          player.dispose();
        };
      }, [
        timingUrl,
        outputUrl,
        inputUrl,
        rows,
        cols,
        autoPlay,
        loop,
        theme2,
        speed,
        idleTimeLimit,
        fit
      ]);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id: `asciinema-player-${id || "default"}`,
          ref: playerContainerRef,
          style: { ...style2 }
        }
      );
    };
    const carouselThumbs = "_carouselThumbs_1mvg8_1";
    const carouselThumb = "_carouselThumb_1mvg8_1";
    const carouselPlayIcon = "_carouselPlayIcon_1mvg8_16";
    const lightboxOverlay = "_lightboxOverlay_1mvg8_20";
    const lightboxContent = "_lightboxContent_1mvg8_33";
    const lightboxButtonCloseWrapper = "_lightboxButtonCloseWrapper_1mvg8_45";
    const lightboxButtonClose = "_lightboxButtonClose_1mvg8_45";
    const lightboxPreviewButton = "_lightboxPreviewButton_1mvg8_63";
    const styles$q = {
      carouselThumbs,
      carouselThumb,
      carouselPlayIcon,
      lightboxOverlay,
      lightboxContent,
      lightboxButtonCloseWrapper,
      lightboxButtonClose,
      lightboxPreviewButton
    };
    const LightboxCarousel = ({ slides }) => {
      const [isOpen, setIsOpen] = reactExports.useState(false);
      const [showOverlay, setShowOverlay] = reactExports.useState(false);
      const [currentIndex, setCurrentIndex] = reactExports.useState(0);
      const openLightbox = reactExports.useCallback(
        (index2) => {
          setCurrentIndex(index2);
          setShowOverlay(true);
          setTimeout(() => setIsOpen(true), 10);
        },
        [setCurrentIndex, setShowOverlay]
      );
      const closeLightbox = reactExports.useCallback(() => {
        setIsOpen(false);
      }, [setIsOpen]);
      reactExports.useEffect(() => {
        if (!isOpen && showOverlay) {
          const timer = setTimeout(() => {
            setShowOverlay(false);
          }, 300);
          return () => clearTimeout(timer);
        }
      }, [isOpen, showOverlay, setShowOverlay]);
      const showNext = reactExports.useCallback(() => {
        setCurrentIndex((prev) => {
          return (prev + 1) % slides.length;
        });
      }, [slides, setCurrentIndex]);
      const showPrev = reactExports.useCallback(() => {
        setCurrentIndex((prev) => (prev - 1 + slides.length) % slides.length);
      }, [slides, setCurrentIndex]);
      reactExports.useEffect(() => {
        if (!isOpen) return;
        const handleKeyUp = (e) => {
          if (e.key === "Escape") {
            closeLightbox();
          } else if (e.key === "ArrowRight") {
            showNext();
          } else if (e.key === "ArrowLeft") {
            showPrev();
          }
          e.preventDefault();
          e.stopPropagation();
        };
        window.addEventListener("keyup", handleKeyUp, true);
        return () => window.removeEventListener("keyup", handleKeyUp);
      }, [isOpen, showNext, showPrev]);
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("lightbox-carousel-container"), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$q.carouselThumbs), children: slides.map((slide, index2) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: clsx(styles$q.carouselThumb),
              onClick: () => openLightbox(index2),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: slide.label }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "i",
                  {
                    className: clsx(
                      ApplicationIcons.play,
                      styles$q.carouselPlayIcon
                    )
                  }
                ) })
              ]
            },
            index2
          );
        }) }),
        showOverlay && /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: clsx(styles$q.lightboxOverlay, isOpen ? "open" : "closed"),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$q.lightboxButtonCloseWrapper), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  className: styles$q.lightboxButtonClose,
                  onClick: closeLightbox,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.close })
                }
              ) }),
              slides.length > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  className: clsx(styles$q.lightboxPreviewButton, "prev"),
                  onClick: showPrev,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.previous })
                }
              ) : "",
              slides.length > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  className: clsx(styles$q.lightboxPreviewButton, "next"),
                  onClick: showNext,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.next })
                }
              ) : "",
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: clsx(styles$q.lightboxContent, isOpen ? "open" : "closed"),
                  children: slides[currentIndex].render()
                },
                `carousel-slide-${currentIndex}`
              )
            ]
          }
        )
      ] });
    };
    const HumanBaselineView = ({
      started,
      runtime,
      answer: answer2,
      completed,
      running: running2,
      sessionLogs
    }) => {
      const player_fns = [];
      const revokableUrls = [];
      const revokableUrl = (data) => {
        const blob = new Blob([data], { type: "text/plain" });
        const url = URL.createObjectURL(blob);
        revokableUrls.push(url);
        return url;
      };
      reactExports.useEffect(() => {
        return () => {
          revokableUrls.forEach((url) => URL.revokeObjectURL(url));
        };
      }, []);
      let count = 1;
      for (const sessionLog of sessionLogs) {
        const rows = extractSize(sessionLog.output, "LINES", 24);
        const cols = extractSize(sessionLog.output, "COLUMNS", 80);
        const currentCount = count;
        const title2 = sessionLogs.length === 1 ? "Terminal Session" : `Terminal Session ${currentCount}`;
        player_fns.push({
          label: title2,
          render: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
            AsciinemaPlayer,
            {
              id: `player-${currentCount}`,
              inputUrl: revokableUrl(sessionLog.input),
              outputUrl: revokableUrl(sessionLog.output),
              timingUrl: revokableUrl(sessionLog.timing),
              rows,
              cols,
              className: "asciinema-player",
              style: {
                height: `${rows * 2}em`,
                width: `${cols * 2}em`
              },
              fit: "both"
            }
          )
        });
        count += 1;
      }
      const StatusMessage = ({
        completed: completed2,
        running: running22,
        answer: answer22
      }) => {
        if (running22) {
          return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-style-label", children: "Running" });
        } else if (completed2) {
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                className: "text-style-label text-style-secondary asciinema-player-status",
                children: "Answer"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: answer22 })
          ] });
        } else {
          return "Unknown status";
        }
      };
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "asciinema-wrapper", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "asciinema-container", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "asciinema-header-left text-style-label", children: [
          started ? formatDateTime(started) : "",
          runtime ? ` (${formatTime$1(Math.floor(runtime))})` : ""
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "asciinema-header-center text-style-label" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "asciinema-header-right", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          StatusMessage,
          {
            completed,
            running: running2,
            answer: answer2
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "asciinema-body", children: /* @__PURE__ */ jsxRuntimeExports.jsx(LightboxCarousel, { slides: player_fns }) })
      ] }) });
    };
    const extractSize = (value2, label2, defaultValue) => {
      const regex2 = new RegExp(`${label2}="(\\d+)"`);
      const match = value2.match(regex2);
      const size = match ? match[1] : void 0;
      if (size) {
        return parseInt(size);
      } else {
        return defaultValue;
      }
    };
    const tools = "_tools_13oio_1";
    const tool = "_tool_13oio_1";
    const styles$p = {
      tools,
      tool
    };
    const system_msg_added_sig = {
      type: "system_message",
      signature: {
        remove: ["/messages/0/source"],
        replace: ["/messages/0/role", "/messages/0/content"],
        add: ["/messages/1"]
      },
      render: (_changes, resolvedState) => {
        const messages = resolvedState["messages"];
        const message2 = messages[0];
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          ChatView,
          {
            id: "system_msg_event_preview",
            messages: [message2]
          },
          "system_msg_event_preview"
        );
      }
    };
    const kToolPattern = "/tools/(\\d+)";
    const use_tools = {
      type: "use_tools",
      signature: {
        add: ["/tools/0"],
        replace: ["/tool_choice"],
        remove: []
      },
      render: (changes, resolvedState) => {
        return renderTools(changes, resolvedState);
      }
    };
    const add_tools = {
      type: "add_tools",
      signature: {
        add: [kToolPattern],
        replace: [],
        remove: []
      },
      render: (changes, resolvedState) => {
        return renderTools(changes, resolvedState);
      }
    };
    const humanAgentKey = (key2) => {
      return `HumanAgentState:${key2}`;
    };
    const human_baseline_session = {
      type: "human_baseline_session",
      signature: {
        add: ["HumanAgentState:logs"],
        replace: [],
        remove: []
      },
      render: (_changes, state) => {
        const started = state[humanAgentKey("started_running")];
        const runtime = state[humanAgentKey("accumulated_time")];
        const answer2 = state[humanAgentKey("answer")];
        const completed = !!answer2;
        const running2 = state[humanAgentKey("running_state")];
        const rawSessions = state[humanAgentKey("logs")];
        const startedDate = started ? new Date(started * 1e3) : void 0;
        const sessions = {};
        if (rawSessions) {
          for (const key2 of Object.keys(rawSessions)) {
            const value2 = rawSessions[key2];
            const match = key2.match(/(.*)_(\d+_\d+)\.(.*)/);
            if (match) {
              const user = match[1];
              const timestamp = match[2];
              const type = match[3];
              sessions[timestamp] = sessions[timestamp] || {};
              switch (type) {
                case "input":
                  sessions[timestamp].input = value2;
                  break;
                case "output":
                  sessions[timestamp].output = value2;
                  break;
                case "timing":
                  sessions[timestamp].timing = value2;
                  break;
                case "name":
                  sessions[timestamp].name = value2;
                  break;
              }
              sessions[timestamp].user = user;
            }
          }
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          HumanBaselineView,
          {
            started: startedDate,
            running: running2,
            completed,
            answer: answer2,
            runtime,
            sessionLogs: Object.values(sessions)
          },
          "human_baseline_view"
        );
      }
    };
    const renderTools = (changes, resolvedState) => {
      const toolIndexes = [];
      for (const change of changes) {
        const match = change.path.match(kToolPattern);
        if (match) {
          toolIndexes.push(match[1]);
        }
      }
      const toolName = (toolChoice) => {
        if (typeof toolChoice === "object" && toolChoice && !Array.isArray(toolChoice)) {
          return toolChoice["name"];
        } else {
          return String(toolChoice);
        }
      };
      const toolsInfo = {};
      const hasToolChoice = changes.find((change) => {
        return change.path.startsWith("/tool_choice");
      });
      if (resolvedState.tool_choice && hasToolChoice) {
        toolsInfo["Tool Choice"] = toolName(resolvedState.tool_choice);
      }
      const tools2 = resolvedState.tools;
      if (tools2.length > 0) {
        if (toolIndexes.length === 0) {
          toolsInfo["Tools"] = /* @__PURE__ */ jsxRuntimeExports.jsx(Tools, { toolDefinitions: resolvedState.tools });
        } else {
          const filtered = tools2.filter((_, index2) => {
            return toolIndexes.includes(index2.toString());
          });
          toolsInfo["Tools"] = /* @__PURE__ */ jsxRuntimeExports.jsx(Tools, { toolDefinitions: filtered });
        }
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$p.tools), children: Object.keys(toolsInfo).map((key2) => {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                "text-size-smaller",
                "text-style-label",
                "text-style-secondary"
              ),
              children: key2
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-base"), children: toolsInfo[key2] })
        ] }, key2);
      }) }, "state-diff-tools");
    };
    const RenderableChangeTypes = [
      system_msg_added_sig,
      use_tools,
      add_tools
    ];
    const StoreSpecificRenderableTypes = [
      human_baseline_session
    ];
    const Tools = ({ toolDefinitions }) => {
      return toolDefinitions.map((toolDefinition, idx) => {
        var _a2;
        const toolName = toolDefinition.name;
        const toolArgs = ((_a2 = toolDefinition.parameters) == null ? void 0 : _a2.properties) ? Object.keys(toolDefinition.parameters.properties) : [];
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Tool,
          {
            toolName,
            toolArgs
          },
          `${toolName}-${idx}`
        );
      });
    };
    const Tool = ({ toolName, toolArgs }) => {
      const functionCall = toolArgs && toolArgs.length > 0 ? `${toolName}(${toolArgs.join(", ")})` : toolName;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: clsx("text-size-small", styles$p.tool), children: functionCall }) });
    };
    const diff = "_diff_eobja_1";
    const summary$2 = "_summary_eobja_6";
    const styles$o = {
      diff,
      summary: summary$2
    };
    const StateEventView = ({
      id,
      event,
      eventState,
      setEventState,
      isStore = false,
      className: className2
    }) => {
      const summary2 = reactExports.useMemo(() => {
        return summarizeChanges(event.changes);
      }, [event.changes]);
      const [before, after] = reactExports.useMemo(() => {
        return synthesizeComparable(event.changes);
      }, [event.changes]);
      const changePreview = reactExports.useMemo(() => {
        return generatePreview(event.changes, structuredClone(after), isStore);
      }, [event.changes, after, isStore]);
      const title2 = event.event === "state" ? "State Updated" : "Store Updated";
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        EventPanel,
        {
          id,
          title: title2,
          className: className2,
          subTitle: formatDateTime(new Date(event.timestamp)),
          text: !changePreview ? summary2 : void 0,
          collapse: changePreview === void 0 ? true : void 0,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: [
            changePreview ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-name": "Summary", className: clsx(styles$o.summary), children: changePreview }) : void 0,
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              StateDiffView,
              {
                before,
                after,
                "data-name": "Diff",
                className: clsx(styles$o.diff)
              }
            )
          ]
        }
      );
    };
    const generatePreview = (changes, resolvedState, isStore) => {
      const results = [];
      for (const changeType of [
        ...RenderableChangeTypes,
        ...isStore ? StoreSpecificRenderableTypes : []
      ]) {
        const requiredMatchCount = changeType.signature.remove.length + changeType.signature.replace.length + changeType.signature.add.length;
        let matchingOps = 0;
        for (const change of changes) {
          const op = change.op;
          switch (op) {
            case "add":
              if (changeType.signature.add && changeType.signature.add.length > 0) {
                changeType.signature.add.forEach((signature) => {
                  if (change.path.match(signature)) {
                    matchingOps++;
                  }
                });
              }
              break;
            case "remove":
              if (changeType.signature.remove && changeType.signature.remove.length > 0) {
                changeType.signature.remove.forEach((signature) => {
                  if (change.path.match(signature)) {
                    matchingOps++;
                  }
                });
              }
              break;
            case "replace":
              if (changeType.signature.replace && changeType.signature.replace.length > 0) {
                changeType.signature.replace.forEach((signature) => {
                  if (change.path.match(signature)) {
                    matchingOps++;
                  }
                });
              }
              break;
          }
        }
        if (matchingOps === requiredMatchCount) {
          const el = changeType.render(changes, resolvedState);
          results.push(el);
          break;
        }
      }
      return results.length > 0 ? results : void 0;
    };
    const summarizeChanges = (changes) => {
      const changeMap = {
        add: [],
        copy: [],
        move: [],
        replace: [],
        remove: [],
        test: []
      };
      for (const change of changes) {
        switch (change.op) {
          case "add":
            changeMap.add.push(change.path);
            break;
          case "copy":
            changeMap.copy.push(change.path);
            break;
          case "move":
            changeMap.move.push(change.path);
            break;
          case "replace":
            changeMap.replace.push(change.path);
            break;
          case "remove":
            changeMap.remove.push(change.path);
            break;
          case "test":
            changeMap.test.push(change.path);
            break;
        }
      }
      const changeList = [];
      const totalOpCount = Object.keys(changeMap).reduce((prev, current) => {
        return prev + changeMap[current].length;
      }, 0);
      if (totalOpCount > 2) {
        Object.keys(changeMap).forEach((key2) => {
          const opChanges = changeMap[key2];
          if (opChanges.length > 0) {
            changeList.push(`${key2} ${opChanges.length}`);
          }
        });
      } else {
        Object.keys(changeMap).forEach((key2) => {
          const opChanges = changeMap[key2];
          if (opChanges.length > 0) {
            changeList.push(`${key2} ${opChanges.join(", ")}`);
          }
        });
      }
      return changeList.join(", ");
    };
    const synthesizeComparable = (changes) => {
      const before = {};
      const after = {};
      for (const change of changes) {
        switch (change.op) {
          case "add":
            initializeArrays(before, change.path);
            initializeArrays(after, change.path);
            setPath(after, change.path, change.value);
            break;
          case "copy":
            setPath(before, change.path, change.value);
            setPath(after, change.path, change.value);
            break;
          case "move":
            setPath(before, change.from || "", change.value);
            setPath(after, change.path, change.value);
            break;
          case "remove":
            setPath(before, change.path, change.value);
            break;
          case "replace":
            initializeArrays(before, change.path);
            initializeArrays(after, change.path);
            setPath(before, change.path, change.replaced);
            setPath(after, change.path, change.value);
            break;
        }
      }
      return [before, after];
    };
    function setPath(target2, path, value2) {
      const keys = parsePath(path);
      let current = target2;
      for (let i2 = 0; i2 < keys.length - 1; i2++) {
        const key2 = keys[i2];
        if (!(key2 in current)) {
          current[key2] = isArrayIndex(keys[i2 + 1]) ? [] : {};
        }
        current = current[key2];
      }
      const lastKey = keys[keys.length - 1];
      current[lastKey] = value2;
    }
    function initializeArrays(target2, path) {
      const keys = parsePath(path);
      let current = target2;
      for (let i2 = 0; i2 < keys.length - 1; i2++) {
        const key2 = keys[i2];
        const nextKey = keys[i2 + 1];
        if (isArrayIndex(nextKey)) {
          current[key2] = initializeArray(
            current[key2],
            nextKey
          );
        } else {
          current[key2] = initializeObject(current[key2]);
        }
        current = current[key2];
      }
      const lastKey = keys[keys.length - 1];
      if (isArrayIndex(lastKey)) {
        const lastValue = current[lastKey];
        initializeArray(lastValue, lastKey);
      }
    }
    function parsePath(path) {
      return path.split("/").filter(Boolean);
    }
    function isArrayIndex(key2) {
      return /^\d+$/.test(key2);
    }
    function initializeArray(current, nextKey) {
      if (!Array.isArray(current)) {
        current = [];
      }
      const nextKeyIndex = parseInt(nextKey, 10);
      while (current.length < nextKeyIndex) {
        current.push("");
      }
      return current;
    }
    function initializeObject(current) {
      return current ?? {};
    }
    const StepEventView = ({
      event,
      eventState,
      setEventState,
      children: children2,
      scrollRef,
      className: className2
    }) => {
      const descriptor = stepDescriptor(event);
      const title2 = descriptor.name || `${event.type ? event.type + ": " : "Step: "}${event.name}`;
      const text2 = summarize(children2);
      const [transcriptState, setTranscriptState] = reactExports.useState({});
      const onTranscriptState = reactExports.useCallback(
        (state) => {
          setTranscriptState({ ...state });
        },
        [setTranscriptState]
      );
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventPanel,
        {
          id: `step-${event.name}`,
          className: clsx("transcript-step", className2),
          title: title2,
          subTitle: formatDateTime(new Date(event.timestamp)),
          icon: descriptor.icon,
          collapse: descriptor.collapse,
          text: text2,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            TranscriptComponent,
            {
              id: `step-${event.name}-transcript`,
              eventNodes: children2,
              transcriptState,
              setTranscriptState: onTranscriptState
            }
          )
        }
      );
    };
    const summarize = (children2) => {
      if (children2.length === 0) {
        return "(no events)";
      }
      const formatEvent = (event, count) => {
        if (count === 1) {
          return `${count} ${event} event`;
        } else {
          return `${count} ${event} events`;
        }
      };
      const typeCount = {};
      children2.forEach((child) => {
        const currentCount = typeCount[child.event.event] || 0;
        typeCount[child.event.event] = currentCount + 1;
      });
      const numberOfTypes = Object.keys(typeCount).length;
      if (numberOfTypes < 3) {
        return Object.keys(typeCount).map((key2) => {
          return formatEvent(key2, typeCount[key2]);
        }).join(", ");
      }
      if (children2.length === 1) {
        return "1 event";
      } else {
        return `${children2.length} events`;
      }
    };
    const stepDescriptor = (event) => {
      const rootStepDescriptor = {
        endSpace: true
      };
      if (event.type === "solver") {
        switch (event.name) {
          case "chain_of_thought":
            return {
              ...rootStepDescriptor
            };
          case "generate":
            return {
              ...rootStepDescriptor
            };
          case "self_critique":
            return {
              ...rootStepDescriptor
            };
          case "system_message":
            return {
              ...rootStepDescriptor
            };
          case "use_tools":
            return {
              ...rootStepDescriptor
            };
          case "multiple_choice":
            return {
              ...rootStepDescriptor
            };
          default:
            return {
              ...rootStepDescriptor
            };
        }
      } else if (event.type === "scorer") {
        return {
          ...rootStepDescriptor
        };
      } else {
        switch (event.name) {
          case "sample_init":
            return {
              ...rootStepDescriptor,
              name: "Sample Init",
              collapse: true
            };
          case "init":
            return {
              ...rootStepDescriptor,
              name: "Init",
              collapse: true
            };
          default:
            return {
              endSpace: false
            };
        }
      }
    };
    const summary$1 = "_summary_ac4z2_1";
    const summaryRendered = "_summaryRendered_ac4z2_6";
    const subtaskSummary = "_subtaskSummary_ac4z2_10";
    const subtaskLabel = "_subtaskLabel_ac4z2_17";
    const styles$n = {
      summary: summary$1,
      summaryRendered,
      subtaskSummary,
      subtaskLabel
    };
    const SubtaskEventView = ({
      id,
      event,
      eventState,
      setEventState,
      depth,
      className: className2
    }) => {
      const body2 = event.type === "fork" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { title: "Summary", className: clsx(styles$n.summary), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label"), children: "Inputs" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$n.summaryRendered), children: /* @__PURE__ */ jsxRuntimeExports.jsx(Rendered, { values: event.input }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label"), children: "Transcript" }),
        event.events.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          TranscriptView,
          {
            id: `${id}-subtask`,
            "data-name": "Transcript",
            events: event.events,
            depth: depth + 1
          }
        ) : /* @__PURE__ */ jsxRuntimeExports.jsx(None, {})
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SubtaskSummary,
          {
            "data-name": "Summary",
            input: event.input,
            result: event.result
          }
        ),
        event.events.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          TranscriptView,
          {
            id: `${id}-subtask`,
            "data-name": "Transcript",
            events: event.events,
            depth: depth + 1
          }
        ) : void 0
      ] });
      const type = event.type === "fork" ? "Fork" : "Subtask";
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventPanel,
        {
          id,
          className: className2,
          title: formatTitle(
            `${type}: ${event.name}`,
            void 0,
            event.working_time
          ),
          subTitle: formatTiming(event.timestamp, event.working_start),
          collapse: false,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: body2
        }
      );
    };
    const SubtaskSummary = ({ input: input2, result: result2 }) => {
      const output2 = typeof result2 === "object" ? result2 : { result: result2 };
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$n.subtaskSummary), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label"), children: "Input" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-large", styles$n.subtaskLabel) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label"), children: "Output" }),
        input2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(Rendered, { values: input2 }) : void 0,
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-title-secondary", styles$n.subtaskLabel), children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.arrows.right }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Rendered, { values: output2 }) })
      ] });
    };
    const Rendered = ({ values }) => {
      if (Array.isArray(values)) {
        return values.map((val) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(Rendered, { values: val });
        });
      } else if (values && typeof values === "object") {
        if (Object.keys(values).length === 0) {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(None, {});
        } else {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(MetaDataView, { entries: values });
        }
      } else {
        return values;
      }
    };
    const None = () => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: clsx("text-size-small", "text-style-secondary"), children: "[None]" });
    };
    const summary = "_summary_1qkjz_1";
    const approval = "_approval_1qkjz_6";
    const styles$m = {
      summary,
      approval
    };
    const ToolEventView = ({
      id,
      event,
      eventState,
      setEventState,
      depth,
      className: className2
    }) => {
      var _a2, _b2;
      const { input: input2, functionCall, highlightLanguage } = reactExports.useMemo(
        () => resolveToolInput(event.function, event.arguments),
        [event.function, event.arguments]
      );
      const approvalEvent = event.events.find((e) => {
        return e.event === "approval";
      });
      const title2 = `Tool: ${((_a2 = event.view) == null ? void 0 : _a2.title) || event.function}`;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        EventPanel,
        {
          id,
          title: formatTitle(title2, void 0, event.working_time),
          className: className2,
          subTitle: formatTiming(event.timestamp, event.working_start),
          icon: ApplicationIcons.solvers.use_tools,
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { "data-name": "Summary", className: styles$m.summary, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                ToolCallView,
                {
                  functionCall,
                  input: input2,
                  highlightLanguage,
                  output: ((_b2 = event.error) == null ? void 0 : _b2.message) || event.result,
                  mode: "compact",
                  view: event.view ? event.view : void 0
                }
              ),
              approvalEvent ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                ApprovalEventView,
                {
                  event: approvalEvent,
                  className: styles$m.approval
                }
              ) : ""
            ] }),
            event.events.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              TranscriptView,
              {
                id: `${id}-subtask`,
                "data-name": "Transcript",
                events: event.events,
                depth: depth + 1
              }
            ) : ""
          ]
        }
      );
    };
    class EventNode {
      constructor(event, depth) {
        __publicField(this, "event");
        __publicField(this, "children", []);
        __publicField(this, "depth");
        this.event = event;
        this.depth = depth;
      }
    }
    const twoColumn = "_twoColumn_iwnfd_9";
    const exec = "_exec_iwnfd_15";
    const result = "_result_iwnfd_19";
    const fileLabel = "_fileLabel_iwnfd_23";
    const wrapPre = "_wrapPre_iwnfd_28";
    const styles$l = {
      twoColumn,
      exec,
      result,
      fileLabel,
      wrapPre
    };
    const SandboxEventView = ({
      id,
      event,
      eventState,
      setEventState,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        EventPanel,
        {
          id,
          className: className2,
          title: `Sandbox: ${event.action}`,
          icon: ApplicationIcons.sandbox,
          subTitle: formatTiming(event.timestamp, event.working_start),
          selectedNav: eventState.selectedNav || "",
          setSelectedNav: (selectedNav) => {
            setEventState({ ...eventState, selectedNav });
          },
          collapsed: eventState.collapsed,
          setCollapsed: (collapsed) => {
            setEventState({ ...eventState, collapsed });
          },
          children: event.action === "exec" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ExecView, { event }) : event.action === "read_file" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ReadFileView, { event }) : /* @__PURE__ */ jsxRuntimeExports.jsx(WriteFileView, { event })
        }
      );
    };
    const ExecView = ({ event }) => {
      if (event.cmd === null) {
        return void 0;
      }
      const cmd2 = event.cmd;
      const options2 = event.options;
      const input2 = event.input;
      const result2 = event.result;
      const output2 = event.output;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$l.exec), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: `Command`, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$l.twoColumn), children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: clsx(styles$l.wrapPre), children: cmd2 }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: clsx(styles$l.wrapPre), children: input2 !== null ? input2 == null ? void 0 : input2.trim() : void 0 }),
          options2 !== null ? /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: `Options`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            MetaDataGrid,
            {
              entries: options2,
              plain: true
            }
          ) }) : void 0
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(EventSection, { title: `Result`, children: [
          output2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(ExpandablePanel, { collapse: false, children: /* @__PURE__ */ jsxRuntimeExports.jsx(MarkdownDiv, { markdown: output2 }) }) : void 0,
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$l.result), children: [
            "Exited with code ",
            result2
          ] })
        ] })
      ] });
    };
    const ReadFileView = ({ event }) => {
      if (event.file === null) {
        return void 0;
      }
      const file = event.file;
      const output2 = event.output;
      return /* @__PURE__ */ jsxRuntimeExports.jsx(FileView, { file, contents: output2 == null ? void 0 : output2.trim() });
    };
    const WriteFileView = ({ event }) => {
      if (event.file === null) {
        return void 0;
      }
      const file = event.file;
      const input2 = event.input;
      return /* @__PURE__ */ jsxRuntimeExports.jsx(FileView, { file, contents: input2 == null ? void 0 : input2.trim() });
    };
    const FileView = ({ file, contents: contents2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "File", children: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: clsx(styles$l.fileLabel), children: file }) }),
        contents2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(EventSection, { title: "Contents", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExpandablePanel, { collapse: false, children: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { children: contents2 }) }) }) : void 0
      ] });
    };
    const darkenedBg = "_darkenedBg_c8m1t_1";
    const normalBg = "_normalBg_c8m1t_5";
    const node = "_node_c8m1t_9";
    const first = "_first_c8m1t_9";
    const transcriptComponent = "_transcriptComponent_c8m1t_23";
    const eventNode = "_eventNode_c8m1t_29";
    const darkenBg = "_darkenBg_c8m1t_35";
    const lastNode = "_lastNode_c8m1t_39";
    const eventNodeContainer = "_eventNodeContainer_c8m1t_43";
    const noBottom = "_noBottom_c8m1t_47";
    const styles$k = {
      darkenedBg,
      normalBg,
      node,
      first,
      transcriptComponent,
      eventNode,
      darkenBg,
      lastNode,
      eventNodeContainer,
      noBottom
    };
    const TranscriptView = ({
      id,
      events,
      depth
    }) => {
      const [transcriptState, setTranscriptState] = reactExports.useState({});
      const onTranscriptState = reactExports.useCallback(
        (state) => {
          setTranscriptState(state);
        },
        [setTranscriptState]
      );
      const resolvedEvents = fixupEventStream(events);
      const eventNodes = treeifyEvents(
        resolvedEvents,
        depth !== void 0 ? depth : 0
      );
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        TranscriptComponent,
        {
          id,
          eventNodes,
          transcriptState,
          setTranscriptState: onTranscriptState
        }
      );
    };
    const TranscriptVirtualList = (props) => {
      let { id, scrollRef, events, depth } = props;
      const resolvedEvents = fixupEventStream(events);
      const eventNodes = treeifyEvents(resolvedEvents, depth || 0);
      const [transcriptState, setTranscriptState] = reactExports.useState({});
      const onTranscriptState = reactExports.useCallback(
        (state) => {
          setTranscriptState(state);
        },
        [setTranscriptState]
      );
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        TranscriptVirtualListComponent,
        {
          id,
          eventNodes,
          scrollRef,
          transcriptState,
          setTranscriptState: onTranscriptState
        }
      );
    };
    const TranscriptVirtualListComponent = ({ id, eventNodes, scrollRef, transcriptState, setTranscriptState }) => {
      const setEventState = reactExports.useCallback(
        (eventId, state) => {
          setTranscriptState({ ...transcriptState, [eventId]: state });
        },
        [transcriptState, setTranscriptState]
      );
      const [followOutput, setFollowOutput] = reactExports.useState(false);
      const renderRow = (item2, index2) => {
        const bgClass = item2.depth % 2 == 0 ? styles$k.darkenedBg : styles$k.normalBg;
        const paddingClass = index2 === 0 ? styles$k.first : void 0;
        const eventId = `${id}-event${index2}`;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$k.node, paddingClass), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          RenderedEventNode,
          {
            id: eventId,
            node: item2,
            className: clsx(bgClass),
            scrollRef,
            eventState: transcriptState[eventId] || {},
            setEventState: (state) => setEventState(eventId, state)
          }
        ) }, eventId);
      };
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        $r,
        {
          customScrollParent: (scrollRef == null ? void 0 : scrollRef.current) ? scrollRef.current : void 0,
          style: { height: "100%", width: "100%" },
          data: eventNodes,
          itemContent: (index2, data) => {
            return renderRow(data, index2);
          },
          increaseViewportBy: { top: 1e3, bottom: 1e3 },
          overscan: {
            main: 10,
            reverse: 10
          },
          followOutput,
          atBottomStateChange: (atBottom) => {
            setFollowOutput(atBottom);
          },
          skipAnimationFrameInResizeObserver: true,
          className: clsx("transcript")
        }
      );
    };
    const TranscriptComponent = ({
      id,
      transcriptState,
      setTranscriptState,
      eventNodes
    }) => {
      const setEventState = reactExports.useCallback(
        (state, eventId) => {
          setTranscriptState({ ...transcriptState, [eventId]: state });
        },
        [setTranscriptState, transcriptState]
      );
      const rows = eventNodes.map((eventNode2, index2) => {
        const clz = [styles$k.eventNode];
        if (eventNode2.depth % 2 == 0) {
          clz.push(styles$k.darkenBg);
        }
        if (index2 === eventNodes.length - 1) {
          clz.push(styles$k.lastNode);
        }
        const eventId = `${id}-event${index2}`;
        const row2 = /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: clsx(
              styles$k.eventNodeContainer,
              index2 === eventNodes.length - 1 ? styles$k.noBottom : void 0
            ),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              RenderedEventNode,
              {
                id: eventId,
                node: eventNode2,
                className: clsx(clz),
                eventState: transcriptState[eventId] || {},
                setEventState: (state) => {
                  setEventState(state, eventId);
                }
              }
            )
          },
          eventId
        );
        return row2;
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id,
          className: clsx("text-size-small", styles$k.transcriptComponent),
          children: rows
        }
      );
    };
    const RenderedEventNode = ({
      id,
      node: node2,
      scrollRef,
      eventState,
      setEventState,
      className: className2
    }) => {
      switch (node2.event.event) {
        case "sample_init":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleInitEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "sample_limit":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleLimitEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "info":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            InfoEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "logger":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(LoggerEventView, { event: node2.event, className: className2 });
        case "model":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            ModelEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "score":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            ScoreEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "state":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            StateEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "step":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            StepEventView,
            {
              event: node2.event,
              eventState,
              setEventState,
              children: node2.children,
              scrollRef,
              className: className2
            }
          );
        case "store":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            StateEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2,
              isStore: true
            }
          );
        case "subtask":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            SubtaskEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2,
              depth: node2.depth
            }
          );
        case "tool":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            ToolEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2,
              depth: node2.depth
            }
          );
        case "input":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            InputEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "error":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            ErrorEventView,
            {
              id,
              event: node2.event,
              eventState,
              setEventState,
              className: className2
            }
          );
        case "approval":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ApprovalEventView, { event: node2.event, className: className2 });
        case "sandbox":
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            SandboxEventView,
            {
              id,
              event: node2.event,
              className: className2,
              eventState,
              setEventState
            }
          );
        default:
          return null;
      }
    };
    const fixupEventStream = (events) => {
      const initEventIndex = events.findIndex((e) => {
        return e.event === "sample_init";
      });
      const initEvent = events[initEventIndex];
      const finalEvents = events.filter((e) => !e.pending);
      const hasInitStep = events.findIndex((e) => {
        return e.event === "step" && e.name === "init";
      }) !== -1;
      const fixedUp = [...finalEvents];
      if (!hasInitStep && initEvent) {
        fixedUp.splice(initEventIndex, 0, {
          timestamp: initEvent.timestamp,
          event: "step",
          action: "begin",
          type: null,
          name: "sample_init",
          pending: false,
          working_start: 0
        });
        fixedUp.splice(initEventIndex + 2, 0, {
          timestamp: initEvent.timestamp,
          event: "step",
          action: "end",
          type: null,
          name: "sample_init",
          pending: false,
          working_start: 0
        });
      }
      return fixedUp;
    };
    function treeifyEvents(events, depth) {
      const rootNodes = [];
      const stack2 = [];
      const pushNode = (event) => {
        const node2 = new EventNode(event, stack2.length + depth);
        if (stack2.length > 0) {
          const parentNode = stack2[stack2.length - 1];
          parentNode.children.push(node2);
        } else {
          rootNodes.push(node2);
        }
        return node2;
      };
      events.forEach((event) => {
        if (event.event === "step" && event.action === "begin") {
          const node2 = pushNode(event);
          stack2.push(node2);
        } else if (event.event === "step" && event.action === "end") {
          if (stack2.length > 0) {
            stack2.pop();
          }
        } else {
          pushNode(event);
        }
      });
      return rootNodes;
    }
    const SampleTranscript = ({
      id,
      evalEvents,
      scrollRef
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(TranscriptVirtualList, { id, events: evalEvents, scrollRef });
    };
    const SampleDisplay = ({
      id,
      sample: sample2,
      sampleDescriptor,
      selectedTab,
      setSelectedTab,
      scrollRef
    }) => {
      const baseId = `sample-dialog`;
      if (!sample2) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyPanel, {});
      }
      const onSelectedTab = (e) => {
        const el = e.currentTarget;
        const id2 = el.id;
        setSelectedTab(id2);
        return false;
      };
      const scorerNames = Object.keys(sample2.scores || {});
      const sampleMetadatas = metadataViewsForSample(`${baseId}-${id}`, sample2);
      const tabsetId = `task-sample-details-tab-${id}`;
      const targetId = `${tabsetId}-content`;
      const tools2 = [];
      if (!isVscode()) {
        tools2.push(
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ToolButton,
            {
              label: "Print",
              icon: ApplicationIcons.copy,
              onClick: () => {
                printSample(id, targetId);
              }
            },
            "sample-print-tool"
          )
        );
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SampleSummaryView,
          {
            parent_id: id,
            sample: sample2,
            sampleDescriptor
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          TabSet,
          {
            id: tabsetId,
            tabControlsClassName: clsx("text-size-base"),
            tabPanelsClassName: clsx(styles$E.tabPanel),
            tools: tools2,
            children: [
              sample2.events && sample2.events.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                TabPanel,
                {
                  id: kSampleTranscriptTabId,
                  className: "sample-tab",
                  title: "Transcript",
                  onSelected: onSelectedTab,
                  selected: selectedTab === kSampleTranscriptTabId || selectedTab === void 0,
                  scrollable: false,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    SampleTranscript,
                    {
                      id: `${baseId}-transcript-display-${id}`,
                      evalEvents: sample2.events,
                      scrollRef
                    },
                    `${baseId}-transcript-display-${id}`
                  )
                },
                kSampleTranscriptTabId
              ) : null,
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                TabPanel,
                {
                  id: kSampleMessagesTabId,
                  className: clsx("sample-tab", styles$E.fullWidth),
                  title: "Messages",
                  onSelected: onSelectedTab,
                  selected: selectedTab === kSampleMessagesTabId,
                  scrollable: false,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ChatViewVirtualList,
                    {
                      id: `${baseId}-chat-${id}`,
                      messages: sample2.messages,
                      indented: true,
                      scrollRef,
                      toolCallStyle: "complete"
                    },
                    `${baseId}-chat-${id}`
                  )
                },
                kSampleMessagesTabId
              ),
              scorerNames.length === 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                TabPanel,
                {
                  id: kSampleScoringTabId,
                  className: "sample-tab",
                  title: "Scoring",
                  onSelected: onSelectedTab,
                  selected: selectedTab === kSampleScoringTabId,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    SampleScoreView,
                    {
                      sample: sample2,
                      sampleDescriptor,
                      scorer: scorerNames[0]
                    }
                  )
                },
                kSampleScoringTabId
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: Object.keys(sample2.scores || {}).map((scorer) => {
                const tabId = `score-${scorer}`;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  TabPanel,
                  {
                    id: tabId,
                    className: "sample-tab",
                    title: scorer,
                    onSelected: onSelectedTab,
                    selected: selectedTab === tabId,
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      SampleScoreView,
                      {
                        sample: sample2,
                        sampleDescriptor,
                        scorer
                      }
                    )
                  },
                  tabId
                );
              }) }),
              sampleMetadatas.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                TabPanel,
                {
                  id: kSampleMetdataTabId,
                  className: clsx("sample-tab"),
                  title: "Metadata",
                  onSelected: onSelectedTab,
                  selected: selectedTab === kSampleMetdataTabId,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$E.metadataPanel), children: sampleMetadatas })
                }
              ) : null,
              sample2.error ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                TabPanel,
                {
                  id: kSampleErrorTabId,
                  className: "sample-tab",
                  title: "Error",
                  onSelected: onSelectedTab,
                  selected: selectedTab === kSampleErrorTabId,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$E.padded), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ANSIDisplay,
                    {
                      output: sample2.error.traceback_ansi,
                      className: clsx("text-size-small", styles$E.ansi)
                    }
                  ) })
                }
              ) : null,
              sample2.messages.length < 100 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                TabPanel,
                {
                  id: kSampleJsonTabId,
                  className: "sample-tab",
                  title: "JSON",
                  onSelected: onSelectedTab,
                  selected: selectedTab === kSampleJsonTabId,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$E.padded, styles$E.fullWidth), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    JSONPanel,
                    {
                      data: sample2,
                      simple: true,
                      className: clsx("text-size-small")
                    }
                  ) })
                }
              ) : null
            ]
          }
        )
      ] });
    };
    const metadataViewsForSample = (id, sample2) => {
      const sampleMetadatas = [];
      if (sample2.model_usage && Object.keys(sample2.model_usage).length > 0) {
        sampleMetadatas.push(
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { label: "Usage" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              ModelTokenTable,
              {
                model_usage: sample2.model_usage,
                className: clsx(styles$E.noTop)
              }
            ) })
          ] }, `sample-usage-${id}`)
        );
      }
      if (sample2.total_time !== void 0 && sample2.total_time !== null && sample2.working_time !== void 0 && sample2.working_time !== null) {
        sampleMetadatas.push(
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { label: "Time" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$E.timePanel, "text-size-smaller"), children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label", "text-style-secondary"), children: "Working" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatTime$1(sample2.working_time) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-style-label", "text-style-secondary"), children: "Total" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatTime$1(sample2.total_time) })
            ] }) })
          ] }, `sample-time-${id}`)
        );
      }
      if (Object.keys(sample2 == null ? void 0 : sample2.metadata).length > 0) {
        sampleMetadatas.push(
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { label: "Metadata" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              MetaDataView,
              {
                id: "task-sample-metadata-${id}",
                entries: sample2 == null ? void 0 : sample2.metadata,
                className: clsx("tab-pane", styles$E.noTop)
              }
            ) })
          ] }, `sample-metadata-${id}`)
        );
      }
      if (Object.keys(sample2 == null ? void 0 : sample2.store).length > 0) {
        sampleMetadatas.push(
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { label: "Store" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              MetaDataView,
              {
                id: "task-sample-store-${id}",
                entries: sample2 == null ? void 0 : sample2.store,
                className: clsx("tab-pane", styles$E.noTop)
              }
            ) })
          ] }, `sample-store-${id}`)
        );
      }
      return sampleMetadatas;
    };
    const printSample = (id, targetId) => {
      const targetTabEl = document.querySelector(
        `#${escapeSelector(targetId)} .sample-tab.tab-pane.show.active`
      );
      if (targetTabEl) {
        const targetEl = targetTabEl.firstElementChild;
        if (targetEl) {
          const headingId = `sample-heading-${id}`;
          const headingEl = document.getElementById(headingId);
          const headingHtml = printHeadingHtml();
          const css = `
      html { font-size: 9pt }
      /* Allow content to break anywhere without any forced page breaks */
      * {
        break-inside: auto;  /* Let elements break anywhere */
        page-break-inside: auto;  /* Legacy support */
        break-before: auto;
        page-break-before: auto;
        break-after: auto;
        page-break-after: auto;
      }
      /* Specifically disable all page breaks for divs */
      div {
        break-inside: auto;
        page-break-inside: auto;
      }
      body > .transcript-step {
        break-inside: avoid;
      }
      body{
        -webkit-print-color-adjust:exact !important;
        print-color-adjust:exact !important;
      }
      /* Allow preformatted text and code blocks to break across pages */
      pre, code {
          white-space: pre-wrap; /* Wrap long lines instead of keeping them on one line */
          overflow-wrap: break-word; /* Ensure long words are broken to fit within the page */
          break-inside: auto; /* Allow page breaks inside the element */
          page-break-inside: auto; /* Older equivalent */
      }

      /* Additional control for long lines within code/preformatted blocks */
      pre {
          word-wrap: break-word; /* Break long words if needed */
      }    
          
      `;
          printHtml(
            [headingHtml, headingEl == null ? void 0 : headingEl.outerHTML, targetEl.innerHTML].join("\n"),
            css
          );
        }
      }
    };
    const container$5 = "_container_gzd7f_1";
    const body$2 = "_body_gzd7f_6";
    const styles$j = {
      container: container$5,
      body: body$2
    };
    const InlineSampleDisplay = ({
      id,
      sample: sample2,
      sampleStatus,
      sampleError,
      sampleDescriptor,
      selectedTab,
      setSelectedTab,
      scrollRef
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$j.container, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ProgressBar, { animating: sampleStatus === "loading" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$j.body, children: sampleError ? /* @__PURE__ */ jsxRuntimeExports.jsx(ErrorPanel, { title: "Unable to load sample", error: sampleError }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
          SampleDisplay,
          {
            id,
            sample: sample2,
            sampleDescriptor,
            selectedTab,
            setSelectedTab,
            scrollRef
          }
        ) })
      ] });
    };
    const title = "_title_yj2nt_1";
    const detail = "_detail_yj2nt_5";
    const detailText = "_detailText_yj2nt_13";
    const close = "_close_yj2nt_18";
    const modal = "_modal_yj2nt_26";
    const hidden = "_hidden_yj2nt_31";
    const modalBody = "_modalBody_yj2nt_35";
    const content = "_content_yj2nt_41";
    const header$1 = "_header_yj2nt_45";
    const titleTool = "_titleTool_yj2nt_50";
    const styles$i = {
      title,
      detail,
      detailText,
      close,
      modal,
      hidden,
      modalBody,
      content,
      header: header$1,
      titleTool
    };
    const LargeModal = ({
      id,
      title: title2,
      detail: detail2,
      detailTools,
      children: children2,
      footer: footer2,
      onkeyup,
      visible: visible2,
      onHide,
      showProgress,
      initialScrollPositionRef,
      setInitialScrollPosition,
      scrollRef
    }) => {
      const modalFooter = footer2 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "modal-footer", children: footer2 }) : "";
      const modalRef = reactExports.useRef(null);
      scrollRef = scrollRef || modalRef;
      reactExports.useEffect(() => {
        if (scrollRef.current) {
          setTimeout(() => {
            if (scrollRef.current && initialScrollPositionRef.current && scrollRef.current.scrollTop !== (initialScrollPositionRef == null ? void 0 : initialScrollPositionRef.current)) {
              scrollRef.current.scrollTop = initialScrollPositionRef.current;
            }
          }, 0);
        }
      }, []);
      const onScroll = reactExports.useCallback(
        (e) => {
          setInitialScrollPosition(e.currentTarget.scrollTop);
        },
        [setInitialScrollPosition]
      );
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id,
          className: clsx(
            "modal",
            styles$i.modal,
            !visible2 ? styles$i.hidden : void 0
          ),
          role: "dialog",
          onKeyUp: onkeyup,
          tabIndex: visible2 ? 0 : void 0,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: clsx(
                "modal-dialog",
                "modal-dialog-scrollable",
                styles$i.modalBody
              ),
              role: "document",
              children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("modal-content", styles$i.content), children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("modal-header", styles$i.header), children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      className: clsx("modal-title", "text-size-smaller", styles$i.title),
                      children: title2 || ""
                    }
                  ),
                  detail2 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$i.detail, children: [
                    (detailTools == null ? void 0 : detailTools.left) ? detailTools.left.map((tool2, idx) => {
                      return /* @__PURE__ */ jsxRuntimeExports.jsx(TitleTool, { ...tool2 }, `tool-left-${idx}`);
                    }) : "",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-smaller", styles$i.detailText), children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: detail2 }) }),
                    (detailTools == null ? void 0 : detailTools.right) ? detailTools.right.map((tool2, idx) => {
                      return /* @__PURE__ */ jsxRuntimeExports.jsx(TitleTool, { ...tool2 }, `tool-right-${idx}`);
                    }) : ""
                  ] }) : void 0,
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: clsx(
                        "btn",
                        "btn-close-large-dialog",
                        "text-size-larger",
                        styles$i.close
                      ),
                      onClick: onHide,
                      "aria-label": "Close",
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(HtmlEntity, { html: "&times;" })
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(ProgressBar, { animating: showProgress }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "modal-body", ref: scrollRef, onScroll, children: children2 }),
                modalFooter
              ] })
            }
          )
        }
      );
    };
    const HtmlEntity = ({ html }) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { dangerouslySetInnerHTML: { __html: html } });
    const TitleTool = ({ label: label2, icon, enabled, onClick }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: clsx(
            "btn",
            "btn-outline",
            "text-size-small",
            styles$i.titleTool
          ),
          "aria-label": label2,
          onClick,
          disabled: !enabled,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: icon })
        }
      );
    };
    const SampleDialog = ({
      id,
      title: title2,
      sample: sample2,
      sampleDescriptor,
      nextSample,
      prevSample,
      sampleStatus,
      sampleError,
      showingSampleDialog,
      setShowingSampleDialog,
      selectedTab,
      setSelectedTab,
      sampleScrollPositionRef,
      setSampleScrollPosition
    }) => {
      const scrollRef = reactExports.useRef(null);
      const tools2 = reactExports.useMemo(() => {
        const nextTool = {
          label: "Next Sample",
          icon: ApplicationIcons.next,
          onClick: nextSample,
          enabled: !!nextSample
        };
        const prevTool = {
          label: "Previous Sample",
          icon: ApplicationIcons.previous,
          onClick: prevSample,
          enabled: !!prevSample
        };
        return {
          left: [prevTool],
          right: [nextTool]
        };
      }, [prevSample, nextSample]);
      const handleKeyUp = reactExports.useCallback(
        (e) => {
          switch (e.key) {
            case "ArrowRight":
              if (nextSample) {
                nextSample();
              }
              break;
            case "ArrowLeft":
              if (prevSample) {
                prevSample();
              }
              break;
            case "Escape":
              setShowingSampleDialog(false);
              break;
          }
        },
        [prevSample, nextSample, setShowingSampleDialog]
      );
      const onHide = reactExports.useCallback(() => {
        setShowingSampleDialog(false);
      }, [setShowingSampleDialog]);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        LargeModal,
        {
          id,
          detail: title2,
          detailTools: tools2,
          onkeyup: handleKeyUp,
          visible: showingSampleDialog,
          onHide,
          showProgress: sampleStatus === "loading",
          initialScrollPositionRef: sampleScrollPositionRef,
          setInitialScrollPosition: setSampleScrollPosition,
          scrollRef,
          children: sampleError ? /* @__PURE__ */ jsxRuntimeExports.jsx(ErrorPanel, { title: "Sample Error", error: sampleError }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleDisplay,
            {
              id,
              sample: sample2,
              sampleDescriptor,
              selectedTab,
              setSelectedTab,
              scrollRef
            }
          )
        }
      );
    };
    const MessageBand = ({
      message: message2,
      hidden: hidden2,
      setHidden,
      type
    }) => {
      const className2 = [type];
      if (hidden2) {
        className2.push("hidden");
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("message-band", className2), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.logging[type] }),
        message2,
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            className: clsx("btn", "message-band-btn", type),
            title: "Close",
            onClick: () => {
              setHidden(true);
            },
            children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.close })
          }
        )
      ] });
    };
    const kBaseFontSize = 0.9;
    const ScaleBaseFont = (scale) => {
      return `${kBaseFontSize + scale}rem`;
    };
    const FontSize = {
      smaller: ScaleBaseFont(-0.1)
    };
    const TextStyle = {
      secondary: {
        color: "var(--bs-secondary)"
      }
    };
    const ApplicationStyles = {
      moreButton: {
        maxHeight: "1.8em",
        fontSize: FontSize.smaller,
        padding: "0 0.2em 0 0.2em",
        ...TextStyle.secondary
      },
      threeLineClamp: {
        display: "-webkit-box",
        WebkitLineClamp: "3",
        WebkitBoxOrient: "vertical",
        overflow: "hidden"
      },
      lineClamp: (len) => {
        return {
          display: "-webkit-box",
          WebkitLineClamp: `${len}`,
          WebkitBoxOrient: "vertical",
          overflow: "hidden"
        };
      },
      wrapText: () => {
        return {
          whiteSpace: "nowrap",
          textOverflow: "ellipsis",
          overflow: "hidden"
        };
      },
      scoreFills: {
        green: {
          backgroundColor: "var(--bs-success)",
          borderColor: "var(--bs-success)",
          color: "var(--bs-body-bg)"
        },
        red: {
          backgroundColor: "var(--bs-danger)",
          borderColor: "var(--bs-danger)",
          color: "var(--bs-body-bg)"
        },
        orange: {
          backgroundColor: "var(--bs-orange)",
          borderColor: "var(--bs-orange)",
          color: "var(--bs-body-bg)"
        }
      }
    };
    const body$1 = "_body_5y0hl_1";
    const iconSmall = "_iconSmall_5y0hl_9";
    const message = "_message_5y0hl_15";
    const styles$h = {
      body: body$1,
      iconSmall,
      message
    };
    const SampleErrorView = ({
      message: message2,
      align
    }) => {
      align = align || "center";
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$h.body, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: clsx(ApplicationIcons.error, styles$h.iconSmall) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$h.message, style: ApplicationStyles.lineClamp(2), children: errorType(message2) })
      ] });
    };
    const grid$1 = "_grid_1kcta_1";
    const selected = "_selected_1kcta_13";
    const cell = "_cell_1kcta_17";
    const wrapAnywhere = "_wrapAnywhere_1kcta_22";
    const noLeft = "_noLeft_1kcta_26";
    const score = "_score_1kcta_30";
    const styles$g = {
      grid: grid$1,
      selected,
      cell,
      wrapAnywhere,
      noLeft,
      score
    };
    const SampleRow = ({
      id,
      index: index2,
      sample: sample2,
      sampleDescriptor,
      gridColumnsTemplate,
      height,
      selected: selected2,
      showSample
    }) => {
      var _a2;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          id: `sample-${id}`,
          onClick: () => {
            showSample(index2);
          },
          className: clsx(
            styles$g.grid,
            "text-size-base",
            selected2 ? styles$g.selected : void 0
          ),
          style: {
            height: `${height}px`,
            gridTemplateRows: `${height - 28}px`,
            gridTemplateColumns: gridColumnsTemplate
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("sample-id", "three-line-clamp", styles$g.cell), children: sample2.id }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  "sample-input",
                  "three-line-clamp",
                  styles$g.cell,
                  styles$g.wrapAnywhere
                ),
                children: inputString(sample2.input).join(" ")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("sample-target", "three-line-clamp", styles$g.cell), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarkdownDiv,
              {
                markdown: arrayToString(sample2 == null ? void 0 : sample2.target),
                className: clsx("no-last-para-padding", styles$g.noLeft)
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("sample-answer", "three-line-clamp", styles$g.cell), children: sample2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarkdownDiv,
              {
                markdown: sampleDescriptor == null ? void 0 : sampleDescriptor.selectedScorerDescriptor(sample2).answer(),
                className: clsx("no-last-para-padding", styles$g.noLeft)
              }
            ) : "" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  "sample-limit",
                  "text-size-small",
                  "three-line-clamp",
                  styles$g.cell
                ),
                children: sample2.limit
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-small", styles$g.cell, styles$g.score), children: sample2.error ? /* @__PURE__ */ jsxRuntimeExports.jsx(SampleErrorView, { message: sample2.error }) : (_a2 = sampleDescriptor == null ? void 0 : sampleDescriptor.selectedScore(sample2)) == null ? void 0 : _a2.render() })
          ]
        }
      );
    };
    const row$1 = "_row_utdq5_1";
    const styles$f = {
      row: row$1
    };
    const SampleSeparator = ({
      id,
      title: title2,
      height
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id,
          className: clsx("text-style-secondary", "text-size-smaller", styles$f.row),
          style: { height: `${height}px` },
          children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: title2 })
        }
      );
    };
    const footer = "_footer_vk06l_1";
    const styles$e = {
      footer
    };
    const SampleFooter = ({ sampleCount }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("text-size-smaller", styles$e.footer), children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        sampleCount,
        " Samples"
      ] }) });
    };
    const header = "_header_16ngy_1";
    const center = "_center_16ngy_11";
    const styles$d = {
      header,
      center
    };
    const SampleHeader = ({
      input: input2 = true,
      target: target2 = true,
      answer: answer2 = true,
      limit = true,
      score: score2 = true,
      gridColumnsTemplate
    }) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: clsx(
          styles$d.header,
          "text-size-smaller",
          "text-style-label",
          "text-style-secondary"
        ),
        style: { gridTemplateColumns: gridColumnsTemplate },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Id" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: input2 ? "Input" : "" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: target2 ? "Target" : "" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: answer2 ? "Answer" : "" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: limit ? "Limit" : "" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$d.center, children: score2 ? "Score" : "" })
        ]
      }
    );
    const mainLayout = "_mainLayout_q79zq_7";
    const styles$c = {
      mainLayout
    };
    const kSampleHeight = 88;
    const kSeparatorHeight = 24;
    const SampleList = (props) => {
      const {
        items,
        sampleDescriptor,
        selectedIndex,
        nextSample,
        prevSample,
        showSample,
        className: className2,
        listHandle
      } = props;
      const [followOutput, setFollowOutput] = reactExports.useState(false);
      const [hidden2, setHidden] = reactExports.useState(false);
      reactExports.useEffect(() => {
        setHidden(false);
      }, [items]);
      const itemRowMapping = reactExports.useMemo(() => {
        const rowIndexes = [];
        items.forEach((item2, index2) => {
          if (item2.type === "sample") {
            rowIndexes.push(index2);
          }
        });
        return rowIndexes;
      }, [items]);
      const prevSelectedIndexRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        const listEl = listHandle.current;
        if (listEl) {
          requestAnimationFrame(() => {
            setTimeout(() => {
              const actualRowIndex = itemRowMapping[selectedIndex];
              listEl.scrollToIndex(actualRowIndex);
              prevSelectedIndexRef.current = actualRowIndex;
            }, 10);
          });
        }
      }, [selectedIndex, listHandle, itemRowMapping]);
      const onkeydown = reactExports.useCallback(
        (e) => {
          switch (e.key) {
            case "ArrowUp":
              prevSample();
              e.preventDefault();
              e.stopPropagation();
              break;
            case "ArrowDown":
              nextSample();
              e.preventDefault();
              e.stopPropagation();
              break;
            case "Enter":
              showSample(selectedIndex);
              e.preventDefault();
              e.stopPropagation();
              break;
          }
        },
        [selectedIndex, nextSample, prevSample, showSample]
      );
      if (items.length === 0) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyPanel, { children: "No Samples" });
      }
      const renderRow = (item2) => {
        if (item2.type === "sample") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleRow,
            {
              id: `${item2.number}`,
              index: item2.index,
              sample: item2.data,
              height: kSampleHeight,
              sampleDescriptor,
              gridColumnsTemplate: gridColumnsValue(sampleDescriptor),
              selected: selectedIndex === item2.index,
              showSample
            }
          );
        } else if (item2.type === "separator") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleSeparator,
            {
              id: `sample-group${item2.number}`,
              title: item2.data,
              height: kSeparatorHeight
            }
          );
        } else {
          return null;
        }
      };
      const { input: input2, limit, answer: answer2, target: target2 } = gridColumns(sampleDescriptor);
      const sampleCount = items == null ? void 0 : items.reduce((prev, current) => {
        if (current.type === "sample") {
          return prev + 1;
        } else {
          return prev;
        }
      }, 0);
      const errorCount = items == null ? void 0 : items.reduce((previous, item2) => {
        if (typeof item2.data === "object" && item2.data.error) {
          return previous + 1;
        }
        return previous;
      }, 0);
      const limitCount = items == null ? void 0 : items.reduce((previous, item2) => {
        if (typeof item2.data === "object" && item2.data.limit) {
          return previous + 1;
        } else {
          return previous;
        }
      }, 0);
      const percentError = errorCount / sampleCount * 100;
      const percentLimit = limitCount / sampleCount * 100;
      const warningMessage = errorCount > 0 ? `INFO: ${errorCount} of ${sampleCount} samples (${formatNoDecimal(percentError)}%) had errors and were not scored.` : limitCount ? `INFO: ${limitCount} of ${sampleCount} samples (${formatNoDecimal(percentLimit)}%) completed due to exceeding a limit.` : void 0;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$c.mainLayout, children: [
        warningMessage ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          MessageBand,
          {
            message: warningMessage,
            hidden: hidden2,
            setHidden,
            type: "info"
          }
        ) : void 0,
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SampleHeader,
          {
            input: input2 !== "0",
            target: target2 !== "0",
            answer: answer2 !== "0",
            limit: limit !== "0",
            gridColumnsTemplate: gridColumnsValue(sampleDescriptor)
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          $r,
          {
            ref: listHandle,
            style: { height: "100%" },
            data: items,
            defaultItemHeight: 50,
            itemContent: (_index, data) => {
              return renderRow(data);
            },
            followOutput,
            atBottomStateChange: (atBottom) => {
              setFollowOutput(atBottom);
            },
            className: clsx(className2),
            onKeyDown: onkeydown,
            skipAnimationFrameInResizeObserver: true
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SampleFooter, { sampleCount })
      ] });
    };
    const gridColumnsValue = (sampleDescriptor) => {
      const { input: input2, target: target2, answer: answer2, limit, id, score: score2 } = gridColumns(sampleDescriptor);
      return `${id} ${input2} ${target2} ${answer2} ${limit} ${score2}`;
    };
    const gridColumns = (sampleDescriptor) => {
      const input2 = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.input) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.input) : 0;
      const target2 = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.target) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.target) : 0;
      const answer2 = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.answer) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.answer) : 0;
      const limit = (sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.normalized.limit) > 0 ? Math.max(0.15, sampleDescriptor.messageShape.normalized.limit) : 0;
      const id = Math.max(2, Math.min(10, sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.raw.id));
      const score2 = Math.max(
        3,
        Math.min(10, sampleDescriptor == null ? void 0 : sampleDescriptor.messageShape.raw.score)
      );
      const frSize = (val) => {
        if (val === 0) {
          return "0";
        } else {
          return `${val}fr`;
        }
      };
      return {
        input: frSize(input2),
        target: frSize(target2),
        answer: frSize(answer2),
        limit: frSize(limit),
        id: `${id}rem`,
        score: `${score2}rem`
      };
    };
    const getSampleProcessor = (samples, groupBy, groupByOrder, sampleDescriptor) => {
      if (groupBy == "epoch") {
        return groupByEpoch(samples, sampleDescriptor, groupByOrder);
      } else if (groupBy === "sample") {
        return groupBySample(samples, sampleDescriptor, groupByOrder);
      } else {
        return noGrouping(samples, groupByOrder);
      }
    };
    const noGrouping = (samples, order) => {
      const counter = getCounter(samples.length, 1, order);
      return (sample2, index2) => {
        counter.incrementItem();
        const itemCount = counter.item();
        return [
          {
            label: `Sample ${itemCount}`,
            number: itemCount,
            index: index2,
            data: sample2,
            type: "sample"
          }
        ];
      };
    };
    const groupBySample = (samples, sampleDescriptor, order) => {
      samples = samples.sort((a, b) => {
        if (typeof a.id === "string") {
          if (order === "asc") {
            return String(a.id).localeCompare(String(b.id));
          } else {
            return String(b.id).localeCompare(String(a.id));
          }
        } else {
          if (order === "asc") {
            return Number(a.id) - Number(b.id);
          } else {
            return Number(b.id) - Number(b.id);
          }
        }
      });
      const groupCount = samples.length / sampleDescriptor.evalDescriptor.epochs;
      const itemCount = samples.length / groupCount;
      const counter = getCounter(itemCount, groupCount, order);
      return (sample2, index2, previousSample) => {
        const results = [];
        const lastId = previousSample ? previousSample.id : void 0;
        if (sample2.id !== lastId) {
          counter.incrementGroup();
          results.push({
            label: `Sample ${itemCount}`,
            number: counter.group(),
            index: index2,
            data: `Sample ${counter.group()}`,
            type: "separator"
          });
          counter.resetItem();
        }
        counter.incrementItem();
        results.push({
          label: `Sample ${counter.group()} (Epoch ${counter.item()})`,
          number: counter.item(),
          index: index2,
          data: sample2,
          type: "sample"
        });
        return results;
      };
    };
    const groupByEpoch = (samples, sampleDescriptor, order) => {
      const groupCount = sampleDescriptor.evalDescriptor.epochs;
      const itemCount = samples.length / groupCount;
      const counter = getCounter(itemCount, groupCount, order);
      return (sample2, index2, previousSample) => {
        const results = [];
        const lastEpoch = previousSample ? previousSample.epoch : -1;
        if (lastEpoch !== sample2.epoch) {
          counter.incrementGroup();
          results.push({
            label: `Epoch ${counter.group()}`,
            number: counter.group(),
            index: index2,
            data: `Epoch ${counter.group()}`,
            type: "separator"
          });
          counter.resetItem();
        }
        counter.incrementItem();
        results.push({
          label: `Sample ${counter.item()} (Epoch ${counter.group()})`,
          number: counter.item(),
          index: index2,
          data: sample2,
          type: "sample"
        });
        return results;
      };
    };
    const getCounter = (itemCount, groupCount, order) => {
      let itemIndex = order !== "desc" ? 0 : itemCount + 1;
      let groupIndex = order !== "desc" ? 0 : groupCount + 1;
      return {
        resetItem: () => {
          itemIndex = order !== "desc" ? 0 : itemCount + 1;
        },
        incrementItem: () => {
          if (order !== "desc") {
            itemIndex++;
          } else {
            itemIndex--;
          }
        },
        incrementGroup: () => {
          if (order !== "desc") {
            groupIndex++;
          } else {
            groupIndex--;
          }
        },
        item: () => {
          return itemIndex;
        },
        group: () => {
          return groupIndex;
        }
      };
    };
    const SamplesTab = ({
      sample: sample2,
      samples,
      sampleMode,
      groupBy,
      groupByOrder,
      sampleDescriptor,
      sampleStatus,
      sampleError,
      selectedSampleIndex,
      setSelectedSampleIndex,
      showingSampleDialog,
      setShowingSampleDialog,
      selectedSampleTab,
      setSelectedSampleTab,
      sampleScrollPositionRef,
      setSampleScrollPosition,
      sampleTabScrollRef
    }) => {
      const [items, setItems] = reactExports.useState([]);
      const [sampleItems, setSampleItems] = reactExports.useState([]);
      const sampleListHandle = reactExports.useRef(null);
      const sampleDialogRef = reactExports.useRef(null);
      const showSample = reactExports.useCallback(
        (index2) => {
          setSelectedSampleIndex(index2);
          setShowingSampleDialog(true);
        },
        [setSelectedSampleIndex, setShowingSampleDialog]
      );
      reactExports.useEffect(() => {
        if (showingSampleDialog) {
          setTimeout(() => {
            var _a2;
            (_a2 = sampleDialogRef.current) == null ? void 0 : _a2.focus();
          }, 0);
        } else {
          setTimeout(() => {
            if (sampleListHandle.current) {
              sampleListHandle.current.scrollToIndex(0);
            }
          }, 0);
        }
      }, [showingSampleDialog]);
      reactExports.useEffect(() => {
        const sampleProcessor = sampleDescriptor ? getSampleProcessor(
          samples || [],
          groupBy,
          groupByOrder,
          sampleDescriptor
        ) : void 0;
        const items2 = samples == null ? void 0 : samples.flatMap((sample22, index2) => {
          const results = [];
          const previousSample2 = index2 !== 0 ? samples[index2 - 1] : void 0;
          const items3 = sampleProcessor ? sampleProcessor(sample22, index2, previousSample2) : [];
          results.push(...items3);
          return results;
        });
        setItems(items2 || []);
        setSampleItems(
          items2 ? items2.filter((item2) => {
            return item2.type === "sample";
          }) : []
        );
      }, [samples, groupBy, groupByOrder, sampleDescriptor]);
      const nextSampleIndex = reactExports.useCallback(() => {
        if (selectedSampleIndex < sampleItems.length - 1) {
          return selectedSampleIndex + 1;
        } else {
          return -1;
        }
      }, [selectedSampleIndex, sampleItems.length]);
      const previousSampleIndex = reactExports.useCallback(() => {
        return selectedSampleIndex > 0 ? selectedSampleIndex - 1 : -1;
      }, [selectedSampleIndex]);
      const nextSample = reactExports.useCallback(() => {
        const next = nextSampleIndex();
        if (sampleStatus !== "loading" && next > -1) {
          setSelectedSampleIndex(next);
        }
      }, [nextSampleIndex, sampleStatus, setSelectedSampleIndex]);
      const previousSample = reactExports.useCallback(() => {
        const prev = previousSampleIndex();
        if (sampleStatus !== "loading" && prev > -1) {
          setSelectedSampleIndex(prev);
        }
      }, [previousSampleIndex, sampleStatus, setSelectedSampleIndex]);
      const title2 = selectedSampleIndex > -1 && sampleItems.length > selectedSampleIndex ? sampleItems[selectedSampleIndex].label : "";
      if (!sampleDescriptor) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyPanel, {});
      } else {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
          sampleDescriptor && sampleMode === "single" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            InlineSampleDisplay,
            {
              id: "sample-display",
              sample: sample2,
              sampleStatus,
              sampleError,
              sampleDescriptor,
              selectedTab: selectedSampleTab,
              setSelectedTab: setSelectedSampleTab,
              scrollRef: sampleTabScrollRef
            }
          ) : void 0,
          sampleDescriptor && sampleMode === "many" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleList,
            {
              listHandle: sampleListHandle,
              items,
              sampleDescriptor,
              selectedIndex: selectedSampleIndex,
              nextSample,
              prevSample: previousSample,
              showSample
            }
          ) : void 0,
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleDialog,
            {
              id: String((sample2 == null ? void 0 : sample2.id) || ""),
              title: title2,
              sample: sample2,
              sampleStatus,
              sampleError,
              sampleDescriptor,
              showingSampleDialog,
              setShowingSampleDialog,
              selectedTab: selectedSampleTab,
              setSelectedTab: setSelectedSampleTab,
              nextSample,
              prevSample: previousSample,
              sampleScrollPositionRef,
              setSampleScrollPosition
            }
          )
        ] });
      }
    };
    const ghCommitUrl = (origin, commit) => {
      const baseUrl = origin.replace(/\.git$/, "");
      return `${baseUrl}/commit/${commit}`;
    };
    const item = "_item_1uzhd_1";
    const styles$b = {
      item
    };
    const DatasetDetailView = ({
      dataset,
      style: style2
    }) => {
      const filtered = Object.fromEntries(
        Object.entries(dataset).filter(([key2]) => key2 !== "sample_ids")
      );
      if (!dataset || Object.keys(filtered).length === 0) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: clsx("text-size-base", styles$b.item), style: style2, children: "No dataset information available" });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        MetaDataView,
        {
          className: clsx("text-size-base", styles$b.item),
          entries: filtered,
          tableOptions: "borderless,sm",
          style: style2
        }
      );
    };
    const DetailStep = ({
      icon,
      name: name2,
      params: params2,
      className: className2
    }) => {
      const iconHtml = icon ? /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: clsx(icon, styles$b.icon) }) : "";
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(className2), children: [
        iconHtml,
        " ",
        name2,
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.container, children: params2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(MetaDataView, { entries: params2, className: "text-size-small" }) : "" })
      ] });
    };
    const ScorerDetailView = ({
      name: name2,
      scores: scores2,
      params: params2
    }) => {
      if (scores2.length > 1) {
        params2["scores"] = scores2;
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        DetailStep,
        {
          icon: ApplicationIcons.scorer,
          name: name2,
          params: params2,
          className: clsx(styles$b.item, "text-size-base")
        }
      );
    };
    const container$4 = "_container_12g3a_1";
    const separator = "_separator_12g3a_10";
    const styles$a = {
      container: container$4,
      separator
    };
    const SolversDetailView = ({ steps }) => {
      const separator2 = /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$a.items, "text-size-small", styles$a.separator), children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.arrows.right }) });
      const details = steps == null ? void 0 : steps.map((step, index2) => {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            DetailStep,
            {
              name: step.solver,
              className: clsx(styles$a.items, "text-size-small")
            }
          ),
          index2 < steps.length - 1 ? separator2 : ""
        ] }, `solver-step-${index2}`);
      });
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$a.container, children: details });
    };
    const floatingCol = "_floatingCol_q6xma_1";
    const wideCol = "_wideCol_q6xma_9";
    const oneCol = "_oneCol_q6xma_16";
    const twoCol = "_twoCol_q6xma_20";
    const planCol = "_planCol_q6xma_24";
    const container$3 = "_container_q6xma_28";
    const grid = "_grid_q6xma_34";
    const row = "_row_q6xma_42";
    const styles$9 = {
      floatingCol,
      wideCol,
      oneCol,
      twoCol,
      planCol,
      container: container$3,
      grid,
      row
    };
    const PlanDetailView = ({
      evaluation,
      plan,
      scores: scores2
    }) => {
      if (!evaluation) {
        return null;
      }
      const config2 = {};
      Object.entries((evaluation == null ? void 0 : evaluation.config) || {}).forEach((entry2) => {
        const key2 = entry2[0];
        const value2 = entry2[1];
        config2[key2] = value2;
      });
      const steps = plan == null ? void 0 : plan.steps;
      const metadata2 = evaluation == null ? void 0 : evaluation.metadata;
      const revision = evaluation == null ? void 0 : evaluation.revision;
      const packages = evaluation == null ? void 0 : evaluation.packages;
      const model_args = evaluation == null ? void 0 : evaluation.model_args;
      const task_args = evaluation == null ? void 0 : evaluation.task_args;
      const generate_config = plan == null ? void 0 : plan.config;
      const taskInformation = {
        ["Task ID"]: evaluation == null ? void 0 : evaluation.task_id,
        ["Run ID"]: evaluation == null ? void 0 : evaluation.run_id
      };
      if (revision) {
        taskInformation[`${revision.type ? `${toTitleCase(revision.type)} ` : ""}Revision`] = {
          _html: /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: ghCommitUrl(revision.origin, revision.commit), children: revision.commit })
        };
      }
      if (packages) {
        const names = Object.keys(packages).map((key2) => {
          return `${key2} ${packages[key2]}`;
        });
        if (names.length === 1) {
          taskInformation["Inspect"] = names[0];
        } else {
          taskInformation["Inspect"] = names;
        }
      }
      if (evaluation.tags) {
        taskInformation["Tags"] = evaluation.tags.join(", ");
      }
      if ((evaluation == null ? void 0 : evaluation.model) && evaluation.model !== kModelNone) {
        config2["model"] = evaluation.model;
      }
      if (evaluation == null ? void 0 : evaluation.model_base_url) {
        config2["model_base_url"] = evaluation.model_base_url;
      }
      if (evaluation == null ? void 0 : evaluation.sandbox) {
        if (Array.isArray(evaluation == null ? void 0 : evaluation.sandbox)) {
          config2["sandbox"] = evaluation.sandbox[0];
          if (evaluation.sandbox[1]) {
            config2["sandbox_config"] = evaluation.sandbox[1];
          }
        } else {
          config2["sandbox"] = evaluation == null ? void 0 : evaluation.sandbox.type;
          config2["sandbox_config"] = evaluation == null ? void 0 : evaluation.sandbox.config;
        }
      }
      const taskColumns = [];
      taskColumns.push({
        title: "Dataset",
        className: styles$9.floatingCol,
        contents: /* @__PURE__ */ jsxRuntimeExports.jsx(DatasetDetailView, { dataset: evaluation.dataset })
      });
      if (steps) {
        taskColumns.push({
          title: "Solvers",
          className: styles$9.wideCol,
          contents: /* @__PURE__ */ jsxRuntimeExports.jsx(SolversDetailView, { steps })
        });
      }
      if (scores2) {
        const scorers = scores2.reduce(
          (accum, score2) => {
            if (!accum[score2.scorer]) {
              accum[score2.scorer] = {
                scores: [score2.name],
                params: score2.params
              };
            } else {
              accum[score2.scorer].scores.push(score2.name);
            }
            return accum;
          },
          {}
        );
        if (Object.keys(scorers).length > 0) {
          const label2 = Object.keys(scorers).length === 1 ? "Scorer" : "Scorers";
          const scorerPanels = Object.keys(scorers).map((key2) => {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              ScorerDetailView,
              {
                name: key2,
                scores: scorers[key2].scores,
                params: scorers[key2].params
              },
              key2
            );
          });
          taskColumns.push({
            title: label2,
            className: styles$9.floatingCol,
            contents: scorerPanels
          });
        }
      }
      const metadataColumns = [];
      const cols = colCount(
        metadataColumns,
        task_args,
        model_args,
        config2,
        metadata2
      );
      metadataColumns.push({
        title: "Task Information",
        className: cols === 1 ? styles$9.oneCol : styles$9.twoCol,
        contents: /* @__PURE__ */ jsxRuntimeExports.jsx(
          MetaDataView,
          {
            className: "text-size-small",
            entries: taskInformation,
            tableOptions: "sm"
          },
          `plan-md-task`
        )
      });
      if (task_args && Object.keys(task_args).length > 0) {
        metadataColumns.push({
          title: "Task Args",
          className: cols === 1 ? styles$9.oneCol : styles$9.twoCol,
          contents: /* @__PURE__ */ jsxRuntimeExports.jsx(
            MetaDataView,
            {
              className: "text-size-small",
              entries: task_args,
              tableOptions: "sm"
            },
            `plan-md-task-args`
          )
        });
      }
      if (model_args && Object.keys(model_args).length > 0) {
        metadataColumns.push({
          title: "Model Args",
          className: cols === 1 ? styles$9.oneCol : styles$9.twoCol,
          contents: /* @__PURE__ */ jsxRuntimeExports.jsx(
            MetaDataView,
            {
              className: "text-size-small",
              entries: model_args,
              tableOptions: "sm"
            },
            `plan-md-model-args`
          )
        });
      }
      if (config2 && Object.keys(config2).length > 0) {
        metadataColumns.push({
          title: "Configuration",
          className: cols === 1 ? styles$9.oneCol : styles$9.twoCol,
          contents: /* @__PURE__ */ jsxRuntimeExports.jsx(
            MetaDataView,
            {
              className: "text-size-small",
              entries: config2,
              tableOptions: "sm"
            },
            `plan-md-config`
          )
        });
      }
      if (generate_config && Object.keys(generate_config).length > 0) {
        const generate_record = Object.fromEntries(
          Object.entries(generate_config)
        );
        metadataColumns.push({
          title: "Generate Config",
          className: cols === 1 ? styles$9.oneCol : styles$9.twoCol,
          contents: /* @__PURE__ */ jsxRuntimeExports.jsx(
            MetaDataView,
            {
              className: "text-size-small",
              entries: generate_record,
              tableOptions: "sm"
            },
            `plan-md-generate-config`
          )
        });
      }
      if (metadata2 && Object.keys(metadata2).length > 0) {
        metadataColumns.push({
          title: "Metadata",
          className: cols === 1 ? styles$9.oneCol : styles$9.twoCol,
          contents: /* @__PURE__ */ jsxRuntimeExports.jsx(
            MetaDataView,
            {
              className: "text-size-small",
              entries: metadata2,
              tableOptions: "sm"
            },
            `plan-md-metadata`
          )
        });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.container, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: styles$9.grid,
            style: {
              gridTemplateColumns: `repeat(${taskColumns.length}, auto)`
            },
            children: taskColumns.map((col) => {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(
                PlanColumn,
                {
                  title: col.title,
                  className: col.className,
                  children: col.contents
                },
                `plan-col-${col.title}`
              );
            })
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(styles$9.row), children: metadataColumns.map((col) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            PlanColumn,
            {
              title: col.title,
              className: col.className,
              children: col.contents
            },
            `plan-col-${col.title}`
          );
        }) })
      ] });
    };
    const colCount = (...other) => {
      let count = 0;
      for (const o in other) {
        if (o && Object.keys(o).length > 0) {
          count++;
        }
      }
      return count;
    };
    const PlanColumn = ({ title: title2, className: className2, children: children2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(className2), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: clsx(
              "card-subheading",
              "text-size-small",
              "text-style-label",
              "text-style-secondary",
              styles$9.planCol
            ),
            children: title2
          }
        ),
        children2
      ] });
    };
    const PlanCard = ({ evalSpec, evalPlan, scores: scores2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { icon: ApplicationIcons.config, label: "Config" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { id: "task-plan-card-body", children: /* @__PURE__ */ jsxRuntimeExports.jsx(PlanDetailView, { evaluation: evalSpec, plan: evalPlan, scores: scores2 }) })
      ] });
    };
    const wrapper$1 = "_wrapper_11ije_1";
    const col1 = "_col1_11ije_8";
    const col2 = "_col2_11ije_13";
    const styles$8 = {
      wrapper: wrapper$1,
      col1,
      col2
    };
    const kUsageCardBodyId = "usage-card-body";
    const UsageCard = ({ stats }) => {
      if (!stats) {
        return null;
      }
      const totalDuration = formatDuration(
        new Date(stats.started_at),
        new Date(stats.completed_at)
      );
      const usageMetadataStyle = {
        fontSize: FontSize.smaller
      };
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { icon: ApplicationIcons.usage, label: "Usage" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { id: kUsageCardBodyId, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$8.wrapper, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$8.col1, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  "text-size-smaller",
                  "text-style-label",
                  "text-style-secondary"
                ),
                children: "Duration"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              MetaDataView,
              {
                entries: {
                  ["Start"]: new Date(stats.started_at).toLocaleString(),
                  ["End"]: new Date(stats.completed_at).toLocaleString(),
                  ["Duration"]: totalDuration
                },
                tableOptions: "borderless,sm",
                style: usageMetadataStyle
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$8.col2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ModelTokenTable, { model_usage: stats.model_usage }) })
        ] }) })
      ] });
    };
    const styles$7 = {
      "task-error-display": "_task-error-display_1624b_1"
    };
    const TaskErrorCard = ({ error: error2 }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          CardHeader,
          {
            icon: ApplicationIcons.error,
            label: "Task Failed: ${error.message}"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardBody, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ANSIDisplay,
          {
            output: error2.traceback_ansi,
            className: styles$7["task-error-display"]
          }
        ) })
      ] });
    };
    const InfoTab = ({
      evalSpec,
      evalPlan,
      evalResults,
      evalStats,
      samples,
      evalStatus,
      evalError
    }) => {
      const [hidden2, setHidden] = reactExports.useState(false);
      reactExports.useEffect(() => {
        setHidden(false);
      }, [evalSpec, evalPlan, evalResults, evalStats, samples]);
      const showWarning = (!samples || samples.length === 0) && evalStatus === "success" && (evalSpec == null ? void 0 : evalSpec.dataset.samples) && evalSpec.dataset.samples > 0;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { width: "100%" }, children: [
        showWarning ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          MessageBand,
          {
            message: "Unable to display samples (this evaluation log may be too large).",
            hidden: hidden2,
            setHidden,
            type: "warning"
          }
        ) : "",
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { padding: "0.5em 1em 0 1em", width: "100%" }, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PlanCard,
            {
              evalSpec,
              evalPlan,
              scores: evalResults == null ? void 0 : evalResults.scores
            }
          ),
          evalStatus !== "started" ? /* @__PURE__ */ jsxRuntimeExports.jsx(UsageCard, { stats: evalStats }) : void 0,
          evalStatus === "error" && evalError ? /* @__PURE__ */ jsxRuntimeExports.jsx(TaskErrorCard, { error: evalError }) : void 0
        ] })
      ] });
    };
    const navbarWrapper = "_navbarWrapper_838qu_48";
    const styles$6 = {
      navbarWrapper
    };
    const copyButton = "_copyButton_1goi8_1";
    const styles$5 = {
      copyButton
    };
    const CopyButton = ({
      value: value2,
      onCopySuccess,
      onCopyError,
      className: className2 = "",
      ariaLabel = "Copy to clipboard"
    }) => {
      const [isCopied, setIsCopied] = reactExports.useState(false);
      const handleClick = async () => {
        try {
          await navigator.clipboard.writeText(value2);
          setIsCopied(true);
          onCopySuccess == null ? void 0 : onCopySuccess();
          setTimeout(() => {
            setIsCopied(false);
          }, 1250);
        } catch (error2) {
          onCopyError == null ? void 0 : onCopyError(
            error2 instanceof Error ? error2 : new Error("Failed to copy")
          );
        }
      };
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: clsx(styles$5.copyButton, className2),
          onClick: handleClick,
          "aria-label": ariaLabel,
          disabled: isCopied,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "i",
            {
              className: isCopied ? `${ApplicationIcons.confirm} primary` : ApplicationIcons.copy,
              "aria-hidden": "true"
            }
          )
        }
      );
    };
    const container$2 = "_container_1w9cu_1";
    const wrapper = "_wrapper_1w9cu_8";
    const toggle = "_toggle_1w9cu_14";
    const body = "_body_1w9cu_19";
    const bodyContainer = "_bodyContainer_1w9cu_25";
    const taskTitle = "_taskTitle_1w9cu_31";
    const taskModel = "_taskModel_1w9cu_36";
    const taskStatus = "_taskStatus_1w9cu_40";
    const secondaryContainer = "_secondaryContainer_1w9cu_46";
    const styles$4 = {
      container: container$2,
      wrapper,
      toggle,
      body,
      bodyContainer,
      taskTitle,
      taskModel,
      taskStatus,
      secondaryContainer
    };
    const simpleMetricsRows = "_simpleMetricsRows_tnqkm_1";
    const multiMetricsRows = "_multiMetricsRows_tnqkm_12";
    const verticalMetricReducer = "_verticalMetricReducer_tnqkm_26";
    const verticalMetricName = "_verticalMetricName_tnqkm_33";
    const verticalMetricValue = "_verticalMetricValue_tnqkm_41";
    const multiScorer = "_multiScorer_tnqkm_46";
    const multiScorerIndent = "_multiScorerIndent_tnqkm_54";
    const multiScorerReducer = "_multiScorerReducer_tnqkm_58";
    const multiScorerLabel = "_multiScorerLabel_tnqkm_64";
    const multiScorerValue = "_multiScorerValue_tnqkm_70";
    const multiScorerValueContent = "_multiScorerValueContent_tnqkm_79";
    const multiScoreMetricGrid = "_multiScoreMetricGrid_tnqkm_84";
    const styles$3 = {
      simpleMetricsRows,
      multiMetricsRows,
      verticalMetricReducer,
      verticalMetricName,
      verticalMetricValue,
      multiScorer,
      multiScorerIndent,
      multiScorerReducer,
      multiScorerLabel,
      multiScorerValue,
      multiScorerValueContent,
      multiScoreMetricGrid
    };
    const ResultsPanel = ({ results }) => {
      var _a2, _b2;
      if (((_a2 = results == null ? void 0 : results.scores) == null ? void 0 : _a2.length) === 1) {
        const scorers = {};
        results.scores.map((score2) => {
          scorers[score2.name] = Object.keys(score2.metrics).map((key2) => {
            return {
              reducer: score2.reducer,
              metric: {
                name: key2,
                value: score2.metrics[key2].value,
                params: score2.metrics[key2].params,
                metadata: {}
              }
            };
          });
        });
        const metrics = Object.values(scorers)[0];
        const showReducer = metrics && metrics.length > 0 && !!metrics[0].reducer;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$3.simpleMetricsRows, children: metrics.map((metric2, i2) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            VerticalMetric,
            {
              metricSummary: metric2,
              isFirst: i2 === 0,
              showReducer
            },
            `simple-metric-${i2}`
          );
        }) });
      } else {
        const showReducer = (results == null ? void 0 : results.scores.findIndex((score2) => !!score2.reducer)) !== -1;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$3.multiMetricsRows, children: (_b2 = results == null ? void 0 : results.scores) == null ? void 0 : _b2.map((score2, index2) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            MultiScorerMetric,
            {
              scorer: score2,
              isFirst: index2 === 0,
              showReducer
            },
            `multi-metric-${index2}`
          );
        }) });
      }
    };
    const VerticalMetric = ({
      metricSummary,
      isFirst,
      showReducer
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { paddingLeft: isFirst ? "0" : "1em" }, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: clsx(
              "vertical-metric-label",
              "text-style-label",
              "text-style-secondary",
              styles$3.verticalMetricName
            ),
            children: metricDisplayName(metricSummary.metric)
          }
        ),
        showReducer ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: clsx(
              "text-style-label",
              "text-style-secondary",
              styles$3.verticalMetricReducer
            ),
            children: metricSummary.reducer || "default"
          }
        ) : void 0,
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: clsx(
              "vertical-metric-value",
              "text-size-largest",
              styles$3.verticalMetricValue
            ),
            children: formatPrettyDecimal(metricSummary.metric.value)
          }
        )
      ] });
    };
    const MultiScorerMetric = ({
      scorer,
      isFirst,
      showReducer
    }) => {
      const titleFontClz = "text-size-base";
      const reducerFontClz = "text-size-smaller";
      const valueFontClz = "text-size-base";
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: clsx(
            styles$3.multiScorer,
            isFirst ? styles$3.multiScorerIndent : void 0
          ),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  titleFontClz,
                  "text-style-label",
                  "text-style-secondary",
                  "multi-score-label",
                  styles$3.multiScorerLabel
                ),
                children: scorer.name
              }
            ),
            showReducer ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: clsx(
                  reducerFontClz,
                  "text-style-label",
                  "text-style-secondary",
                  styles$3.multiScorerReducer
                ),
                children: scorer.reducer || "default"
              }
            ) : void 0,
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(valueFontClz, styles$3.multiScorerValue), children: Object.keys(scorer.metrics).map((key2) => {
              const metric2 = scorer.metrics[key2];
              return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$3.multiScoreMetricGrid, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: metricDisplayName(metric2) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$3.multiScorerValueContent, children: formatPrettyDecimal(metric2.value) })
              ] }, key2);
            }) })
          ]
        }
      );
    };
    const statusPanel = "_statusPanel_66f9o_1";
    const statusIcon = "_statusIcon_66f9o_11";
    const styles$2 = {
      statusPanel,
      statusIcon
    };
    const CancelledPanel = ({ sampleCount }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatusPanel,
        {
          icon: ApplicationIcons.logging["info"],
          status: "Cancelled",
          sampleCount
        }
      );
    };
    const ErroredPanel = ({ sampleCount }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatusPanel,
        {
          icon: ApplicationIcons.logging["error"],
          status: "Task Failed",
          sampleCount
        }
      );
    };
    const RunningPanel = ({ sampleCount }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatusPanel,
        {
          icon: ApplicationIcons.running,
          status: "Running",
          sampleCount
        }
      );
    };
    const StatusPanel = ({ icon, status, sampleCount }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$2.statusPanel, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: clsx(icon, styles$2.statusIcon), style: {} }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: status }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            "(",
            sampleCount,
            " ",
            sampleCount === 1 ? "sample" : "samples",
            ")"
          ] })
        ] })
      ] });
    };
    const PrimaryBar = ({
      showToggle,
      offcanvas,
      status,
      evalResults,
      samples,
      file,
      evalSpec,
      setOffcanvas
    }) => {
      const logFileName = file ? filename(file) : "";
      const handleToggle = reactExports.useCallback(() => {
        setOffcanvas(!offcanvas);
      }, [setOffcanvas, offcanvas]);
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$4.wrapper), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: clsx(
              "navbar-brand",
              "navbar-text",
              "mb-0",
              styles$4.container
            ),
            children: [
              showToggle ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  id: "sidebarToggle",
                  onClick: handleToggle,
                  className: clsx(
                    "btn",
                    offcanvas ? "d-md-none" : void 0,
                    styles$4.toggle
                  ),
                  type: "button",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("i", { className: ApplicationIcons.menu })
                }
              ) : "",
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$4.body, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$4.bodyContainer, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      id: "task-title",
                      className: clsx("task-title", "text-truncate", styles$4.taskTitle),
                      title: evalSpec == null ? void 0 : evalSpec.task,
                      children: evalSpec == null ? void 0 : evalSpec.task
                    }
                  ),
                  (evalSpec == null ? void 0 : evalSpec.model) && evalSpec.model !== kModelNone ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      id: "task-model",
                      className: clsx(
                        "task-model",
                        "text-truncate",
                        styles$4.taskModel,
                        "text-size-base"
                      ),
                      title: evalSpec == null ? void 0 : evalSpec.model,
                      children: evalSpec == null ? void 0 : evalSpec.model
                    }
                  ) : ""
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("text-size-small", styles$4.secondaryContainer), children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("navbar-secondary-text", "text-truncate"), children: logFileName }),
                  file ? /* @__PURE__ */ jsxRuntimeExports.jsx(CopyButton, { value: file }) : ""
                ] })
              ] })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(styles$4.taskStatus, "navbar-text"), children: [
          status === "success" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ResultsPanel, { results: evalResults }) : void 0,
          status === "cancelled" ? /* @__PURE__ */ jsxRuntimeExports.jsx(CancelledPanel, { sampleCount: (samples == null ? void 0 : samples.length) || 0 }) : void 0,
          status === "started" ? /* @__PURE__ */ jsxRuntimeExports.jsx(RunningPanel, { sampleCount: (samples == null ? void 0 : samples.length) || 0 }) : void 0,
          status === "error" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ErroredPanel, { sampleCount: (samples == null ? void 0 : samples.length) || 0 }) : void 0
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id: "task-created", style: { display: "none" }, children: evalSpec == null ? void 0 : evalSpec.created })
      ] });
    };
    const LabeledValue = ({
      layout = "column",
      style: style2,
      label: label2,
      children: children2,
      valueStyle,
      className: className2
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: clsx(
            "labeled-value",
            layout === "column" ? "column" : "row",
            className2
          ),
          style: {
            ...style2
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: "labeled-value-label text-style-label text-style-secondary",
                children: label2
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "labeled-value-value", style: { ...valueStyle }, children: children2 })
          ]
        }
      );
    };
    const staticCol = "_staticCol_xzzhl_1";
    const justifyLeft = "_justifyLeft_xzzhl_5";
    const justifyCenter = "_justifyCenter_xzzhl_9";
    const justifyRight = "_justifyRight_xzzhl_13";
    const valueGrid = "_valueGrid_xzzhl_17";
    const container$1 = "_container_xzzhl_25";
    const styles$1 = {
      staticCol,
      justifyLeft,
      justifyCenter,
      justifyRight,
      valueGrid,
      container: container$1
    };
    const SecondaryBar = ({
      evalSpec,
      evalPlan,
      evalResults,
      evalStats,
      samples,
      evalDescriptor,
      status
    }) => {
      if (!evalSpec || status !== "success") {
        return null;
      }
      const epochs = evalSpec.config.epochs || 1;
      const hyperparameters = {
        ...(evalPlan == null ? void 0 : evalPlan.config) || {},
        ...evalSpec.task_args || {}
      };
      const hasConfig = Object.keys(hyperparameters).length > 0;
      const values = [];
      values.push({
        size: "minmax(12%, auto)",
        value: /* @__PURE__ */ jsxRuntimeExports.jsx(
          LabeledValue,
          {
            label: "Dataset",
            className: "text-size-small",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              DatasetSummary,
              {
                dataset: evalSpec.dataset,
                samples,
                epochs
              }
            )
          },
          "sb-dataset"
        )
      });
      const label2 = (evalResults == null ? void 0 : evalResults.scores) && evalResults.scores.length > 1 ? "Scorers" : "Scorer";
      values.push({
        size: "minmax(12%, auto)",
        value: /* @__PURE__ */ jsxRuntimeExports.jsx(
          LabeledValue,
          {
            label: label2,
            className: clsx(
              styles$1.staticCol,
              hasConfig ? styles$1.justifyLeft : styles$1.justifyCenter,
              "text-size-small"
            ),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(ScorerSummary, { evalDescriptor })
          },
          "sb-scorer"
        )
      });
      if (hasConfig) {
        values.push({
          size: "minmax(12%, auto)",
          value: /* @__PURE__ */ jsxRuntimeExports.jsx(
            LabeledValue,
            {
              label: "Config",
              className: clsx(styles$1.justifyRight, "text-size-small"),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(ParamSummary, { params: hyperparameters })
            },
            "sb-params"
          )
        });
      }
      if (evalStats) {
        const totalDuration = formatDuration(
          new Date(evalStats == null ? void 0 : evalStats.started_at),
          new Date(evalStats == null ? void 0 : evalStats.completed_at)
        );
        values.push({
          size: "minmax(12%, auto)",
          value: /* @__PURE__ */ jsxRuntimeExports.jsx(
            LabeledValue,
            {
              label: "Duration",
              className: clsx(styles$1.justifyRight, "text-size-small"),
              children: totalDuration
            },
            "sb-duration"
          )
        });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ExpandablePanel,
        {
          className: clsx(styles$1.container, "text-size-small"),
          collapse: true,
          lines: 4,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: styles$1.valueGrid,
              style: {
                gridTemplateColumns: `${values.map((val) => {
                  return val.size;
                }).join(" ")}`
              },
              children: values.map((val) => {
                return val.value;
              })
            }
          )
        }
      );
    };
    const DatasetSummary = ({
      dataset,
      samples,
      epochs
    }) => {
      if (!dataset) {
        return null;
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: (samples == null ? void 0 : samples.length) ? formatDataset(samples.length, epochs, dataset.name) : "" });
    };
    const ScorerSummary = ({ evalDescriptor }) => {
      if (!evalDescriptor) {
        return null;
      }
      const items = scoreFilterItems(evalDescriptor);
      return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: { position: "relative" }, children: Array.from(items).map((item2, index2, array) => /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { title: item2.tooltip, children: item2.canonicalName }),
        index2 < array.length - 1 ? ", " : ""
      ] }, index2)) });
    };
    const ParamSummary = ({ params: params2 }) => {
      if (!params2) {
        return null;
      }
      const paraValues = Object.keys(params2).map((key2) => {
        const val = params2[key2];
        if (Array.isArray(val) || typeof val === "object") {
          return `${key2}: ${JSON.stringify(val)}`;
        } else {
          return `${key2}: ${val}`;
        }
      });
      if (paraValues.length > 0) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("code", { style: { padding: 0, color: "var(--bs-body-color)" }, children: paraValues.join(", ") });
      } else {
        return null;
      }
    };
    const Navbar = ({
      file,
      evalSpec,
      evalPlan,
      evalResults,
      evalStats,
      samples,
      evalDescriptor,
      showToggle,
      offcanvas,
      setOffcanvas,
      status
    }) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("nav", { className: clsx("navbar", "sticky-top", styles$6.navbarWrapper), children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          PrimaryBar,
          {
            file,
            evalSpec,
            evalResults,
            samples,
            showToggle,
            offcanvas,
            setOffcanvas,
            status
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SecondaryBar,
          {
            evalSpec,
            evalPlan,
            evalResults,
            evalStats,
            samples,
            evalDescriptor,
            status
          }
        )
      ] });
    };
    const workspace = "_workspace_1r3mu_1";
    const tabContainer = "_tabContainer_1r3mu_6";
    const tabSet = "_tabSet_1r3mu_14";
    const tabs = "_tabs_1r3mu_21";
    const tabPanels = "_tabPanels_1r3mu_29";
    const styles = {
      workspace,
      tabContainer,
      tabSet,
      tabs,
      tabPanels
    };
    const WorkSpaceView = ({
      logFileName,
      evalSpec,
      evalPlan,
      evalResults,
      evalStats,
      samples,
      evalDescriptor,
      status,
      showToggle,
      selectedTab,
      tabs: tabs2,
      setSelectedTab,
      divRef,
      offcanvas,
      setOffcanvas,
      workspaceTabScrollPositionRef,
      setWorkspaceTabScrollPosition
    }) => {
      const debouncedScroll = reactExports.useMemo(() => {
        return debounce$1((id, position) => {
          setWorkspaceTabScrollPosition(id, position);
        }, 100);
      }, [setWorkspaceTabScrollPosition]);
      const onScroll = reactExports.useCallback(
        (id, position) => {
          debouncedScroll(id, position);
        },
        [debouncedScroll]
      );
      const onSelected = reactExports.useCallback(
        (e) => {
          var _a2;
          const id = (_a2 = e.currentTarget) == null ? void 0 : _a2.id;
          if (id) {
            setSelectedTab(id);
          }
        },
        [setSelectedTab]
      );
      const handleScroll = reactExports.useCallback(
        (tabid, position) => {
          onScroll(tabid, position);
        },
        [onScroll]
      );
      if (evalSpec === void 0) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyPanel, {});
      } else {
        const tabTools2 = Object.keys(tabs2).map((key2) => {
          const tab2 = tabs2[key2];
          return tab2;
        }).filter((tab2) => {
          return tab2.id === selectedTab;
        }).map((tab2) => {
          if (tab2.tools) {
            const tools2 = tab2.tools();
            return tools2;
          } else {
            return null;
          }
        });
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Navbar,
            {
              evalSpec,
              evalPlan,
              evalResults,
              evalStats,
              samples,
              evalDescriptor,
              status,
              file: logFileName,
              showToggle,
              offcanvas,
              setOffcanvas
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: divRef, className: clsx("workspace", styles.workspace), children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("log-detail", styles.tabContainer), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            TabSet,
            {
              id: "log-details",
              tools: tabTools2,
              type: "pills",
              className: clsx(styles.tabSet, "text-size-smaller"),
              tabControlsClassName: clsx(styles.tabs, "text-size-smaller"),
              tabPanelsClassName: clsx(styles.tabPanels),
              children: Object.keys(tabs2).map((key2) => {
                var _a2;
                const tab2 = tabs2[key2];
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  TabPanel,
                  {
                    id: tab2.id,
                    title: tab2.label,
                    onSelected,
                    selected: selectedTab === tab2.id,
                    scrollable: !!tab2.scrollable,
                    scrollRef: tab2.scrollRef,
                    scrollPosition: (_a2 = workspaceTabScrollPositionRef.current) == null ? void 0 : _a2[tab2.id],
                    setScrollPosition: (position) => {
                      handleScroll(tab2.id, position);
                    },
                    children: tab2.content()
                  },
                  tab2.id
                );
              })
            }
          ) }) })
        ] });
      }
    };
    const WorkSpace = (props) => {
      const {
        task_id,
        evalStatus,
        logFileName,
        evalSpec,
        evalPlan,
        evalStats,
        evalResults,
        samples,
        showToggle,
        offcanvas,
        setOffcanvas,
        samplesDescriptor,
        selectedTab,
        setSelectedTab,
        workspaceTabScrollPositionRef,
        setWorkspaceTabScrollPosition
      } = props;
      const divRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        if (divRef.current) {
          divRef.current.scrollTop = 0;
        }
      }, [task_id]);
      const resolvedTabs = useResolvedTabs(props);
      if (!evalSpec) {
        return void 0;
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        WorkSpaceView,
        {
          logFileName,
          divRef,
          evalSpec,
          evalPlan,
          evalResults,
          evalStats,
          samples,
          evalDescriptor: samplesDescriptor == null ? void 0 : samplesDescriptor.evalDescriptor,
          status: evalStatus,
          tabs: resolvedTabs,
          selectedTab,
          showToggle,
          offcanvas,
          setSelectedTab,
          workspaceTabScrollPositionRef,
          setWorkspaceTabScrollPosition,
          setOffcanvas
        }
      );
    };
    const copyFeedback = (e) => {
      const textEl = e.currentTarget.querySelector(".task-btn-copy-content");
      const iconEl = e.currentTarget.querySelector("i.bi");
      if (textEl) {
        const htmlEl = textEl;
        const htmlIconEl = iconEl;
        const oldText = htmlEl.innerText;
        const oldIconClz = htmlIconEl.className;
        htmlEl.innerText = "Copied!";
        htmlIconEl.className = `${ApplicationIcons.confirm}`;
        setTimeout(() => {
          var _a2;
          (_a2 = window.getSelection()) == null ? void 0 : _a2.removeAllRanges();
        }, 50);
        setTimeout(() => {
          htmlEl.innerText = oldText;
          htmlIconEl.className = oldIconClz;
        }, 1250);
      }
    };
    const useResolvedTabs = ({
      evalVersion,
      evalStatus,
      sampleMode,
      samples,
      selectedSample,
      sampleStatus,
      sampleError,
      showingSampleDialog,
      setShowingSampleDialog,
      groupBy,
      groupByOrder,
      selectedSampleIndex,
      setSelectedSampleIndex,
      samplesDescriptor,
      selectedSampleTab,
      setSelectedSampleTab,
      filter,
      sort,
      epoch,
      sampleScrollPositionRef,
      setSampleScrollPosition,
      epochs,
      setEpoch,
      setFilter,
      setSort,
      score: score2,
      setScore,
      scores: scores2,
      evalSpec,
      evalPlan,
      evalResults,
      evalStats,
      evalError,
      logFileName,
      capabilities: capabilities2,
      selectedTab,
      refreshLog
    }) => {
      const sampleTabScrollRef = reactExports.useRef(null);
      const samplesTab = sampleMode !== "none" ? {
        id: kEvalWorkspaceTabId,
        scrollable: (samples == null ? void 0 : samples.length) === 1,
        scrollRef: sampleTabScrollRef,
        label: (samples || []).length > 1 ? "Samples" : "Sample",
        content: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
          SamplesTab,
          {
            sample: selectedSample,
            sampleStatus,
            sampleError,
            showingSampleDialog,
            setShowingSampleDialog,
            samples,
            sampleMode,
            groupBy,
            groupByOrder,
            selectedSampleIndex,
            setSelectedSampleIndex,
            sampleDescriptor: samplesDescriptor,
            selectedSampleTab,
            setSelectedSampleTab,
            filter,
            epoch,
            sampleScrollPositionRef,
            setSampleScrollPosition,
            sampleTabScrollRef
          }
        ),
        tools: () => sampleMode === "single" || !samplesDescriptor ? void 0 : [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            SampleTools,
            {
              epoch,
              epochs: epochs || 1,
              setEpoch,
              scoreFilter: filter,
              setScoreFilter: setFilter,
              sort,
              setSort,
              score: score2,
              setScore,
              scores: scores2,
              sampleDescriptor: samplesDescriptor
            },
            "sample-tools"
          ),
          evalStatus === "started" && /* @__PURE__ */ jsxRuntimeExports.jsx(
            ToolButton,
            {
              label: "Refresh",
              icon: ApplicationIcons.refresh,
              onClick: refreshLog
            },
            "refresh"
          )
        ].filter(Boolean)
      } : null;
      const configTab = {
        id: kInfoWorkspaceTabId,
        label: "Info",
        scrollable: true,
        content: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
          InfoTab,
          {
            evalSpec,
            evalPlan,
            evalError,
            evalResults,
            evalStats,
            samples
          }
        )
      };
      const jsonTab2 = {
        id: kJsonWorkspaceTabId,
        label: "JSON",
        scrollable: true,
        content: () => {
          const evalHeader = {
            version: evalVersion,
            status: evalStatus,
            eval: evalSpec,
            plan: evalPlan,
            error: evalError,
            results: evalResults,
            stats: evalStats
          };
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            JsonTab,
            {
              logFile: logFileName,
              json: JSON.stringify(evalHeader, null, 2),
              capabilities: capabilities2,
              selected: selectedTab === kJsonWorkspaceTabId
            }
          );
        },
        tools: () => [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ToolButton,
            {
              label: "Copy JSON",
              icon: ApplicationIcons.copy,
              className: clsx("task-btn-json-copy", "clipboard-button"),
              "data-clipboard-target": "#task-json-contents",
              onClick: copyFeedback
            },
            "copy-json"
          )
        ]
      };
      return reactExports.useMemo(
        () => ({
          ...samplesTab ? { samples: samplesTab } : {},
          config: configTab,
          json: jsonTab2
        }),
        [samplesTab, configTab, jsonTab2]
      );
    };
    var clipboard = { exports: {} };
    /*!
     * clipboard.js v2.0.11
     * https://clipboardjs.com/
     *
     * Licensed MIT © Zeno Rocha
     */
    (function(module2, exports2) {
      (function webpackUniversalModuleDefinition(root2, factory) {
        module2.exports = factory();
      })(commonjsGlobal, function() {
        return (
          /******/
          function() {
            var __webpack_modules__ = {
              /***/
              686: (
                /***/
                function(__unused_webpack_module, __webpack_exports__, __webpack_require__2) {
                  __webpack_require__2.d(__webpack_exports__, {
                    "default": function() {
                      return (
                        /* binding */
                        clipboard2
                      );
                    }
                  });
                  var tiny_emitter = __webpack_require__2(279);
                  var tiny_emitter_default = /* @__PURE__ */ __webpack_require__2.n(tiny_emitter);
                  var listen = __webpack_require__2(370);
                  var listen_default = /* @__PURE__ */ __webpack_require__2.n(listen);
                  var src_select = __webpack_require__2(817);
                  var select_default = /* @__PURE__ */ __webpack_require__2.n(src_select);
                  function command2(type) {
                    try {
                      return document.execCommand(type);
                    } catch (err2) {
                      return false;
                    }
                  }
                  var ClipboardActionCut = function ClipboardActionCut2(target2) {
                    var selectedText = select_default()(target2);
                    command2("cut");
                    return selectedText;
                  };
                  var actions_cut = ClipboardActionCut;
                  function createFakeElement(value2) {
                    var isRTL = document.documentElement.getAttribute("dir") === "rtl";
                    var fakeElement = document.createElement("textarea");
                    fakeElement.style.fontSize = "12pt";
                    fakeElement.style.border = "0";
                    fakeElement.style.padding = "0";
                    fakeElement.style.margin = "0";
                    fakeElement.style.position = "absolute";
                    fakeElement.style[isRTL ? "right" : "left"] = "-9999px";
                    var yPosition = window.pageYOffset || document.documentElement.scrollTop;
                    fakeElement.style.top = "".concat(yPosition, "px");
                    fakeElement.setAttribute("readonly", "");
                    fakeElement.value = value2;
                    return fakeElement;
                  }
                  var fakeCopyAction = function fakeCopyAction2(value2, options2) {
                    var fakeElement = createFakeElement(value2);
                    options2.container.appendChild(fakeElement);
                    var selectedText = select_default()(fakeElement);
                    command2("copy");
                    fakeElement.remove();
                    return selectedText;
                  };
                  var ClipboardActionCopy = function ClipboardActionCopy2(target2) {
                    var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
                      container: document.body
                    };
                    var selectedText = "";
                    if (typeof target2 === "string") {
                      selectedText = fakeCopyAction(target2, options2);
                    } else if (target2 instanceof HTMLInputElement && !["text", "search", "url", "tel", "password"].includes(target2 === null || target2 === void 0 ? void 0 : target2.type)) {
                      selectedText = fakeCopyAction(target2.value, options2);
                    } else {
                      selectedText = select_default()(target2);
                      command2("copy");
                    }
                    return selectedText;
                  };
                  var actions_copy = ClipboardActionCopy;
                  function _typeof(obj) {
                    "@babel/helpers - typeof";
                    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                      _typeof = function _typeof2(obj2) {
                        return typeof obj2;
                      };
                    } else {
                      _typeof = function _typeof2(obj2) {
                        return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                      };
                    }
                    return _typeof(obj);
                  }
                  var ClipboardActionDefault = function ClipboardActionDefault2() {
                    var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
                    var _options$action = options2.action, action = _options$action === void 0 ? "copy" : _options$action, container2 = options2.container, target2 = options2.target, text2 = options2.text;
                    if (action !== "copy" && action !== "cut") {
                      throw new Error('Invalid "action" value, use either "copy" or "cut"');
                    }
                    if (target2 !== void 0) {
                      if (target2 && _typeof(target2) === "object" && target2.nodeType === 1) {
                        if (action === "copy" && target2.hasAttribute("disabled")) {
                          throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');
                        }
                        if (action === "cut" && (target2.hasAttribute("readonly") || target2.hasAttribute("disabled"))) {
                          throw new Error(`Invalid "target" attribute. You can't cut text from elements with "readonly" or "disabled" attributes`);
                        }
                      } else {
                        throw new Error('Invalid "target" value, use a valid Element');
                      }
                    }
                    if (text2) {
                      return actions_copy(text2, {
                        container: container2
                      });
                    }
                    if (target2) {
                      return action === "cut" ? actions_cut(target2) : actions_copy(target2, {
                        container: container2
                      });
                    }
                  };
                  var actions_default = ClipboardActionDefault;
                  function clipboard_typeof(obj) {
                    "@babel/helpers - typeof";
                    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                      clipboard_typeof = function _typeof2(obj2) {
                        return typeof obj2;
                      };
                    } else {
                      clipboard_typeof = function _typeof2(obj2) {
                        return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                      };
                    }
                    return clipboard_typeof(obj);
                  }
                  function _classCallCheck(instance, Constructor) {
                    if (!(instance instanceof Constructor)) {
                      throw new TypeError("Cannot call a class as a function");
                    }
                  }
                  function _defineProperties(target2, props) {
                    for (var i2 = 0; i2 < props.length; i2++) {
                      var descriptor = props[i2];
                      descriptor.enumerable = descriptor.enumerable || false;
                      descriptor.configurable = true;
                      if ("value" in descriptor) descriptor.writable = true;
                      Object.defineProperty(target2, descriptor.key, descriptor);
                    }
                  }
                  function _createClass(Constructor, protoProps, staticProps) {
                    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
                    if (staticProps) _defineProperties(Constructor, staticProps);
                    return Constructor;
                  }
                  function _inherits(subClass, superClass) {
                    if (typeof superClass !== "function" && superClass !== null) {
                      throw new TypeError("Super expression must either be null or a function");
                    }
                    subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
                    if (superClass) _setPrototypeOf(subClass, superClass);
                  }
                  function _setPrototypeOf(o, p) {
                    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) {
                      o2.__proto__ = p2;
                      return o2;
                    };
                    return _setPrototypeOf(o, p);
                  }
                  function _createSuper(Derived) {
                    var hasNativeReflectConstruct = _isNativeReflectConstruct();
                    return function _createSuperInternal() {
                      var Super = _getPrototypeOf(Derived), result2;
                      if (hasNativeReflectConstruct) {
                        var NewTarget = _getPrototypeOf(this).constructor;
                        result2 = Reflect.construct(Super, arguments, NewTarget);
                      } else {
                        result2 = Super.apply(this, arguments);
                      }
                      return _possibleConstructorReturn(this, result2);
                    };
                  }
                  function _possibleConstructorReturn(self2, call) {
                    if (call && (clipboard_typeof(call) === "object" || typeof call === "function")) {
                      return call;
                    }
                    return _assertThisInitialized(self2);
                  }
                  function _assertThisInitialized(self2) {
                    if (self2 === void 0) {
                      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
                    }
                    return self2;
                  }
                  function _isNativeReflectConstruct() {
                    if (typeof Reflect === "undefined" || !Reflect.construct) return false;
                    if (Reflect.construct.sham) return false;
                    if (typeof Proxy === "function") return true;
                    try {
                      Date.prototype.toString.call(Reflect.construct(Date, [], function() {
                      }));
                      return true;
                    } catch (e) {
                      return false;
                    }
                  }
                  function _getPrototypeOf(o) {
                    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o2) {
                      return o2.__proto__ || Object.getPrototypeOf(o2);
                    };
                    return _getPrototypeOf(o);
                  }
                  function getAttributeValue(suffix2, element) {
                    var attribute2 = "data-clipboard-".concat(suffix2);
                    if (!element.hasAttribute(attribute2)) {
                      return;
                    }
                    return element.getAttribute(attribute2);
                  }
                  var Clipboard = /* @__PURE__ */ function(_Emitter) {
                    _inherits(Clipboard2, _Emitter);
                    var _super = _createSuper(Clipboard2);
                    function Clipboard2(trigger, options2) {
                      var _this;
                      _classCallCheck(this, Clipboard2);
                      _this = _super.call(this);
                      _this.resolveOptions(options2);
                      _this.listenClick(trigger);
                      return _this;
                    }
                    _createClass(Clipboard2, [{
                      key: "resolveOptions",
                      value: function resolveOptions() {
                        var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
                        this.action = typeof options2.action === "function" ? options2.action : this.defaultAction;
                        this.target = typeof options2.target === "function" ? options2.target : this.defaultTarget;
                        this.text = typeof options2.text === "function" ? options2.text : this.defaultText;
                        this.container = clipboard_typeof(options2.container) === "object" ? options2.container : document.body;
                      }
                      /**
                       * Adds a click event listener to the passed trigger.
                       * @param {String|HTMLElement|HTMLCollection|NodeList} trigger
                       */
                    }, {
                      key: "listenClick",
                      value: function listenClick(trigger) {
                        var _this2 = this;
                        this.listener = listen_default()(trigger, "click", function(e) {
                          return _this2.onClick(e);
                        });
                      }
                      /**
                       * Defines a new `ClipboardAction` on each click event.
                       * @param {Event} e
                       */
                    }, {
                      key: "onClick",
                      value: function onClick(e) {
                        var trigger = e.delegateTarget || e.currentTarget;
                        var action = this.action(trigger) || "copy";
                        var text2 = actions_default({
                          action,
                          container: this.container,
                          target: this.target(trigger),
                          text: this.text(trigger)
                        });
                        this.emit(text2 ? "success" : "error", {
                          action,
                          text: text2,
                          trigger,
                          clearSelection: function clearSelection() {
                            if (trigger) {
                              trigger.focus();
                            }
                            window.getSelection().removeAllRanges();
                          }
                        });
                      }
                      /**
                       * Default `action` lookup function.
                       * @param {Element} trigger
                       */
                    }, {
                      key: "defaultAction",
                      value: function defaultAction(trigger) {
                        return getAttributeValue("action", trigger);
                      }
                      /**
                       * Default `target` lookup function.
                       * @param {Element} trigger
                       */
                    }, {
                      key: "defaultTarget",
                      value: function defaultTarget(trigger) {
                        var selector = getAttributeValue("target", trigger);
                        if (selector) {
                          return document.querySelector(selector);
                        }
                      }
                      /**
                       * Allow fire programmatically a copy action
                       * @param {String|HTMLElement} target
                       * @param {Object} options
                       * @returns Text copied.
                       */
                    }, {
                      key: "defaultText",
                      /**
                       * Default `text` lookup function.
                       * @param {Element} trigger
                       */
                      value: function defaultText(trigger) {
                        return getAttributeValue("text", trigger);
                      }
                      /**
                       * Destroy lifecycle.
                       */
                    }, {
                      key: "destroy",
                      value: function destroy() {
                        this.listener.destroy();
                      }
                    }], [{
                      key: "copy",
                      value: function copy(target2) {
                        var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
                          container: document.body
                        };
                        return actions_copy(target2, options2);
                      }
                      /**
                       * Allow fire programmatically a cut action
                       * @param {String|HTMLElement} target
                       * @returns Text cutted.
                       */
                    }, {
                      key: "cut",
                      value: function cut(target2) {
                        return actions_cut(target2);
                      }
                      /**
                       * Returns the support of the given action, or all actions if no action is
                       * given.
                       * @param {String} [action]
                       */
                    }, {
                      key: "isSupported",
                      value: function isSupported() {
                        var action = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ["copy", "cut"];
                        var actions = typeof action === "string" ? [action] : action;
                        var support = !!document.queryCommandSupported;
                        actions.forEach(function(action2) {
                          support = support && !!document.queryCommandSupported(action2);
                        });
                        return support;
                      }
                    }]);
                    return Clipboard2;
                  }(tiny_emitter_default());
                  var clipboard2 = Clipboard;
                }
              ),
              /***/
              828: (
                /***/
                function(module3) {
                  var DOCUMENT_NODE_TYPE = 9;
                  if (typeof Element !== "undefined" && !Element.prototype.matches) {
                    var proto = Element.prototype;
                    proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector;
                  }
                  function closest(element, selector) {
                    while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
                      if (typeof element.matches === "function" && element.matches(selector)) {
                        return element;
                      }
                      element = element.parentNode;
                    }
                  }
                  module3.exports = closest;
                }
              ),
              /***/
              438: (
                /***/
                function(module3, __unused_webpack_exports, __webpack_require__2) {
                  var closest = __webpack_require__2(828);
                  function _delegate(element, selector, type, callback, useCapture) {
                    var listenerFn = listener.apply(this, arguments);
                    element.addEventListener(type, listenerFn, useCapture);
                    return {
                      destroy: function() {
                        element.removeEventListener(type, listenerFn, useCapture);
                      }
                    };
                  }
                  function delegate(elements, selector, type, callback, useCapture) {
                    if (typeof elements.addEventListener === "function") {
                      return _delegate.apply(null, arguments);
                    }
                    if (typeof type === "function") {
                      return _delegate.bind(null, document).apply(null, arguments);
                    }
                    if (typeof elements === "string") {
                      elements = document.querySelectorAll(elements);
                    }
                    return Array.prototype.map.call(elements, function(element) {
                      return _delegate(element, selector, type, callback, useCapture);
                    });
                  }
                  function listener(element, selector, type, callback) {
                    return function(e) {
                      e.delegateTarget = closest(e.target, selector);
                      if (e.delegateTarget) {
                        callback.call(element, e);
                      }
                    };
                  }
                  module3.exports = delegate;
                }
              ),
              /***/
              879: (
                /***/
                function(__unused_webpack_module, exports3) {
                  exports3.node = function(value2) {
                    return value2 !== void 0 && value2 instanceof HTMLElement && value2.nodeType === 1;
                  };
                  exports3.nodeList = function(value2) {
                    var type = Object.prototype.toString.call(value2);
                    return value2 !== void 0 && (type === "[object NodeList]" || type === "[object HTMLCollection]") && "length" in value2 && (value2.length === 0 || exports3.node(value2[0]));
                  };
                  exports3.string = function(value2) {
                    return typeof value2 === "string" || value2 instanceof String;
                  };
                  exports3.fn = function(value2) {
                    var type = Object.prototype.toString.call(value2);
                    return type === "[object Function]";
                  };
                }
              ),
              /***/
              370: (
                /***/
                function(module3, __unused_webpack_exports, __webpack_require__2) {
                  var is2 = __webpack_require__2(879);
                  var delegate = __webpack_require__2(438);
                  function listen(target2, type, callback) {
                    if (!target2 && !type && !callback) {
                      throw new Error("Missing required arguments");
                    }
                    if (!is2.string(type)) {
                      throw new TypeError("Second argument must be a String");
                    }
                    if (!is2.fn(callback)) {
                      throw new TypeError("Third argument must be a Function");
                    }
                    if (is2.node(target2)) {
                      return listenNode(target2, type, callback);
                    } else if (is2.nodeList(target2)) {
                      return listenNodeList(target2, type, callback);
                    } else if (is2.string(target2)) {
                      return listenSelector(target2, type, callback);
                    } else {
                      throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList");
                    }
                  }
                  function listenNode(node2, type, callback) {
                    node2.addEventListener(type, callback);
                    return {
                      destroy: function() {
                        node2.removeEventListener(type, callback);
                      }
                    };
                  }
                  function listenNodeList(nodeList, type, callback) {
                    Array.prototype.forEach.call(nodeList, function(node2) {
                      node2.addEventListener(type, callback);
                    });
                    return {
                      destroy: function() {
                        Array.prototype.forEach.call(nodeList, function(node2) {
                          node2.removeEventListener(type, callback);
                        });
                      }
                    };
                  }
                  function listenSelector(selector, type, callback) {
                    return delegate(document.body, selector, type, callback);
                  }
                  module3.exports = listen;
                }
              ),
              /***/
              817: (
                /***/
                function(module3) {
                  function select(element) {
                    var selectedText;
                    if (element.nodeName === "SELECT") {
                      element.focus();
                      selectedText = element.value;
                    } else if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") {
                      var isReadOnly = element.hasAttribute("readonly");
                      if (!isReadOnly) {
                        element.setAttribute("readonly", "");
                      }
                      element.select();
                      element.setSelectionRange(0, element.value.length);
                      if (!isReadOnly) {
                        element.removeAttribute("readonly");
                      }
                      selectedText = element.value;
                    } else {
                      if (element.hasAttribute("contenteditable")) {
                        element.focus();
                      }
                      var selection = window.getSelection();
                      var range = document.createRange();
                      range.selectNodeContents(element);
                      selection.removeAllRanges();
                      selection.addRange(range);
                      selectedText = selection.toString();
                    }
                    return selectedText;
                  }
                  module3.exports = select;
                }
              ),
              /***/
              279: (
                /***/
                function(module3) {
                  function E() {
                  }
                  E.prototype = {
                    on: function(name2, callback, ctx) {
                      var e = this.e || (this.e = {});
                      (e[name2] || (e[name2] = [])).push({
                        fn: callback,
                        ctx
                      });
                      return this;
                    },
                    once: function(name2, callback, ctx) {
                      var self2 = this;
                      function listener() {
                        self2.off(name2, listener);
                        callback.apply(ctx, arguments);
                      }
                      listener._ = callback;
                      return this.on(name2, listener, ctx);
                    },
                    emit: function(name2) {
                      var data = [].slice.call(arguments, 1);
                      var evtArr = ((this.e || (this.e = {}))[name2] || []).slice();
                      var i2 = 0;
                      var len = evtArr.length;
                      for (i2; i2 < len; i2++) {
                        evtArr[i2].fn.apply(evtArr[i2].ctx, data);
                      }
                      return this;
                    },
                    off: function(name2, callback) {
                      var e = this.e || (this.e = {});
                      var evts = e[name2];
                      var liveEvents = [];
                      if (evts && callback) {
                        for (var i2 = 0, len = evts.length; i2 < len; i2++) {
                          if (evts[i2].fn !== callback && evts[i2].fn._ !== callback)
                            liveEvents.push(evts[i2]);
                        }
                      }
                      liveEvents.length ? e[name2] = liveEvents : delete e[name2];
                      return this;
                    }
                  };
                  module3.exports = E;
                  module3.exports.TinyEmitter = E;
                }
              )
              /******/
            };
            var __webpack_module_cache__ = {};
            function __webpack_require__(moduleId) {
              if (__webpack_module_cache__[moduleId]) {
                return __webpack_module_cache__[moduleId].exports;
              }
              var module3 = __webpack_module_cache__[moduleId] = {
                /******/
                // no module.id needed
                /******/
                // no module.loaded needed
                /******/
                exports: {}
                /******/
              };
              __webpack_modules__[moduleId](module3, module3.exports, __webpack_require__);
              return module3.exports;
            }
            !function() {
              __webpack_require__.n = function(module3) {
                var getter = module3 && module3.__esModule ? (
                  /******/
                  function() {
                    return module3["default"];
                  }
                ) : (
                  /******/
                  function() {
                    return module3;
                  }
                );
                __webpack_require__.d(getter, { a: getter });
                return getter;
              };
            }();
            !function() {
              __webpack_require__.d = function(exports3, definition) {
                for (var key2 in definition) {
                  if (__webpack_require__.o(definition, key2) && !__webpack_require__.o(exports3, key2)) {
                    Object.defineProperty(exports3, key2, { enumerable: true, get: definition[key2] });
                  }
                }
              };
            }();
            !function() {
              __webpack_require__.o = function(obj, prop) {
                return Object.prototype.hasOwnProperty.call(obj, prop);
              };
            }();
            return __webpack_require__(686);
          }().default
        );
      });
    })(clipboard);
    var clipboardExports = clipboard.exports;
    const ClipboardJS = /* @__PURE__ */ getDefaultExportFromCjs(clipboardExports);
    const App = ({
      api: api2,
      applicationState,
      saveApplicationState,
      pollForLogs = true,
      capabilities: capabilities2
    }) => {
      var _a2, _b2, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m;
      const [logs, setLogs] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.logs) || { log_dir: "", files: [] }
      );
      const [selectedLogIndex, setSelectedLogIndex] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.selectedLogIndex) !== void 0 ? applicationState.selectedLogIndex : -1
      );
      const [logHeaders, setLogHeaders] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.logHeaders) || {}
      );
      const [headersLoading, setHeadersLoading] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.headersLoading) || false
      );
      const [selectedLog, setSelectedLog] = reactExports.useState(
        applicationState == null ? void 0 : applicationState.selectedLog
      );
      const [selectedWorkspaceTab, setSelectedWorkspaceTab] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.selectedWorkspaceTab) || kEvalWorkspaceTabId
      );
      const [selectedSampleIndex, setSelectedSampleIndex] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.selectedSampleIndex) !== void 0 ? applicationState.selectedSampleIndex : -1
      );
      const [selectedSample, setSelectedSample] = reactExports.useState(
        applicationState == null ? void 0 : applicationState.selectedSample
      );
      const [sampleStatus, setSampleStatus] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.sampleStatus) || "loading"
      );
      const [sampleError, setSampleError] = reactExports.useState(
        applicationState == null ? void 0 : applicationState.sampleError
      );
      const [selectedSampleTab, setSelectedSampleTab] = reactExports.useState(applicationState == null ? void 0 : applicationState.selectedSampleTab);
      const sampleScrollPosition = reactExports.useRef(
        (applicationState == null ? void 0 : applicationState.sampleScrollPosition) || 0
      );
      const loadingSampleIndexRef = reactExports.useRef(null);
      const workspaceTabScrollPosition = reactExports.useRef(
        (applicationState == null ? void 0 : applicationState.workspaceTabScrollPosition) || {}
      );
      const [showingSampleDialog, setShowingSampleDialog] = reactExports.useState(
        !!(applicationState == null ? void 0 : applicationState.showingSampleDialog)
      );
      const [status, setStatus] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.status) || { loading: false }
      );
      const [offcanvas, setOffcanvas] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.offcanvas) || false
      );
      const [showFind, setShowFind] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.showFind) || false
      );
      const [filter, setFilter] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.filter) || {}
      );
      const [epoch, setEpoch] = reactExports.useState((applicationState == null ? void 0 : applicationState.epoch) || "all");
      const [sort, setSort] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.sort) || kDefaultSort
      );
      const [scores2, setScores] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.scores) || []
      );
      const [score2, setScore] = reactExports.useState(
        applicationState == null ? void 0 : applicationState.score
      );
      const [filteredSamples, setFilteredSamples] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.filteredSamples) || []
      );
      const [groupBy, setGroupBy] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.groupBy) || "none"
      );
      const [groupByOrder, setGroupByOrder] = reactExports.useState(
        (applicationState == null ? void 0 : applicationState.groupByOrder) || "asc"
      );
      const saveState = reactExports.useCallback(() => {
        const state = {
          logs,
          selectedLogIndex,
          logHeaders,
          headersLoading,
          selectedLog,
          selectedSampleIndex,
          selectedWorkspaceTab,
          selectedSample,
          sampleStatus,
          sampleError,
          selectedSampleTab,
          showingSampleDialog,
          status,
          offcanvas,
          showFind,
          filter,
          epoch,
          sort,
          scores: scores2,
          score: score2,
          filteredSamples,
          groupBy,
          groupByOrder,
          sampleScrollPosition: sampleScrollPosition.current,
          workspaceTabScrollPosition: workspaceTabScrollPosition.current
        };
        if (saveApplicationState) {
          saveApplicationState(state);
        }
      }, [
        logs,
        selectedLogIndex,
        logHeaders,
        headersLoading,
        selectedLog,
        selectedSampleIndex,
        selectedWorkspaceTab,
        selectedSample,
        sampleStatus,
        sampleError,
        selectedSampleTab,
        showingSampleDialog,
        status,
        offcanvas,
        showFind,
        filter,
        epoch,
        sort,
        scores2,
        score2,
        filteredSamples,
        groupBy,
        groupByOrder
      ]);
      const saveStateRef = reactExports.useRef(saveState);
      reactExports.useEffect(() => {
        saveStateRef.current = saveState;
      }, [saveState]);
      const setSampleScrollPosition = reactExports.useCallback(
        debounce$1((position) => {
          sampleScrollPosition.current = position;
          saveStateRef.current();
        }, 1e3),
        []
      );
      const setWorkspaceTabScrollPosition = reactExports.useCallback(
        debounce$1((tab2, position) => {
          if (workspaceTabScrollPosition.current[tab2] !== position) {
            workspaceTabScrollPosition.current = {
              ...workspaceTabScrollPosition.current,
              [tab2]: position
            };
            saveStateRef.current();
          }
        }, 1e3),
        []
      );
      reactExports.useEffect(() => {
        saveStateRef.current();
      }, [
        logs,
        selectedLogIndex,
        logHeaders,
        headersLoading,
        selectedLog,
        selectedSampleIndex,
        selectedWorkspaceTab,
        selectedSample,
        sampleStatus,
        sampleError,
        selectedSampleTab,
        showingSampleDialog,
        status,
        offcanvas,
        showFind,
        filter,
        epoch,
        sort,
        scores2,
        score2,
        filteredSamples,
        groupBy,
        groupByOrder
      ]);
      const handleSampleShowingDialog = reactExports.useCallback(
        (show) => {
          setShowingSampleDialog(show);
          if (!show) {
            setSelectedSample(void 0);
            setSelectedSampleTab(void 0);
          }
        },
        [
          setShowingSampleDialog,
          setSelectedSample,
          setSelectedSampleTab,
          selectedSample
        ]
      );
      reactExports.useEffect(() => {
        var _a3, _b3;
        const samples = ((_a3 = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _a3.sampleSummaries) || [];
        const { result: prefiltered } = evalDescriptor && (filter == null ? void 0 : filter.value) ? filterSamples(evalDescriptor, samples, filter.value) : { result: samples };
        const filtered = prefiltered.filter((sample2) => {
          if (epoch && epoch !== "all") {
            if (epoch !== String(sample2.epoch)) {
              return false;
            }
          }
          return true;
        });
        if (samplesDescriptor) {
          const { sorted, order } = sortSamples(sort, filtered, samplesDescriptor);
          setFilteredSamples(sorted);
          setGroupByOrder(order);
        }
        let grouping = "none";
        if (((_b3 = samplesDescriptor == null ? void 0 : samplesDescriptor.evalDescriptor) == null ? void 0 : _b3.epochs) && samplesDescriptor.evalDescriptor.epochs > 1) {
          if (byEpoch(sort) || epoch !== "all") {
            grouping = "epoch";
          } else if (bySample(sort)) {
            grouping = "sample";
          }
        }
        setGroupBy(grouping);
      }, [selectedLog, filter, sort, epoch]);
      const evalDescriptor = reactExports.useMemo(() => {
        var _a3, _b3, _c2, _d2;
        return createEvalDescriptor(
          scores2,
          ((_c2 = (_b3 = (_a3 = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _a3.eval) == null ? void 0 : _b3.config) == null ? void 0 : _c2.epochs) || 1,
          (_d2 = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _d2.sampleSummaries
        );
      }, [selectedLog, scores2]);
      const samplesDescriptor = reactExports.useMemo(() => {
        return evalDescriptor && score2 ? createSamplesDescriptor(evalDescriptor, score2) : void 0;
      }, [evalDescriptor, score2]);
      reactExports.useEffect(() => {
        if (selectedSampleTab === void 0 && selectedSample) {
          setSelectedSampleTab(
            selectedSample.events && selectedSample.events.length > 0 ? kSampleTranscriptTabId : kSampleMessagesTabId
          );
        }
      }, [selectedSample, selectedSampleTab]);
      const mainAppRef = reactExports.useRef(null);
      reactExports.useEffect(() => {
        if (!selectedLog || selectedSampleIndex === -1) {
          setSelectedSample(void 0);
          return;
        }
        if (loadingSampleIndexRef.current === selectedSampleIndex) {
          return;
        }
        if (!showingSampleDialog && selectedLog.contents.sampleSummaries.length > 1) {
          return;
        }
        if (selectedSampleIndex < filteredSamples.length) {
          const summary2 = filteredSamples[selectedSampleIndex];
          if (selectedSample && selectedSample.id === summary2.id && selectedSample.epoch === summary2.epoch) {
            return;
          }
          loadingSampleIndexRef.current = selectedSampleIndex;
          setSampleStatus("loading");
          setSampleError(void 0);
          api2.get_log_sample(selectedLog.name, summary2.id, summary2.epoch).then((sample2) => {
            if (sample2) {
              const anySample = sample2;
              if (anySample.transcript) {
                sample2.events = anySample.transcript.events;
                sample2.attachments = anySample.transcript.content;
              }
              sample2.attachments = sample2.attachments || {};
              sample2.input = resolveAttachments(sample2.input, sample2.attachments);
              sample2.messages = resolveAttachments(
                sample2.messages,
                sample2.attachments
              );
              sample2.events = resolveAttachments(
                sample2.events,
                sample2.attachments
              );
              sample2.attachments = {};
              sampleScrollPosition.current = 0;
              setSelectedSample(sample2);
              setSampleStatus("ok");
              loadingSampleIndexRef.current = null;
            } else {
              throw Error("Unable to load sample - an unknown error occurred.");
            }
          }).catch((e) => {
            setSampleStatus("error");
            setSampleError(e);
            sampleScrollPosition.current = 0;
            setSelectedSample(void 0);
            loadingSampleIndexRef.current = null;
          });
        }
      }, [
        selectedSample,
        selectedSampleIndex,
        showingSampleDialog,
        selectedLog,
        filteredSamples,
        setSelectedSample,
        setSampleStatus,
        setSampleError
      ]);
      reactExports.useEffect(() => {
        const loadHeaders = async () => {
          setHeadersLoading(true);
          const chunkSize = 8;
          const fileLists = [];
          for (let i2 = 0; i2 < logs.files.length; i2 += chunkSize) {
            let chunk = logs.files.slice(i2, i2 + chunkSize).map((log2) => log2.name);
            fileLists.push(chunk);
          }
          try {
            for (const fileList of fileLists) {
              const headers = await api2.get_log_headers(fileList);
              setLogHeaders((prev) => {
                const updatedHeaders = {};
                headers.forEach((header2, index2) => {
                  const logFile = fileList[index2];
                  updatedHeaders[logFile] = header2;
                });
                return { ...prev, ...updatedHeaders };
              });
              if (headers.length === chunkSize) {
                await sleep$1(5e3);
              }
            }
          } catch (e) {
            if (e instanceof Error && (e.message === "Load failed" || e.message === "Failed to fetch")) {
              setStatus({ loading: false });
            } else {
              console.log(e);
              setStatus({ loading: false, error: e });
            }
          }
          setHeadersLoading(false);
        };
        loadHeaders();
      }, [logs, setStatus, setLogHeaders, setHeadersLoading]);
      const resetWorkspace = reactExports.useCallback(
        (log2) => {
          const hasSamples = !!log2.sampleSummaries && log2.sampleSummaries.length > 0;
          const showSamples = hasSamples;
          setSelectedWorkspaceTab(
            log2.status !== "error" && hasSamples ? kEvalWorkspaceTabId : kInfoWorkspaceTabId
          );
          const scorer = defaultScorer(log2);
          const scorers = defaultScorers(log2);
          setScores(scorers);
          setScore(scorer);
          setEpoch("all");
          setFilter({});
          setSort(kDefaultSort);
          setSelectedSampleTab(void 0);
          setSelectedSample(void 0);
          if (showSamples) {
            setSelectedSampleIndex(0);
          } else {
            setSelectedSampleIndex(-1);
          }
          workspaceTabScrollPosition.current = {};
        },
        [setSelectedWorkspaceTab]
      );
      reactExports.useEffect(() => {
        const loadSpecificLog = async () => {
          const targetLog = logs.files[selectedLogIndex];
          if (targetLog && (!selectedLog || selectedLog.name !== targetLog.name)) {
            try {
              setStatus({ loading: true, error: void 0 });
              const logContents = await loadLog(targetLog.name);
              if (logContents) {
                const log2 = logContents;
                setSelectedLog({
                  contents: log2,
                  name: targetLog.name
                });
                resetWorkspace(log2);
                setStatus({ loading: false, error: void 0 });
              }
            } catch (e) {
              console.log(e);
              setStatus({ loading: false, error: e });
            }
          } else if (logs.log_dir && logs.files.length === 0) {
            setStatus({
              loading: false,
              error: new Error(
                `No log files to display in the directory ${logs.log_dir}. Are you sure this is the correct log directory?`
              )
            });
          }
        };
        loadSpecificLog();
      }, [selectedLogIndex, logs, selectedLog, setSelectedLog, setStatus]);
      const loadLogs = async () => {
        try {
          const result2 = await api2.get_log_paths();
          return result2;
        } catch (e) {
          console.log(e);
          setStatus({ loading: false, error: e });
          return { log_dir: "", files: [] };
        }
      };
      const loadLog = async (logFileName) => {
        try {
          const logContents = await api2.get_log_summary(logFileName);
          return logContents;
        } catch (e) {
          console.log(e);
          setStatus({ loading: false, error: e });
        }
      };
      const refreshLog = reactExports.useCallback(async () => {
        try {
          setStatus({ loading: true, error: void 0 });
          const targetLog = logs.files[selectedLogIndex];
          const logContents = await loadLog(targetLog.name);
          if (logContents) {
            const log2 = logContents;
            if (log2.status !== "started") {
              setLogHeaders((prev) => {
                const updatedState = { ...prev };
                const freshHeaders = {
                  eval: log2.eval,
                  plan: log2.plan,
                  results: log2.results !== null ? log2.results : void 0,
                  stats: log2.stats,
                  status: log2.status,
                  version: log2.version
                };
                updatedState[targetLog.name] = freshHeaders;
                return updatedState;
              });
            }
            setSelectedLog({
              contents: log2,
              name: targetLog.name
            });
            resetWorkspace(log2);
            setStatus({ loading: false, error: void 0 });
          }
        } catch (e) {
          console.log(e);
          setStatus({ loading: false, error: e });
        }
      }, [logs, selectedLogIndex, setStatus, setSelectedLog, setLogHeaders]);
      const showLogFile = reactExports.useCallback(
        async (logUrl) => {
          const index2 = logs.files.findIndex((val) => {
            return logUrl.endsWith(val.name);
          });
          if (index2 > -1) {
            setSelectedLogIndex(index2);
          } else {
            const result2 = await loadLogs();
            const idx = result2 == null ? void 0 : result2.files.findIndex((file) => {
              return logUrl.endsWith(file.name);
            });
            setLogs(result2 || { log_dir: "", files: [] });
            setSelectedLogIndex(idx && idx > -1 ? idx : 0);
          }
        },
        [logs, setSelectedLogIndex, setLogs]
      );
      const refreshLogList = reactExports.useCallback(async () => {
        const currentLog = logs.files[selectedLogIndex > -1 ? selectedLogIndex : 0];
        const refreshedLogs = await loadLogs();
        setLogs(refreshedLogs || { log_dir: "", files: [] });
        const newIndex = refreshedLogs == null ? void 0 : refreshedLogs.files.findIndex((file) => {
          return currentLog.name.endsWith(file.name);
        });
        if (newIndex !== void 0) {
          setSelectedLogIndex(newIndex);
        }
      }, [logs, selectedLogIndex, setSelectedLogIndex, setLogs]);
      const onMessage = reactExports.useCallback(
        async (e) => {
          switch (e.data.type) {
            case "updateState": {
              if (e.data.url) {
                const decodedUrl = decodeURIComponent(e.data.url);
                showLogFile(decodedUrl);
              }
              break;
            }
            case "backgroundUpdate": {
              const decodedUrl = decodeURIComponent(e.data.url);
              const log_dir = e.data.log_dir;
              const isFocused = document.hasFocus();
              if (!isFocused) {
                if (log_dir === logs.log_dir) {
                  showLogFile(decodedUrl);
                } else {
                  api2.open_log_file(e.data.url, e.data.log_dir);
                }
              } else {
                refreshLogList();
              }
              break;
            }
          }
        },
        [logs, showLogFile, refreshLogList]
      );
      reactExports.useEffect(() => {
        window.addEventListener("message", onMessage);
        return () => {
          window.removeEventListener("message", onMessage);
        };
      }, [onMessage]);
      reactExports.useEffect(() => {
        const loadLogsAndState = async () => {
          const urlParams = new URLSearchParams(window.location.search);
          const logPath = urlParams.get("task_file");
          const resolvedLogPath = logPath ? logPath.replace(" ", "+") : logPath;
          const load = resolvedLogPath ? async () => {
            return {
              log_dir: "",
              files: [{ name: resolvedLogPath }]
            };
          } : loadLogs;
          const embeddedState = document.getElementById("logview-state");
          if (embeddedState) {
            const state = JSON.parse(embeddedState.textContent || "");
            onMessage({ data: state });
          } else {
            const result2 = await load();
            setLogs(result2);
            const log_file = urlParams.get("log_file");
            if (log_file) {
              const index2 = result2.files.findIndex((val) => {
                return log_file.endsWith(val.name);
              });
              if (index2 > -1) {
                setSelectedLogIndex(index2);
              }
            } else if (selectedLogIndex === -1) {
              setSelectedLogIndex(0);
            }
          }
          new ClipboardJS(".clipboard-button,.copy-button");
          if (pollForLogs) {
            let retryDelay = 1e3;
            const maxRetryDelay = 6e4;
            const pollEvents = async () => {
              try {
                const events = await api2.client_events();
                if (events.includes("reload")) {
                  window.location.reload();
                }
                if (events.includes("refresh-evals")) {
                  const logs2 = await load();
                  setLogs(logs2);
                  setSelectedLogIndex(0);
                }
                retryDelay = 1e3;
              } catch (error2) {
                console.error("Error fetching client events:", error2);
                retryDelay = Math.min(retryDelay * 2, maxRetryDelay);
              } finally {
                setTimeout(pollEvents, retryDelay);
              }
            };
            pollEvents();
          }
        };
        loadLogsAndState();
      }, []);
      const fullScreen = logs.files.length === 1 && !logs.log_dir;
      const hideFind = reactExports.useCallback(() => {
        clearDocumentSelection();
        if (showFind) {
          setShowFind(false);
        }
      }, [showFind, setShowFind]);
      const showToggle = logs.files.length > 1 || !!logs.log_dir || false;
      const sampleMode = ((_a2 = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _a2.sampleSummaries) === void 0 || selectedLog.contents.sampleSummaries.length === 0 ? "none" : selectedLog.contents.sampleSummaries.length === 1 ? "single" : "many";
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(AppErrorBoundary, { children: [
        !fullScreen && (selectedLog == null ? void 0 : selectedLog.contents) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          Sidebar,
          {
            logs,
            logHeaders,
            loading: headersLoading,
            offcanvas,
            setOffcanvas,
            selectedIndex: selectedLogIndex,
            onSelectedIndexChanged: (index2) => {
              setSelectedLogIndex(index2);
              setOffcanvas(false);
            }
          }
        ) : void 0,
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            ref: mainAppRef,
            className: clsx(
              "app-main-grid",
              fullScreen ? "full-screen" : void 0,
              offcanvas ? "off-canvas" : void 0
            ),
            tabIndex: 0,
            onKeyDown: (e) => {
              if (!getVscodeApi()) {
                return;
              }
              if ((e.ctrlKey || e.metaKey) && e.key === "f") {
                setShowFind(true);
              } else if (e.key === "Escape") {
                hideFind();
              }
            },
            children: [
              showFind ? /* @__PURE__ */ jsxRuntimeExports.jsx(FindBand, { hideBand: hideFind }) : "",
              /* @__PURE__ */ jsxRuntimeExports.jsx(ProgressBar, { animating: status == null ? void 0 : status.loading }),
              (status == null ? void 0 : status.error) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                ErrorPanel,
                {
                  title: "An error occurred while loading this task.",
                  error: status.error
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                WorkSpace,
                {
                  task_id: (_c = (_b2 = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _b2.eval) == null ? void 0 : _c.task_id,
                  logFileName: selectedLog == null ? void 0 : selectedLog.name,
                  evalStatus: (_d = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _d.status,
                  evalError: filterNull((_e2 = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _e2.error),
                  evalVersion: (_f = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _f.version,
                  evalSpec: (_g = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _g.eval,
                  evalPlan: (_h = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _h.plan,
                  evalStats: (_i = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _i.stats,
                  evalResults: filterNull((_j = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _j.results),
                  showToggle,
                  samples: filteredSamples,
                  sampleMode,
                  groupBy,
                  groupByOrder,
                  sampleStatus,
                  sampleError,
                  samplesDescriptor,
                  refreshLog,
                  offcanvas,
                  setOffcanvas,
                  capabilities: capabilities2,
                  selectedSample,
                  selectedSampleIndex,
                  setSelectedSampleIndex,
                  showingSampleDialog,
                  setShowingSampleDialog: handleSampleShowingDialog,
                  selectedTab: selectedWorkspaceTab,
                  setSelectedTab: setSelectedWorkspaceTab,
                  selectedSampleTab,
                  setSelectedSampleTab,
                  sort,
                  setSort,
                  epochs: (_m = (_l = (_k = selectedLog == null ? void 0 : selectedLog.contents) == null ? void 0 : _k.eval) == null ? void 0 : _l.config) == null ? void 0 : _m.epochs,
                  epoch,
                  setEpoch,
                  filter,
                  setFilter,
                  score: score2,
                  setScore,
                  scores: scores2,
                  sampleScrollPositionRef: sampleScrollPosition,
                  setSampleScrollPosition,
                  workspaceTabScrollPositionRef: workspaceTabScrollPosition,
                  setWorkspaceTabScrollPosition
                }
              )
            ]
          }
        )
      ] });
    };
    const filterNull = (obj) => {
      if (obj === null) {
        return void 0;
      }
      return obj;
    };
    const defaultScorer = (log2) => {
      var _a2, _b2, _c;
      if (log2.sampleSummaries.length === 0) {
        return void 0;
      }
      const scores2 = log2.sampleSummaries[0].scores;
      const scorer = ((_a2 = log2.results) == null ? void 0 : _a2.scores[0]) ? {
        name: (_b2 = log2.results) == null ? void 0 : _b2.scores[0].name,
        scorer: (_c = log2.results) == null ? void 0 : _c.scores[0].scorer
      } : log2.sampleSummaries.length > 0 && scores2 !== null ? {
        name: Object.keys(scores2)[0],
        scorer: Object.keys(scores2)[0]
      } : void 0;
      return scorer;
    };
    const defaultScorers = (log2) => {
      var _a2, _b2;
      if ((_a2 = log2.results) == null ? void 0 : _a2.scores) {
        return (((_b2 = log2.results) == null ? void 0 : _b2.scores) || []).map((score2) => {
          return {
            name: score2.name,
            scorer: score2.scorer
          };
        }).reduce((accum, scorer) => {
          if (!accum.find((sc) => {
            return scorer.scorer === sc.scorer && scorer.name === sc.name;
          })) {
            accum.push(scorer);
          }
          return accum;
        }, []);
      } else if (log2.sampleSummaries && log2.sampleSummaries.length > 0) {
        const scores2 = log2.sampleSummaries[0].scores;
        if (scores2 !== null) {
          return Object.keys(scores2).map((key2) => {
            return {
              name: key2,
              scorer: key2
            };
          });
        } else {
          return [];
        }
      } else {
        return [];
      }
    };
    const vscode = getVscodeApi();
    let initialState = void 0;
    let capabilities = {
      downloadFiles: true,
      webWorkers: true
    };
    if (vscode) {
      initialState = filterState(vscode.getState());
      const extensionVersionEl = document.querySelector(
        'meta[name="inspect-extension:version"]'
      );
      const extensionVersion = extensionVersionEl ? extensionVersionEl.getAttribute("content") : void 0;
      if (!extensionVersion) {
        capabilities = { downloadFiles: false, webWorkers: false };
      }
    }
    const containerId = "app";
    const container = document.getElementById(containerId);
    if (!container) {
      console.error("Root container not found");
      throw new Error(
        `Expected a container element with Id '${containerId}' but no such container element was present.`
      );
    }
    const root = clientExports.createRoot(container);
    root.render(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        App,
        {
          api,
          applicationState: initialState,
          saveApplicationState: throttle$1((state) => {
            const vscode2 = getVscodeApi();
            if (vscode2) {
              vscode2.setState(filterState(state));
            }
          }, 1e3),
          capabilities,
          pollForLogs: false
        }
      )
    );
    function filterState(state) {
      if (!state) {
        return state;
      }
      const filters = [filterLargeSample, filterLargeSelectedLog];
      return filters.reduce(
        (filteredState, filter) => filter(filteredState),
        state
      );
    }
    function filterLargeSample(state) {
      if (!state || !state.selectedSample) {
        return state;
      }
      const estimatedTotalSize = estimateSize(state.selectedSample.messages);
      if (estimatedTotalSize > 4e5) {
        const { selectedSample, ...filteredState } = state;
        return filteredState;
      } else {
        return state;
      }
    }
    function filterLargeSelectedLog(state) {
      var _a2;
      if (!state || !((_a2 = state.selectedLog) == null ? void 0 : _a2.contents)) {
        return state;
      }
      const estimatedSize = estimateSize(
        state.selectedLog.contents.sampleSummaries
      );
      if (estimatedSize > 4e5) {
        const { selectedLog, ...filteredState } = state;
        return filteredState;
      } else {
        return state;
      }
    }
    function estimateSize(list2, frequency = 0.2) {
      if (!list2 || list2.length === 0) {
        return 0;
      }
      const sampleSize = Math.ceil(list2.length * frequency);
      const messageIndices = /* @__PURE__ */ new Set();
      while (messageIndices.size < sampleSize && messageIndices.size < list2.length) {
        const randomIndex = Math.floor(Math.random() * list2.length);
        messageIndices.add(randomIndex);
      }
      const totalSize = Array.from(messageIndices).reduce((size, index2) => {
        return size + JSON.stringify(list2[index2]).length;
      }, 0);
      const estimatedTotalSize = totalSize / sampleSize * list2.length;
      return estimatedTotalSize;
    }
  }
});
export default require_assets();
//# sourceMappingURL=index.js.map
