var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x2)(function(x2) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});

// node_modules/@ungap/custom-elements/index.js
(function() {
  "use strict";
  var attributesObserver = function(whenDefined2, MutationObserver2) {
    var attributeChanged = function attributeChanged2(records) {
      for (var i2 = 0, length = records.length; i2 < length; i2++) dispatch(records[i2]);
    };
    var dispatch = function dispatch2(_ref2) {
      var target = _ref2.target, attributeName = _ref2.attributeName, oldValue = _ref2.oldValue;
      target.attributeChangedCallback(attributeName, oldValue, target.getAttribute(attributeName));
    };
    return function(target, is3) {
      var attributeFilter = target.constructor.observedAttributes;
      if (attributeFilter) {
        whenDefined2(is3).then(function() {
          new MutationObserver2(attributeChanged).observe(target, {
            attributes: true,
            attributeOldValue: true,
            attributeFilter
          });
          for (var i2 = 0, length = attributeFilter.length; i2 < length; i2++) {
            if (target.hasAttribute(attributeFilter[i2])) dispatch({
              target,
              attributeName: attributeFilter[i2],
              oldValue: null
            });
          }
        });
      }
      return target;
    };
  };
  function _unsupportedIterableToArray(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  }
  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for (var i2 = 0, arr2 = new Array(len); i2 < len; i2++) arr2[i2] = arr[i2];
    return arr2;
  }
  function _createForOfIteratorHelper(o, allowArrayLike) {
    var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
    if (!it) {
      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
        if (it) o = it;
        var i2 = 0;
        var F = function() {
        };
        return {
          s: F,
          n: function() {
            if (i2 >= o.length) return {
              done: true
            };
            return {
              done: false,
              value: o[i2++]
            };
          },
          e: function(e) {
            throw e;
          },
          f: F
        };
      }
      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }
    var normalCompletion = true, didErr = false, err3;
    return {
      s: function() {
        it = it.call(o);
      },
      n: function() {
        var step = it.next();
        normalCompletion = step.done;
        return step;
      },
      e: function(e) {
        didErr = true;
        err3 = e;
      },
      f: function() {
        try {
          if (!normalCompletion && it.return != null) it.return();
        } finally {
          if (didErr) throw err3;
        }
      }
    };
  }
  var TRUE = true, FALSE = false, QSA$1 = "querySelectorAll";
  var notify2 = function notify3(callback) {
    var root68 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : document;
    var MO = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : MutationObserver;
    var query3 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ["*"];
    var loop2 = function loop3(nodes, selectors, added, removed, connected, pass) {
      var _iterator = _createForOfIteratorHelper(nodes), _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done; ) {
          var node = _step.value;
          if (pass || QSA$1 in node) {
            if (connected) {
              if (!added.has(node)) {
                added.add(node);
                removed["delete"](node);
                callback(node, connected);
              }
            } else if (!removed.has(node)) {
              removed.add(node);
              added["delete"](node);
              callback(node, connected);
            }
            if (!pass) loop3(node[QSA$1](selectors), selectors, added, removed, connected, TRUE);
          }
        }
      } catch (err3) {
        _iterator.e(err3);
      } finally {
        _iterator.f();
      }
    };
    var mo = new MO(function(records) {
      if (query3.length) {
        var selectors = query3.join(",");
        var added = /* @__PURE__ */ new Set(), removed = /* @__PURE__ */ new Set();
        var _iterator2 = _createForOfIteratorHelper(records), _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) {
            var _step2$value = _step2.value, addedNodes = _step2$value.addedNodes, removedNodes = _step2$value.removedNodes;
            loop2(removedNodes, selectors, added, removed, FALSE, FALSE);
            loop2(addedNodes, selectors, added, removed, TRUE, FALSE);
          }
        } catch (err3) {
          _iterator2.e(err3);
        } finally {
          _iterator2.f();
        }
      }
    });
    var observe = mo.observe;
    (mo.observe = function(node) {
      return observe.call(mo, node, {
        subtree: TRUE,
        childList: TRUE
      });
    })(root68);
    return mo;
  };
  var QSA = "querySelectorAll";
  var _self$1 = self, document$2 = _self$1.document, Element$1 = _self$1.Element, MutationObserver$2 = _self$1.MutationObserver, Set$2 = _self$1.Set, WeakMap$1 = _self$1.WeakMap;
  var elements = function elements2(element2) {
    return QSA in element2;
  };
  var filter2 = [].filter;
  var qsaObserver = function(options4) {
    var live = new WeakMap$1();
    var drop2 = function drop3(elements2) {
      for (var i2 = 0, length = elements2.length; i2 < length; i2++) live["delete"](elements2[i2]);
    };
    var flush = function flush2() {
      var records = observer.takeRecords();
      for (var i2 = 0, length = records.length; i2 < length; i2++) {
        parse2(filter2.call(records[i2].removedNodes, elements), false);
        parse2(filter2.call(records[i2].addedNodes, elements), true);
      }
    };
    var matches = function matches2(element2) {
      return element2.matches || element2.webkitMatchesSelector || element2.msMatchesSelector;
    };
    var notifier = function notifier2(element2, connected) {
      var selectors;
      if (connected) {
        for (var q, m2 = matches(element2), i2 = 0, length = query3.length; i2 < length; i2++) {
          if (m2.call(element2, q = query3[i2])) {
            if (!live.has(element2)) live.set(element2, new Set$2());
            selectors = live.get(element2);
            if (!selectors.has(q)) {
              selectors.add(q);
              options4.handle(element2, connected, q);
            }
          }
        }
      } else if (live.has(element2)) {
        selectors = live.get(element2);
        live["delete"](element2);
        selectors.forEach(function(q2) {
          options4.handle(element2, connected, q2);
        });
      }
    };
    var parse2 = function parse3(elements2) {
      var connected = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
      for (var i2 = 0, length = elements2.length; i2 < length; i2++) notifier(elements2[i2], connected);
    };
    var query3 = options4.query;
    var root68 = options4.root || document$2;
    var observer = notify2(notifier, root68, MutationObserver$2, query3);
    var attachShadow2 = Element$1.prototype.attachShadow;
    if (attachShadow2) Element$1.prototype.attachShadow = function(init4) {
      var shadowRoot = attachShadow2.call(this, init4);
      observer.observe(shadowRoot);
      return shadowRoot;
    };
    if (query3.length) parse2(root68[QSA](query3));
    return {
      drop: drop2,
      flush,
      observer,
      parse: parse2
    };
  };
  var _self = self, document$1 = _self.document, Map2 = _self.Map, MutationObserver$1 = _self.MutationObserver, Object$1 = _self.Object, Set$1 = _self.Set, WeakMap2 = _self.WeakMap, Element2 = _self.Element, HTMLElement2 = _self.HTMLElement, Node4 = _self.Node, Error2 = _self.Error, TypeError$1 = _self.TypeError, Reflect2 = _self.Reflect;
  var defineProperty = Object$1.defineProperty, keys = Object$1.keys, getOwnPropertyNames = Object$1.getOwnPropertyNames, setPrototypeOf = Object$1.setPrototypeOf;
  var legacy = !self.customElements;
  var expando = function expando2(element2) {
    var key2 = keys(element2);
    var value = [];
    var ignore = new Set$1();
    var length = key2.length;
    for (var i2 = 0; i2 < length; i2++) {
      value[i2] = element2[key2[i2]];
      try {
        delete element2[key2[i2]];
      } catch (SafariTP) {
        ignore.add(i2);
      }
    }
    return function() {
      for (var _i = 0; _i < length; _i++) ignore.has(_i) || (element2[key2[_i]] = value[_i]);
    };
  };
  if (legacy) {
    var HTMLBuiltIn = function HTMLBuiltIn2() {
      var constructor = this.constructor;
      if (!classes.has(constructor)) throw new TypeError$1("Illegal constructor");
      var is3 = classes.get(constructor);
      if (override) return augment(override, is3);
      var element2 = createElement.call(document$1, is3);
      return augment(setPrototypeOf(element2, constructor.prototype), is3);
    };
    var createElement = document$1.createElement;
    var classes = new Map2();
    var defined = new Map2();
    var prototypes = new Map2();
    var registry = new Map2();
    var query2 = [];
    var handle2 = function handle3(element2, connected, selector) {
      var proto = prototypes.get(selector);
      if (connected && !proto.isPrototypeOf(element2)) {
        var redefine = expando(element2);
        override = setPrototypeOf(element2, proto);
        try {
          new proto.constructor();
        } finally {
          override = null;
          redefine();
        }
      }
      var method = "".concat(connected ? "" : "dis", "connectedCallback");
      if (method in proto) element2[method]();
    };
    var _qsaObserver = qsaObserver({
      query: query2,
      handle: handle2
    }), parse = _qsaObserver.parse;
    var override = null;
    var whenDefined = function whenDefined2(name3) {
      if (!defined.has(name3)) {
        var _2, $ = new Promise(function($2) {
          _2 = $2;
        });
        defined.set(name3, {
          $,
          _: _2
        });
      }
      return defined.get(name3).$;
    };
    var augment = attributesObserver(whenDefined, MutationObserver$1);
    self.customElements = {
      define: function define2(is3, Class) {
        if (registry.has(is3)) throw new Error2('the name "'.concat(is3, '" has already been used with this registry'));
        classes.set(Class, is3);
        prototypes.set(is3, Class.prototype);
        registry.set(is3, Class);
        query2.push(is3);
        whenDefined(is3).then(function() {
          parse(document$1.querySelectorAll(is3));
        });
        defined.get(is3)._(Class);
      },
      get: function get5(is3) {
        return registry.get(is3);
      },
      whenDefined
    };
    defineProperty(HTMLBuiltIn.prototype = HTMLElement2.prototype, "constructor", {
      value: HTMLBuiltIn
    });
    self.HTMLElement = HTMLBuiltIn;
    document$1.createElement = function(name3, options4) {
      var is3 = options4 && options4.is;
      var Class = is3 ? registry.get(is3) : registry.get(name3);
      return Class ? new Class() : createElement.call(document$1, name3);
    };
    if (!("isConnected" in Node4.prototype)) defineProperty(Node4.prototype, "isConnected", {
      configurable: true,
      get: function get5() {
        return !(this.ownerDocument.compareDocumentPosition(this) & this.DOCUMENT_POSITION_DISCONNECTED);
      }
    });
  } else {
    legacy = !self.customElements.get("extends-br");
    if (legacy) {
      try {
        var BR = function BR2() {
          return self.Reflect.construct(HTMLBRElement, [], BR2);
        };
        BR.prototype = HTMLLIElement.prototype;
        var is2 = "extends-br";
        self.customElements.define("extends-br", BR, {
          "extends": "br"
        });
        legacy = document$1.createElement("br", {
          is: is2
        }).outerHTML.indexOf(is2) < 0;
        var _self$customElements = self.customElements, get4 = _self$customElements.get, _whenDefined = _self$customElements.whenDefined;
        self.customElements.whenDefined = function(is3) {
          var _this = this;
          return _whenDefined.call(this, is3).then(function(Class) {
            return Class || get4.call(_this, is3);
          });
        };
      } catch (o_O) {
      }
    }
  }
  if (legacy) {
    var _parseShadow = function _parseShadow2(element2) {
      var root68 = shadowRoots.get(element2);
      _parse(root68.querySelectorAll(this), element2.isConnected);
    };
    var customElements2 = self.customElements;
    var _createElement = document$1.createElement;
    var define = customElements2.define, _get = customElements2.get, upgrade = customElements2.upgrade;
    var _ref = Reflect2 || {
      construct: function construct2(HTMLElement3) {
        return HTMLElement3.call(this);
      }
    }, construct = _ref.construct;
    var shadowRoots = new WeakMap2();
    var shadows = new Set$1();
    var _classes = new Map2();
    var _defined = new Map2();
    var _prototypes = new Map2();
    var _registry = new Map2();
    var shadowed = [];
    var _query = [];
    var getCE = function getCE2(is3) {
      return _registry.get(is3) || _get.call(customElements2, is3);
    };
    var _handle = function _handle2(element2, connected, selector) {
      var proto = _prototypes.get(selector);
      if (connected && !proto.isPrototypeOf(element2)) {
        var redefine = expando(element2);
        _override = setPrototypeOf(element2, proto);
        try {
          new proto.constructor();
        } finally {
          _override = null;
          redefine();
        }
      }
      var method = "".concat(connected ? "" : "dis", "connectedCallback");
      if (method in proto) element2[method]();
    };
    var _qsaObserver2 = qsaObserver({
      query: _query,
      handle: _handle
    }), _parse = _qsaObserver2.parse;
    var _qsaObserver3 = qsaObserver({
      query: shadowed,
      handle: function handle3(element2, connected) {
        if (shadowRoots.has(element2)) {
          if (connected) shadows.add(element2);
          else shadows["delete"](element2);
          if (_query.length) _parseShadow.call(_query, element2);
        }
      }
    }), parseShadowed = _qsaObserver3.parse;
    var attachShadow = Element2.prototype.attachShadow;
    if (attachShadow) Element2.prototype.attachShadow = function(init4) {
      var root68 = attachShadow.call(this, init4);
      shadowRoots.set(this, root68);
      return root68;
    };
    var _whenDefined2 = function _whenDefined22(name3) {
      if (!_defined.has(name3)) {
        var _2, $ = new Promise(function($2) {
          _2 = $2;
        });
        _defined.set(name3, {
          $,
          _: _2
        });
      }
      return _defined.get(name3).$;
    };
    var _augment = attributesObserver(_whenDefined2, MutationObserver$1);
    var _override = null;
    getOwnPropertyNames(self).filter(function(k) {
      return /^HTML.*Element$/.test(k);
    }).forEach(function(k) {
      var HTMLElement3 = self[k];
      function HTMLBuiltIn2() {
        var constructor = this.constructor;
        if (!_classes.has(constructor)) throw new TypeError$1("Illegal constructor");
        var _classes$get = _classes.get(constructor), is3 = _classes$get.is, tag = _classes$get.tag;
        if (is3) {
          if (_override) return _augment(_override, is3);
          var element2 = _createElement.call(document$1, tag);
          element2.setAttribute("is", is3);
          return _augment(setPrototypeOf(element2, constructor.prototype), is3);
        } else return construct.call(this, HTMLElement3, [], constructor);
      }
      defineProperty(HTMLBuiltIn2.prototype = HTMLElement3.prototype, "constructor", {
        value: HTMLBuiltIn2
      });
      defineProperty(self, k, {
        value: HTMLBuiltIn2
      });
    });
    document$1.createElement = function(name3, options4) {
      var is3 = options4 && options4.is;
      if (is3) {
        var Class = _registry.get(is3);
        if (Class && _classes.get(Class).tag === name3) return new Class();
      }
      var element2 = _createElement.call(document$1, name3);
      if (is3) element2.setAttribute("is", is3);
      return element2;
    };
    customElements2.get = getCE;
    customElements2.whenDefined = _whenDefined2;
    customElements2.upgrade = function(element2) {
      var is3 = element2.getAttribute("is");
      if (is3) {
        var _constructor = _registry.get(is3);
        if (_constructor) {
          _augment(setPrototypeOf(element2, _constructor.prototype), is3);
          return;
        }
      }
      upgrade.call(customElements2, element2);
    };
    customElements2.define = function(is3, Class, options4) {
      if (getCE(is3)) throw new Error2("'".concat(is3, "' has already been defined as a custom element"));
      var selector;
      var tag = options4 && options4["extends"];
      _classes.set(Class, tag ? {
        is: is3,
        tag
      } : {
        is: "",
        tag: is3
      });
      if (tag) {
        selector = "".concat(tag, '[is="').concat(is3, '"]');
        _prototypes.set(selector, Class.prototype);
        _registry.set(is3, Class);
        _query.push(selector);
      } else {
        define.apply(customElements2, arguments);
        shadowed.push(selector = is3);
      }
      _whenDefined2(is3).then(function() {
        if (tag) {
          _parse(document$1.querySelectorAll(selector));
          shadows.forEach(_parseShadow, [selector]);
        } else parseShadowed(document$1.querySelectorAll(selector));
      });
      _defined.get(is3)._(Class);
    };
  }
})();

// node_modules/esm-env/false.js
var false_default = false;

// node_modules/svelte/src/internal/shared/utils.js
var is_array = Array.isArray;
var index_of = Array.prototype.indexOf;
var array_from = Array.from;
var object_keys = Object.keys;
var define_property = Object.defineProperty;
var get_descriptor = Object.getOwnPropertyDescriptor;
var get_descriptors = Object.getOwnPropertyDescriptors;
var object_prototype = Object.prototype;
var array_prototype = Array.prototype;
var get_prototype_of = Object.getPrototypeOf;
var is_extensible = Object.isExtensible;
var noop = () => {
};
function is_promise(value) {
  return typeof value?.then === "function";
}
function run2(fn) {
  return fn();
}
function run_all(arr) {
  for (var i2 = 0; i2 < arr.length; i2++) {
    arr[i2]();
  }
}

// node_modules/svelte/src/internal/client/constants.js
var DERIVED = 1 << 1;
var EFFECT = 1 << 2;
var RENDER_EFFECT = 1 << 3;
var BLOCK_EFFECT = 1 << 4;
var BRANCH_EFFECT = 1 << 5;
var ROOT_EFFECT = 1 << 6;
var BOUNDARY_EFFECT = 1 << 7;
var UNOWNED = 1 << 8;
var DISCONNECTED = 1 << 9;
var CLEAN = 1 << 10;
var DIRTY = 1 << 11;
var MAYBE_DIRTY = 1 << 12;
var INERT = 1 << 13;
var DESTROYED = 1 << 14;
var EFFECT_RAN = 1 << 15;
var EFFECT_TRANSPARENT = 1 << 16;
var LEGACY_DERIVED_PROP = 1 << 17;
var INSPECT_EFFECT = 1 << 18;
var HEAD_EFFECT = 1 << 19;
var EFFECT_HAS_DERIVED = 1 << 20;
var EFFECT_IS_UPDATING = 1 << 21;
var STATE_SYMBOL = Symbol("$state");
var STATE_SYMBOL_METADATA = Symbol("$state metadata");
var LEGACY_PROPS = Symbol("legacy props");
var LOADING_ATTR_SYMBOL = Symbol("");

// node_modules/svelte/src/internal/client/dom/task.js
var request_idle_callback = typeof requestIdleCallback === "undefined" ? (cb) => setTimeout(cb, 1) : requestIdleCallback;
var micro_tasks = [];
var idle_tasks = [];
function run_micro_tasks() {
  var tasks = micro_tasks;
  micro_tasks = [];
  run_all(tasks);
}
function run_idle_tasks() {
  var tasks = idle_tasks;
  idle_tasks = [];
  run_all(tasks);
}
function queue_micro_task(fn) {
  if (micro_tasks.length === 0) {
    queueMicrotask(run_micro_tasks);
  }
  micro_tasks.push(fn);
}
function queue_idle_task(fn) {
  if (idle_tasks.length === 0) {
    request_idle_callback(run_idle_tasks);
  }
  idle_tasks.push(fn);
}
function flush_tasks() {
  if (micro_tasks.length > 0) {
    run_micro_tasks();
  }
  if (idle_tasks.length > 0) {
    run_idle_tasks();
  }
}

// node_modules/svelte/src/internal/client/reactivity/equality.js
function equals(value) {
  return value === this.v;
}
function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function";
}
function safe_equals(value) {
  return !safe_not_equal(value, this.v);
}

// node_modules/svelte/src/internal/client/errors.js
function bind_invalid_checkbox_value() {
  if (false_default) {
    const error2 = new Error(`bind_invalid_checkbox_value
Using \`bind:value\` together with a checkbox input is not allowed. Use \`bind:checked\` instead
https://svelte.dev/e/bind_invalid_checkbox_value`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`);
  }
}
function derived_references_self() {
  if (false_default) {
    const error2 = new Error(`derived_references_self
A derived value cannot reference itself recursively
https://svelte.dev/e/derived_references_self`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/derived_references_self`);
  }
}
function effect_in_teardown(rune) {
  if (false_default) {
    const error2 = new Error(`effect_in_teardown
\`${rune}\` cannot be used inside an effect cleanup function
https://svelte.dev/e/effect_in_teardown`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/effect_in_teardown`);
  }
}
function effect_in_unowned_derived() {
  if (false_default) {
    const error2 = new Error(`effect_in_unowned_derived
Effect cannot be created inside a \`$derived\` value that was not itself created inside an effect
https://svelte.dev/e/effect_in_unowned_derived`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`);
  }
}
function effect_orphan(rune) {
  if (false_default) {
    const error2 = new Error(`effect_orphan
\`${rune}\` can only be used inside an effect (e.g. during component initialisation)
https://svelte.dev/e/effect_orphan`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/effect_orphan`);
  }
}
function effect_update_depth_exceeded() {
  if (false_default) {
    const error2 = new Error(`effect_update_depth_exceeded
Maximum update depth exceeded. This can happen when a reactive block or effect repeatedly sets a new value. Svelte limits the number of nested updates to prevent infinite loops
https://svelte.dev/e/effect_update_depth_exceeded`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);
  }
}
function hydration_failed() {
  if (false_default) {
    const error2 = new Error(`hydration_failed
Failed to hydrate the application
https://svelte.dev/e/hydration_failed`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/hydration_failed`);
  }
}
function invalid_snippet() {
  if (false_default) {
    const error2 = new Error(`invalid_snippet
Could not \`{@render}\` snippet due to the expression being \`null\` or \`undefined\`. Consider using optional chaining \`{@render snippet?.()}\`
https://svelte.dev/e/invalid_snippet`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/invalid_snippet`);
  }
}
function props_invalid_value(key2) {
  if (false_default) {
    const error2 = new Error(`props_invalid_value
Cannot do \`bind:${key2}={undefined}\` when \`${key2}\` has a fallback value
https://svelte.dev/e/props_invalid_value`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/props_invalid_value`);
  }
}
function rune_outside_svelte(rune) {
  if (false_default) {
    const error2 = new Error(`rune_outside_svelte
The \`${rune}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
https://svelte.dev/e/rune_outside_svelte`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/rune_outside_svelte`);
  }
}
function state_descriptors_fixed() {
  if (false_default) {
    const error2 = new Error(`state_descriptors_fixed
Property descriptors defined on \`$state\` objects must contain \`value\` and always be \`enumerable\`, \`configurable\` and \`writable\`.
https://svelte.dev/e/state_descriptors_fixed`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/state_descriptors_fixed`);
  }
}
function state_prototype_fixed() {
  if (false_default) {
    const error2 = new Error(`state_prototype_fixed
Cannot set prototype of \`$state\` object
https://svelte.dev/e/state_prototype_fixed`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/state_prototype_fixed`);
  }
}
function state_unsafe_mutation() {
  if (false_default) {
    const error2 = new Error(`state_unsafe_mutation
Updating state inside a derived or a template expression is forbidden. If the value should not be reactive, declare it without \`$state\`
https://svelte.dev/e/state_unsafe_mutation`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/state_unsafe_mutation`);
  }
}

// node_modules/svelte/src/internal/flags/index.js
var legacy_mode_flag = false;
var tracing_mode_flag = false;
function enable_legacy_mode_flag() {
  legacy_mode_flag = true;
}

// node_modules/svelte/src/constants.js
var EACH_ITEM_REACTIVE = 1;
var EACH_INDEX_REACTIVE = 1 << 1;
var EACH_IS_CONTROLLED = 1 << 2;
var EACH_IS_ANIMATED = 1 << 3;
var EACH_ITEM_IMMUTABLE = 1 << 4;
var PROPS_IS_IMMUTABLE = 1;
var PROPS_IS_RUNES = 1 << 1;
var PROPS_IS_UPDATED = 1 << 2;
var PROPS_IS_BINDABLE = 1 << 3;
var PROPS_IS_LAZY_INITIAL = 1 << 4;
var TRANSITION_OUT = 1 << 1;
var TRANSITION_GLOBAL = 1 << 2;
var TEMPLATE_FRAGMENT = 1;
var TEMPLATE_USE_IMPORT_NODE = 1 << 1;
var HYDRATION_START = "[";
var HYDRATION_START_ELSE = "[!";
var HYDRATION_END = "]";
var HYDRATION_ERROR = {};
var ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1;
var UNINITIALIZED = Symbol();
var FILENAME = Symbol("filename");
var HMR = Symbol("hmr");
var NAMESPACE_HTML = "http://www.w3.org/1999/xhtml";

// node_modules/svelte/src/internal/client/dev/tracing.js
var tracing_expressions = null;
function get_stack(label) {
  let error2 = Error();
  const stack2 = error2.stack;
  if (stack2) {
    const lines = stack2.split("\n");
    const new_lines = ["\n"];
    for (let i2 = 0; i2 < lines.length; i2++) {
      const line = lines[i2];
      if (line === "Error") {
        continue;
      }
      if (line.includes("validate_each_keys")) {
        return null;
      }
      if (line.includes("svelte/src/internal")) {
        continue;
      }
      new_lines.push(line);
    }
    if (new_lines.length === 1) {
      return null;
    }
    define_property(error2, "stack", {
      value: new_lines.join("\n")
    });
    define_property(error2, "name", {
      // 'Error' suffix is required for stack traces to be rendered properly
      value: `${label}Error`
    });
  }
  return error2;
}

// node_modules/svelte/src/internal/client/warnings.js
var bold = "font-weight: bold";
var normal = "font-weight: normal";
function hydration_attribute_changed(attribute, html2, value) {
  if (false_default) {
    console.warn(`%c[svelte] hydration_attribute_changed
%cThe \`${attribute}\` attribute on \`${html2}\` changed its value between server and client renders. The client value, \`${value}\`, will be ignored in favour of the server value
https://svelte.dev/e/hydration_attribute_changed`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/hydration_attribute_changed`);
  }
}
function hydration_html_changed(location) {
  if (false_default) {
    console.warn(`%c[svelte] hydration_html_changed
%c${location ? `The value of an \`{@html ...}\` block ${location} changed between server and client renders. The client value will be ignored in favour of the server value` : "The value of an `{@html ...}` block changed between server and client renders. The client value will be ignored in favour of the server value"}
https://svelte.dev/e/hydration_html_changed`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/hydration_html_changed`);
  }
}
function hydration_mismatch(location) {
  if (false_default) {
    console.warn(`%c[svelte] hydration_mismatch
%c${location ? `Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}` : "Hydration failed because the initial UI does not match what was rendered on the server"}
https://svelte.dev/e/hydration_mismatch`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/hydration_mismatch`);
  }
}
function lifecycle_double_unmount() {
  if (false_default) {
    console.warn(`%c[svelte] lifecycle_double_unmount
%cTried to unmount a component that was not mounted
https://svelte.dev/e/lifecycle_double_unmount`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/lifecycle_double_unmount`);
  }
}
function ownership_invalid_binding(parent2, child2, owner) {
  if (false_default) {
    console.warn(`%c[svelte] ownership_invalid_binding
%c${parent2} passed a value to ${child2} with \`bind:\`, but the value is owned by ${owner}. Consider creating a binding between ${owner} and ${parent2}
https://svelte.dev/e/ownership_invalid_binding`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/ownership_invalid_binding`);
  }
}
function ownership_invalid_mutation(component2, owner) {
  if (false_default) {
    console.warn(`%c[svelte] ownership_invalid_mutation
%c${component2 ? `${component2} mutated a value owned by ${owner}. This is strongly discouraged. Consider passing values to child components with \`bind:\`, or use a callback instead` : "Mutating a value outside the component that created it is strongly discouraged. Consider passing values to child components with `bind:`, or use a callback instead"}
https://svelte.dev/e/ownership_invalid_mutation`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/ownership_invalid_mutation`);
  }
}
function state_proxy_equality_mismatch(operator2) {
  if (false_default) {
    console.warn(`%c[svelte] state_proxy_equality_mismatch
%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${operator2}\` will produce unexpected results
https://svelte.dev/e/state_proxy_equality_mismatch`, bold, normal);
  } else {
    console.warn(`https://svelte.dev/e/state_proxy_equality_mismatch`);
  }
}

// node_modules/svelte/src/internal/client/dev/ownership.js
var boundaries = {};
var chrome_pattern = /at (?:.+ \()?(.+):(\d+):(\d+)\)?$/;
var firefox_pattern = /@(.+):(\d+):(\d+)$/;
function get_stack2() {
  const stack2 = new Error().stack;
  if (!stack2) return null;
  const entries = [];
  for (const line of stack2.split("\n")) {
    let match = chrome_pattern.exec(line) ?? firefox_pattern.exec(line);
    if (match) {
      entries.push({
        file: match[1],
        line: +match[2],
        column: +match[3]
      });
    }
  }
  return entries;
}
function get_component() {
  const stack2 = get_stack2()?.slice(4);
  if (!stack2) return null;
  for (let i2 = 0; i2 < stack2.length; i2++) {
    const entry = stack2[i2];
    const modules = boundaries[entry.file];
    if (!modules) {
      if (i2 === 0) return null;
      continue;
    }
    for (const module2 of modules) {
      if (module2.end == null) {
        return null;
      }
      if (module2.start.line < entry.line && module2.end.line > entry.line) {
        return module2.component;
      }
    }
  }
  return null;
}
var ADD_OWNER = Symbol("ADD_OWNER");
function add_owner(object2, owner, global = false, skip_warning = false) {
  if (object2 && !global) {
    const component2 = dev_current_component_function;
    const metadata2 = object2[STATE_SYMBOL_METADATA];
    if (metadata2 && !has_owner(metadata2, component2)) {
      let original = get_owner(metadata2);
      if (owner && owner[FILENAME] !== component2[FILENAME] && !skip_warning) {
        ownership_invalid_binding(component2[FILENAME], owner[FILENAME], original[FILENAME]);
      }
    }
  }
  add_owner_to_object(object2, owner, /* @__PURE__ */ new Set());
}
function widen_ownership(from, to) {
  if (to.owners === null) {
    return;
  }
  while (from) {
    if (from.owners === null) {
      to.owners = null;
      break;
    }
    for (const owner of from.owners) {
      to.owners.add(owner);
    }
    from = from.parent;
  }
}
function add_owner_to_object(object2, owner, seen) {
  const metadata2 = (
    /** @type {ProxyMetadata} */
    object2?.[STATE_SYMBOL_METADATA]
  );
  if (metadata2) {
    if ("owners" in metadata2 && metadata2.owners != null) {
      if (owner) {
        metadata2.owners.add(owner);
      } else {
        metadata2.owners = null;
      }
    }
  } else if (object2 && typeof object2 === "object") {
    if (seen.has(object2)) return;
    seen.add(object2);
    if (ADD_OWNER in object2 && object2[ADD_OWNER]) {
      render_effect(() => {
        object2[ADD_OWNER](owner);
      });
    } else {
      var proto = get_prototype_of(object2);
      if (proto === Object.prototype) {
        for (const key2 in object2) {
          if (Object.getOwnPropertyDescriptor(object2, key2)?.get) {
            let current = UNINITIALIZED;
            render_effect(() => {
              const next2 = object2[key2];
              if (current !== next2) {
                current = next2;
                add_owner_to_object(next2, owner, seen);
              }
            });
          } else {
            add_owner_to_object(object2[key2], owner, seen);
          }
        }
      } else if (proto === Array.prototype) {
        for (let i2 = 0; i2 < object2.length; i2 += 1) {
          add_owner_to_object(object2[i2], owner, seen);
        }
      }
    }
  }
}
function has_owner(metadata2, component2) {
  if (metadata2.owners === null) {
    return true;
  }
  return metadata2.owners.has(component2) || // This helps avoid false positives when using HMR, where the component function is replaced
  FILENAME in component2 && [...metadata2.owners].some(
    (owner) => (
      /** @type {any} */
      owner[FILENAME] === component2[FILENAME]
    )
  ) || metadata2.parent !== null && has_owner(metadata2.parent, component2);
}
function get_owner(metadata2) {
  return metadata2?.owners?.values().next().value ?? get_owner(
    /** @type {ProxyMetadata} */
    metadata2.parent
  );
}
var skip = false;
function check_ownership(metadata2) {
  if (skip) return;
  const component2 = get_component();
  if (component2 && !has_owner(metadata2, component2)) {
    let original = get_owner(metadata2);
    if (original[FILENAME] !== component2[FILENAME]) {
      ownership_invalid_mutation(component2[FILENAME], original[FILENAME]);
    } else {
      ownership_invalid_mutation();
    }
  }
}

// node_modules/svelte/src/internal/shared/errors.js
function lifecycle_outside_component(name3) {
  if (false_default) {
    const error2 = new Error(`lifecycle_outside_component
\`${name3}(...)\` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component`);
    error2.name = "Svelte error";
    throw error2;
  } else {
    throw new Error(`https://svelte.dev/e/lifecycle_outside_component`);
  }
}

// node_modules/svelte/src/internal/client/context.js
var component_context = null;
function set_component_context(context2) {
  component_context = context2;
}
var dev_current_component_function = null;
function set_dev_current_component_function(fn) {
  dev_current_component_function = fn;
}
function getContext(key2) {
  const context_map = get_or_init_context_map("getContext");
  const result = (
    /** @type {T} */
    context_map.get(key2)
  );
  return result;
}
function setContext(key2, context2) {
  const context_map = get_or_init_context_map("setContext");
  if (false_default) {
    untrack(() => add_owner(context2, null, true));
  }
  context_map.set(key2, context2);
  return context2;
}
function push(props2, runes = false, fn) {
  var ctx2 = component_context = {
    p: component_context,
    c: null,
    d: false,
    e: null,
    m: false,
    s: props2,
    x: null,
    l: null
  };
  if (legacy_mode_flag && !runes) {
    component_context.l = {
      s: null,
      u: null,
      r1: [],
      r2: source(false)
    };
  }
  teardown(() => {
    ctx2.d = true;
  });
  if (false_default) {
    component_context.function = fn;
    dev_current_component_function = fn;
  }
}
function pop(component2) {
  const context_stack_item = component_context;
  if (context_stack_item !== null) {
    if (component2 !== void 0) {
      context_stack_item.x = component2;
    }
    const component_effects = context_stack_item.e;
    if (component_effects !== null) {
      var previous_effect = active_effect;
      var previous_reaction = active_reaction;
      context_stack_item.e = null;
      try {
        for (var i2 = 0; i2 < component_effects.length; i2++) {
          var component_effect = component_effects[i2];
          set_active_effect(component_effect.effect);
          set_active_reaction(component_effect.reaction);
          effect(component_effect.fn);
        }
      } finally {
        set_active_effect(previous_effect);
        set_active_reaction(previous_reaction);
      }
    }
    component_context = context_stack_item.p;
    if (false_default) {
      dev_current_component_function = context_stack_item.p?.function ?? null;
    }
    context_stack_item.m = true;
  }
  return component2 || /** @type {T} */
  {};
}
function is_runes() {
  return !legacy_mode_flag || component_context !== null && component_context.l === null;
}
function get_or_init_context_map(name3) {
  if (component_context === null) {
    lifecycle_outside_component(name3);
  }
  return component_context.c ??= new Map(get_parent_context(component_context) || void 0);
}
function get_parent_context(component_context2) {
  let parent2 = component_context2.p;
  while (parent2 !== null) {
    const context_map = parent2.c;
    if (context_map !== null) {
      return context_map;
    }
    parent2 = parent2.p;
  }
  return null;
}

// node_modules/svelte/src/internal/client/proxy.js
var parent_metadata = null;
function proxy2(value, prev) {
  if (typeof value !== "object" || value === null || STATE_SYMBOL in value) {
    return value;
  }
  const prototype = get_prototype_of(value);
  if (prototype !== object_prototype && prototype !== array_prototype) {
    return value;
  }
  var sources = /* @__PURE__ */ new Map();
  var is_proxied_array = is_array(value);
  var version = state(0);
  var stack2 = false_default && tracing_mode_flag ? get_stack("CreatedAt") : null;
  var reaction = active_reaction;
  var with_parent = (fn) => {
    var previous_reaction = active_reaction;
    set_active_reaction(reaction);
    var result;
    if (false_default) {
      var previous_metadata = parent_metadata;
      parent_metadata = metadata2;
      result = fn();
      parent_metadata = previous_metadata;
    } else {
      result = fn();
    }
    set_active_reaction(previous_reaction);
    return result;
  };
  if (is_proxied_array) {
    sources.set("length", state(
      /** @type {any[]} */
      value.length,
      stack2
    ));
  }
  var metadata2;
  if (false_default) {
    metadata2 = {
      parent: parent_metadata,
      owners: null
    };
    if (prev) {
      const prev_owners = prev.v?.[STATE_SYMBOL_METADATA]?.owners;
      metadata2.owners = prev_owners ? new Set(prev_owners) : null;
    } else {
      metadata2.owners = parent_metadata === null ? component_context !== null ? /* @__PURE__ */ new Set([component_context.function]) : null : /* @__PURE__ */ new Set();
    }
  }
  return new Proxy(
    /** @type {any} */
    value,
    {
      defineProperty(_2, prop2, descriptor) {
        if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) {
          state_descriptors_fixed();
        }
        var s = sources.get(prop2);
        if (s === void 0) {
          s = with_parent(() => state(descriptor.value, stack2));
          sources.set(prop2, s);
        } else {
          set(
            s,
            with_parent(() => proxy2(descriptor.value))
          );
        }
        return true;
      },
      deleteProperty(target, prop2) {
        var s = sources.get(prop2);
        if (s === void 0) {
          if (prop2 in target) {
            sources.set(
              prop2,
              with_parent(() => state(UNINITIALIZED, stack2))
            );
          }
        } else {
          if (is_proxied_array && typeof prop2 === "string") {
            var ls = (
              /** @type {Source<number>} */
              sources.get("length")
            );
            var n = Number(prop2);
            if (Number.isInteger(n) && n < ls.v) {
              set(ls, n);
            }
          }
          set(s, UNINITIALIZED);
          update_version(version);
        }
        return true;
      },
      get(target, prop2, receiver) {
        if (false_default && prop2 === STATE_SYMBOL_METADATA) {
          return metadata2;
        }
        if (prop2 === STATE_SYMBOL) {
          return value;
        }
        var s = sources.get(prop2);
        var exists = prop2 in target;
        if (s === void 0 && (!exists || get_descriptor(target, prop2)?.writable)) {
          s = with_parent(() => state(proxy2(exists ? target[prop2] : UNINITIALIZED), stack2));
          sources.set(prop2, s);
        }
        if (s !== void 0) {
          var v = get(s);
          if (false_default) {
            var prop_metadata = v?.[STATE_SYMBOL_METADATA];
            if (prop_metadata && prop_metadata?.parent !== metadata2) {
              widen_ownership(metadata2, prop_metadata);
            }
          }
          return v === UNINITIALIZED ? void 0 : v;
        }
        return Reflect.get(target, prop2, receiver);
      },
      getOwnPropertyDescriptor(target, prop2) {
        var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
        if (descriptor && "value" in descriptor) {
          var s = sources.get(prop2);
          if (s) descriptor.value = get(s);
        } else if (descriptor === void 0) {
          var source3 = sources.get(prop2);
          var value2 = source3?.v;
          if (source3 !== void 0 && value2 !== UNINITIALIZED) {
            return {
              enumerable: true,
              configurable: true,
              value: value2,
              writable: true
            };
          }
        }
        return descriptor;
      },
      has(target, prop2) {
        if (false_default && prop2 === STATE_SYMBOL_METADATA) {
          return true;
        }
        if (prop2 === STATE_SYMBOL) {
          return true;
        }
        var s = sources.get(prop2);
        var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop2);
        if (s !== void 0 || active_effect !== null && (!has || get_descriptor(target, prop2)?.writable)) {
          if (s === void 0) {
            s = with_parent(() => state(has ? proxy2(target[prop2]) : UNINITIALIZED, stack2));
            sources.set(prop2, s);
          }
          var value2 = get(s);
          if (value2 === UNINITIALIZED) {
            return false;
          }
        }
        return has;
      },
      set(target, prop2, value2, receiver) {
        var s = sources.get(prop2);
        var has = prop2 in target;
        if (is_proxied_array && prop2 === "length") {
          for (var i2 = value2; i2 < /** @type {Source<number>} */
          s.v; i2 += 1) {
            var other_s = sources.get(i2 + "");
            if (other_s !== void 0) {
              set(other_s, UNINITIALIZED);
            } else if (i2 in target) {
              other_s = with_parent(() => state(UNINITIALIZED, stack2));
              sources.set(i2 + "", other_s);
            }
          }
        }
        if (s === void 0) {
          if (!has || get_descriptor(target, prop2)?.writable) {
            s = with_parent(() => state(void 0, stack2));
            set(
              s,
              with_parent(() => proxy2(value2))
            );
            sources.set(prop2, s);
          }
        } else {
          has = s.v !== UNINITIALIZED;
          set(
            s,
            with_parent(() => proxy2(value2))
          );
        }
        if (false_default) {
          var prop_metadata = value2?.[STATE_SYMBOL_METADATA];
          if (prop_metadata && prop_metadata?.parent !== metadata2) {
            widen_ownership(metadata2, prop_metadata);
          }
          check_ownership(metadata2);
        }
        var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
        if (descriptor?.set) {
          descriptor.set.call(receiver, value2);
        }
        if (!has) {
          if (is_proxied_array && typeof prop2 === "string") {
            var ls = (
              /** @type {Source<number>} */
              sources.get("length")
            );
            var n = Number(prop2);
            if (Number.isInteger(n) && n >= ls.v) {
              set(ls, n + 1);
            }
          }
          update_version(version);
        }
        return true;
      },
      ownKeys(target) {
        get(version);
        var own_keys = Reflect.ownKeys(target).filter((key3) => {
          var source4 = sources.get(key3);
          return source4 === void 0 || source4.v !== UNINITIALIZED;
        });
        for (var [key2, source3] of sources) {
          if (source3.v !== UNINITIALIZED && !(key2 in target)) {
            own_keys.push(key2);
          }
        }
        return own_keys;
      },
      setPrototypeOf() {
        state_prototype_fixed();
      }
    }
  );
}
function update_version(signal, d = 1) {
  set(signal, signal.v + d);
}
function get_proxied_value(value) {
  try {
    if (value !== null && typeof value === "object" && STATE_SYMBOL in value) {
      return value[STATE_SYMBOL];
    }
  } catch {
  }
  return value;
}
function is(a, b) {
  return Object.is(get_proxied_value(a), get_proxied_value(b));
}

// node_modules/svelte/src/internal/client/reactivity/sources.js
var inspect_effects = /* @__PURE__ */ new Set();
var old_values = /* @__PURE__ */ new Map();
function set_inspect_effects(v) {
  inspect_effects = v;
}
function source(v, stack2) {
  var signal = {
    f: 0,
    // TODO ideally we could skip this altogether, but it causes type errors
    v,
    reactions: null,
    equals,
    rv: 0,
    wv: 0
  };
  if (false_default && tracing_mode_flag) {
    signal.created = stack2 ?? get_stack("CreatedAt");
    signal.debug = null;
  }
  return signal;
}
function state(v, stack2) {
  const s = source(v, stack2);
  push_reaction_value(s);
  return s;
}
// @__NO_SIDE_EFFECTS__
function mutable_source(initial_value, immutable = false) {
  const s = source(initial_value);
  if (!immutable) {
    s.equals = safe_equals;
  }
  if (legacy_mode_flag && component_context !== null && component_context.l !== null) {
    (component_context.l.s ??= []).push(s);
  }
  return s;
}
function mutate(source3, value) {
  set(
    source3,
    untrack(() => get(source3))
  );
  return value;
}
function set(source3, value, should_proxy = false) {
  if (active_reaction !== null && !untracking && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT)) !== 0 && !reaction_sources?.includes(source3)) {
    state_unsafe_mutation();
  }
  let new_value = should_proxy ? proxy2(value, source3) : value;
  return internal_set(source3, new_value);
}
function internal_set(source3, value) {
  if (!source3.equals(value)) {
    var old_value = source3.v;
    if (is_destroying_effect) {
      old_values.set(source3, value);
    } else {
      old_values.set(source3, old_value);
    }
    source3.v = value;
    source3.wv = increment_write_version();
    if (false_default && tracing_mode_flag) {
      source3.updated = get_stack("UpdatedAt");
      if (active_effect != null) {
        source3.trace_need_increase = true;
        source3.trace_v ??= old_value;
      }
    }
    mark_reactions(source3, DIRTY);
    if (is_runes() && active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) {
      if (untracked_writes === null) {
        set_untracked_writes([source3]);
      } else {
        untracked_writes.push(source3);
      }
    }
    if (false_default && inspect_effects.size > 0) {
      const inspects = Array.from(inspect_effects);
      for (const effect2 of inspects) {
        if ((effect2.f & CLEAN) !== 0) {
          set_signal_status(effect2, MAYBE_DIRTY);
        }
        if (check_dirtiness(effect2)) {
          update_effect(effect2);
        }
      }
      inspect_effects.clear();
    }
  }
  return value;
}
function mark_reactions(signal, status) {
  var reactions = signal.reactions;
  if (reactions === null) return;
  var runes = is_runes();
  var length = reactions.length;
  for (var i2 = 0; i2 < length; i2++) {
    var reaction = reactions[i2];
    var flags2 = reaction.f;
    if ((flags2 & DIRTY) !== 0) continue;
    if (!runes && reaction === active_effect) continue;
    if (false_default && (flags2 & INSPECT_EFFECT) !== 0) {
      inspect_effects.add(reaction);
      continue;
    }
    set_signal_status(reaction, status);
    if ((flags2 & (CLEAN | UNOWNED)) !== 0) {
      if ((flags2 & DERIVED) !== 0) {
        mark_reactions(
          /** @type {Derived} */
          reaction,
          MAYBE_DIRTY
        );
      } else {
        schedule_effect(
          /** @type {Effect} */
          reaction
        );
      }
    }
  }
}

// node_modules/svelte/src/internal/client/reactivity/deriveds.js
// @__NO_SIDE_EFFECTS__
function derived(fn) {
  var flags2 = DERIVED | DIRTY;
  var parent_derived = active_reaction !== null && (active_reaction.f & DERIVED) !== 0 ? (
    /** @type {Derived} */
    active_reaction
  ) : null;
  if (active_effect === null || parent_derived !== null && (parent_derived.f & UNOWNED) !== 0) {
    flags2 |= UNOWNED;
  } else {
    active_effect.f |= EFFECT_HAS_DERIVED;
  }
  const signal = {
    ctx: component_context,
    deps: null,
    effects: null,
    equals,
    f: flags2,
    fn,
    reactions: null,
    rv: 0,
    v: (
      /** @type {V} */
      null
    ),
    wv: 0,
    parent: parent_derived ?? active_effect
  };
  if (false_default && tracing_mode_flag) {
    signal.created = get_stack("CreatedAt");
  }
  return signal;
}
function user_derived(fn) {
  const d = /* @__PURE__ */ derived(fn);
  push_reaction_value(d);
  return d;
}
// @__NO_SIDE_EFFECTS__
function derived_safe_equal(fn) {
  const signal = /* @__PURE__ */ derived(fn);
  signal.equals = safe_equals;
  return signal;
}
function destroy_derived_effects(derived3) {
  var effects = derived3.effects;
  if (effects !== null) {
    derived3.effects = null;
    for (var i2 = 0; i2 < effects.length; i2 += 1) {
      destroy_effect(
        /** @type {Effect} */
        effects[i2]
      );
    }
  }
}
var stack = [];
function get_derived_parent_effect(derived3) {
  var parent2 = derived3.parent;
  while (parent2 !== null) {
    if ((parent2.f & DERIVED) === 0) {
      return (
        /** @type {Effect} */
        parent2
      );
    }
    parent2 = parent2.parent;
  }
  return null;
}
function execute_derived(derived3) {
  var value;
  var prev_active_effect = active_effect;
  set_active_effect(get_derived_parent_effect(derived3));
  if (false_default) {
    let prev_inspect_effects = inspect_effects;
    set_inspect_effects(/* @__PURE__ */ new Set());
    try {
      if (stack.includes(derived3)) {
        derived_references_self();
      }
      stack.push(derived3);
      destroy_derived_effects(derived3);
      value = update_reaction(derived3);
    } finally {
      set_active_effect(prev_active_effect);
      set_inspect_effects(prev_inspect_effects);
      stack.pop();
    }
  } else {
    try {
      destroy_derived_effects(derived3);
      value = update_reaction(derived3);
    } finally {
      set_active_effect(prev_active_effect);
    }
  }
  return value;
}
function update_derived(derived3) {
  var value = execute_derived(derived3);
  var status = (skip_reaction || (derived3.f & UNOWNED) !== 0) && derived3.deps !== null ? MAYBE_DIRTY : CLEAN;
  set_signal_status(derived3, status);
  if (!derived3.equals(value)) {
    derived3.v = value;
    derived3.wv = increment_write_version();
  }
}

// node_modules/svelte/src/internal/client/dom/hydration.js
var hydrating = false;
function set_hydrating(value) {
  hydrating = value;
}
var hydrate_node;
function set_hydrate_node(node) {
  if (node === null) {
    hydration_mismatch();
    throw HYDRATION_ERROR;
  }
  return hydrate_node = node;
}
function hydrate_next() {
  return set_hydrate_node(
    /** @type {TemplateNode} */
    get_next_sibling(hydrate_node)
  );
}
function reset(node) {
  if (!hydrating) return;
  if (get_next_sibling(hydrate_node) !== null) {
    hydration_mismatch();
    throw HYDRATION_ERROR;
  }
  hydrate_node = node;
}
function next(count2 = 1) {
  if (hydrating) {
    var i2 = count2;
    var node = hydrate_node;
    while (i2--) {
      node = /** @type {TemplateNode} */
      get_next_sibling(node);
    }
    hydrate_node = node;
  }
}
function remove_nodes() {
  var depth = 0;
  var node = hydrate_node;
  while (true) {
    if (node.nodeType === 8) {
      var data = (
        /** @type {Comment} */
        node.data
      );
      if (data === HYDRATION_END) {
        if (depth === 0) return node;
        depth -= 1;
      } else if (data === HYDRATION_START || data === HYDRATION_START_ELSE) {
        depth += 1;
      }
    }
    var next2 = (
      /** @type {TemplateNode} */
      get_next_sibling(node)
    );
    node.remove();
    node = next2;
  }
}

// node_modules/svelte/src/internal/client/dev/equality.js
function init_array_prototype_warnings() {
  const array_prototype2 = Array.prototype;
  const cleanup = Array.__svelte_cleanup;
  if (cleanup) {
    cleanup();
  }
  const { indexOf, lastIndexOf, includes } = array_prototype2;
  array_prototype2.indexOf = function(item, from_index) {
    const index3 = indexOf.call(this, item, from_index);
    if (index3 === -1) {
      for (let i2 = from_index ?? 0; i2 < this.length; i2 += 1) {
        if (get_proxied_value(this[i2]) === item) {
          state_proxy_equality_mismatch("array.indexOf(...)");
          break;
        }
      }
    }
    return index3;
  };
  array_prototype2.lastIndexOf = function(item, from_index) {
    const index3 = lastIndexOf.call(this, item, from_index ?? this.length - 1);
    if (index3 === -1) {
      for (let i2 = 0; i2 <= (from_index ?? this.length - 1); i2 += 1) {
        if (get_proxied_value(this[i2]) === item) {
          state_proxy_equality_mismatch("array.lastIndexOf(...)");
          break;
        }
      }
    }
    return index3;
  };
  array_prototype2.includes = function(item, from_index) {
    const has = includes.call(this, item, from_index);
    if (!has) {
      for (let i2 = 0; i2 < this.length; i2 += 1) {
        if (get_proxied_value(this[i2]) === item) {
          state_proxy_equality_mismatch("array.includes(...)");
          break;
        }
      }
    }
    return has;
  };
  Array.__svelte_cleanup = () => {
    array_prototype2.indexOf = indexOf;
    array_prototype2.lastIndexOf = lastIndexOf;
    array_prototype2.includes = includes;
  };
}

// node_modules/svelte/src/internal/client/dom/operations.js
var $window;
var $document;
var is_firefox;
var first_child_getter;
var next_sibling_getter;
function init_operations() {
  if ($window !== void 0) {
    return;
  }
  $window = window;
  $document = document;
  is_firefox = /Firefox/.test(navigator.userAgent);
  var element_prototype = Element.prototype;
  var node_prototype = Node.prototype;
  var text_prototype = Text.prototype;
  first_child_getter = get_descriptor(node_prototype, "firstChild").get;
  next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get;
  if (is_extensible(element_prototype)) {
    element_prototype.__click = void 0;
    element_prototype.__className = void 0;
    element_prototype.__attributes = null;
    element_prototype.__style = void 0;
    element_prototype.__e = void 0;
  }
  if (is_extensible(text_prototype)) {
    text_prototype.__t = void 0;
  }
  if (false_default) {
    element_prototype.__svelte_meta = null;
    init_array_prototype_warnings();
  }
}
function create_text(value = "") {
  return document.createTextNode(value);
}
// @__NO_SIDE_EFFECTS__
function get_first_child(node) {
  return first_child_getter.call(node);
}
// @__NO_SIDE_EFFECTS__
function get_next_sibling(node) {
  return next_sibling_getter.call(node);
}
function child(node, is_text) {
  if (!hydrating) {
    return /* @__PURE__ */ get_first_child(node);
  }
  var child2 = (
    /** @type {TemplateNode} */
    /* @__PURE__ */ get_first_child(hydrate_node)
  );
  if (child2 === null) {
    child2 = hydrate_node.appendChild(create_text());
  } else if (is_text && child2.nodeType !== 3) {
    var text2 = create_text();
    child2?.before(text2);
    set_hydrate_node(text2);
    return text2;
  }
  set_hydrate_node(child2);
  return child2;
}
function first_child(fragment, is_text) {
  if (!hydrating) {
    var first = (
      /** @type {DocumentFragment} */
      /* @__PURE__ */ get_first_child(
        /** @type {Node} */
        fragment
      )
    );
    if (first instanceof Comment && first.data === "") return /* @__PURE__ */ get_next_sibling(first);
    return first;
  }
  if (is_text && hydrate_node?.nodeType !== 3) {
    var text2 = create_text();
    hydrate_node?.before(text2);
    set_hydrate_node(text2);
    return text2;
  }
  return hydrate_node;
}
function sibling(node, count2 = 1, is_text = false) {
  let next_sibling = hydrating ? hydrate_node : node;
  var last_sibling;
  while (count2--) {
    last_sibling = next_sibling;
    next_sibling = /** @type {TemplateNode} */
    /* @__PURE__ */ get_next_sibling(next_sibling);
  }
  if (!hydrating) {
    return next_sibling;
  }
  var type = next_sibling?.nodeType;
  if (is_text && type !== 3) {
    var text2 = create_text();
    if (next_sibling === null) {
      last_sibling?.after(text2);
    } else {
      next_sibling.before(text2);
    }
    set_hydrate_node(text2);
    return text2;
  }
  set_hydrate_node(next_sibling);
  return (
    /** @type {TemplateNode} */
    next_sibling
  );
}
function clear_text_content(node) {
  node.textContent = "";
}

// node_modules/svelte/src/internal/client/runtime.js
var handled_errors = /* @__PURE__ */ new WeakSet();
var is_throwing_error = false;
var is_flushing = false;
var last_scheduled_effect = null;
var is_updating_effect = false;
var is_destroying_effect = false;
function set_is_destroying_effect(value) {
  is_destroying_effect = value;
}
var queued_root_effects = [];
var dev_effect_stack = [];
var active_reaction = null;
var untracking = false;
function set_active_reaction(reaction) {
  active_reaction = reaction;
}
var active_effect = null;
function set_active_effect(effect2) {
  active_effect = effect2;
}
var reaction_sources = null;
function set_reaction_sources(sources) {
  reaction_sources = sources;
}
function push_reaction_value(value) {
  if (active_reaction !== null && active_reaction.f & EFFECT_IS_UPDATING) {
    if (reaction_sources === null) {
      set_reaction_sources([value]);
    } else {
      reaction_sources.push(value);
    }
  }
}
var new_deps = null;
var skipped_deps = 0;
var untracked_writes = null;
function set_untracked_writes(value) {
  untracked_writes = value;
}
var write_version = 1;
var read_version = 0;
var skip_reaction = false;
var captured_signals = null;
function increment_write_version() {
  return ++write_version;
}
function check_dirtiness(reaction) {
  var flags2 = reaction.f;
  if ((flags2 & DIRTY) !== 0) {
    return true;
  }
  if ((flags2 & MAYBE_DIRTY) !== 0) {
    var dependencies = reaction.deps;
    var is_unowned = (flags2 & UNOWNED) !== 0;
    if (dependencies !== null) {
      var i2;
      var dependency;
      var is_disconnected = (flags2 & DISCONNECTED) !== 0;
      var is_unowned_connected = is_unowned && active_effect !== null && !skip_reaction;
      var length = dependencies.length;
      if (is_disconnected || is_unowned_connected) {
        var derived3 = (
          /** @type {Derived} */
          reaction
        );
        var parent2 = derived3.parent;
        for (i2 = 0; i2 < length; i2++) {
          dependency = dependencies[i2];
          if (is_disconnected || !dependency?.reactions?.includes(derived3)) {
            (dependency.reactions ??= []).push(derived3);
          }
        }
        if (is_disconnected) {
          derived3.f ^= DISCONNECTED;
        }
        if (is_unowned_connected && parent2 !== null && (parent2.f & UNOWNED) === 0) {
          derived3.f ^= UNOWNED;
        }
      }
      for (i2 = 0; i2 < length; i2++) {
        dependency = dependencies[i2];
        if (check_dirtiness(
          /** @type {Derived} */
          dependency
        )) {
          update_derived(
            /** @type {Derived} */
            dependency
          );
        }
        if (dependency.wv > reaction.wv) {
          return true;
        }
      }
    }
    if (!is_unowned || active_effect !== null && !skip_reaction) {
      set_signal_status(reaction, CLEAN);
    }
  }
  return false;
}
function propagate_error(error2, effect2) {
  var current = effect2;
  while (current !== null) {
    if ((current.f & BOUNDARY_EFFECT) !== 0) {
      try {
        current.fn(error2);
        return;
      } catch {
        current.f ^= BOUNDARY_EFFECT;
      }
    }
    current = current.parent;
  }
  is_throwing_error = false;
  throw error2;
}
function should_rethrow_error(effect2) {
  return (effect2.f & DESTROYED) === 0 && (effect2.parent === null || (effect2.parent.f & BOUNDARY_EFFECT) === 0);
}
function handle_error(error2, effect2, previous_effect, component_context2) {
  if (is_throwing_error) {
    if (previous_effect === null) {
      is_throwing_error = false;
    }
    if (should_rethrow_error(effect2)) {
      throw error2;
    }
    return;
  }
  if (previous_effect !== null) {
    is_throwing_error = true;
  }
  if (!false_default || component_context2 === null || !(error2 instanceof Error) || handled_errors.has(error2)) {
    propagate_error(error2, effect2);
    return;
  }
  handled_errors.add(error2);
  const component_stack = [];
  const effect_name = effect2.fn?.name;
  if (effect_name) {
    component_stack.push(effect_name);
  }
  let current_context = component_context2;
  while (current_context !== null) {
    if (false_default) {
      var filename = current_context.function?.[FILENAME];
      if (filename) {
        const file = filename.split("/").pop();
        component_stack.push(file);
      }
    }
    current_context = current_context.p;
  }
  const indent = is_firefox ? "  " : "	";
  define_property(error2, "message", {
    value: error2.message + `
${component_stack.map((name3) => `
${indent}in ${name3}`).join("")}
`
  });
  define_property(error2, "component_stack", {
    value: component_stack
  });
  const stack2 = error2.stack;
  if (stack2) {
    const lines = stack2.split("\n");
    const new_lines = [];
    for (let i2 = 0; i2 < lines.length; i2++) {
      const line = lines[i2];
      if (line.includes("svelte/src/internal")) {
        continue;
      }
      new_lines.push(line);
    }
    define_property(error2, "stack", {
      value: new_lines.join("\n")
    });
  }
  propagate_error(error2, effect2);
  if (should_rethrow_error(effect2)) {
    throw error2;
  }
}
function schedule_possible_effect_self_invalidation(signal, effect2, root68 = true) {
  var reactions = signal.reactions;
  if (reactions === null) return;
  for (var i2 = 0; i2 < reactions.length; i2++) {
    var reaction = reactions[i2];
    if (reaction_sources?.includes(signal)) continue;
    if ((reaction.f & DERIVED) !== 0) {
      schedule_possible_effect_self_invalidation(
        /** @type {Derived} */
        reaction,
        effect2,
        false
      );
    } else if (effect2 === reaction) {
      if (root68) {
        set_signal_status(reaction, DIRTY);
      } else if ((reaction.f & CLEAN) !== 0) {
        set_signal_status(reaction, MAYBE_DIRTY);
      }
      schedule_effect(
        /** @type {Effect} */
        reaction
      );
    }
  }
}
function update_reaction(reaction) {
  var previous_deps = new_deps;
  var previous_skipped_deps = skipped_deps;
  var previous_untracked_writes = untracked_writes;
  var previous_reaction = active_reaction;
  var previous_skip_reaction = skip_reaction;
  var previous_reaction_sources = reaction_sources;
  var previous_component_context = component_context;
  var previous_untracking = untracking;
  var flags2 = reaction.f;
  new_deps = /** @type {null | Value[]} */
  null;
  skipped_deps = 0;
  untracked_writes = null;
  skip_reaction = (flags2 & UNOWNED) !== 0 && (untracking || !is_updating_effect || active_reaction === null);
  active_reaction = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;
  reaction_sources = null;
  set_component_context(reaction.ctx);
  untracking = false;
  read_version++;
  reaction.f |= EFFECT_IS_UPDATING;
  try {
    var result = (
      /** @type {Function} */
      (0, reaction.fn)()
    );
    var deps = reaction.deps;
    if (new_deps !== null) {
      var i2;
      remove_reactions(reaction, skipped_deps);
      if (deps !== null && skipped_deps > 0) {
        deps.length = skipped_deps + new_deps.length;
        for (i2 = 0; i2 < new_deps.length; i2++) {
          deps[skipped_deps + i2] = new_deps[i2];
        }
      } else {
        reaction.deps = deps = new_deps;
      }
      if (!skip_reaction) {
        for (i2 = skipped_deps; i2 < deps.length; i2++) {
          (deps[i2].reactions ??= []).push(reaction);
        }
      }
    } else if (deps !== null && skipped_deps < deps.length) {
      remove_reactions(reaction, skipped_deps);
      deps.length = skipped_deps;
    }
    if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) {
      for (i2 = 0; i2 < /** @type {Source[]} */
      untracked_writes.length; i2++) {
        schedule_possible_effect_self_invalidation(
          untracked_writes[i2],
          /** @type {Effect} */
          reaction
        );
      }
    }
    if (previous_reaction !== null) {
      read_version++;
      if (untracked_writes !== null) {
        if (previous_untracked_writes === null) {
          previous_untracked_writes = untracked_writes;
        } else {
          previous_untracked_writes.push(.../** @type {Source[]} */
          untracked_writes);
        }
      }
    }
    return result;
  } finally {
    new_deps = previous_deps;
    skipped_deps = previous_skipped_deps;
    untracked_writes = previous_untracked_writes;
    active_reaction = previous_reaction;
    skip_reaction = previous_skip_reaction;
    reaction_sources = previous_reaction_sources;
    set_component_context(previous_component_context);
    untracking = previous_untracking;
    reaction.f ^= EFFECT_IS_UPDATING;
  }
}
function remove_reaction(signal, dependency) {
  let reactions = dependency.reactions;
  if (reactions !== null) {
    var index3 = index_of.call(reactions, signal);
    if (index3 !== -1) {
      var new_length = reactions.length - 1;
      if (new_length === 0) {
        reactions = dependency.reactions = null;
      } else {
        reactions[index3] = reactions[new_length];
        reactions.pop();
      }
    }
  }
  if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear
  // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`
  // allows us to skip the expensive work of disconnecting and immediately reconnecting it
  (new_deps === null || !new_deps.includes(dependency))) {
    set_signal_status(dependency, MAYBE_DIRTY);
    if ((dependency.f & (UNOWNED | DISCONNECTED)) === 0) {
      dependency.f ^= DISCONNECTED;
    }
    destroy_derived_effects(
      /** @type {Derived} **/
      dependency
    );
    remove_reactions(
      /** @type {Derived} **/
      dependency,
      0
    );
  }
}
function remove_reactions(signal, start_index) {
  var dependencies = signal.deps;
  if (dependencies === null) return;
  for (var i2 = start_index; i2 < dependencies.length; i2++) {
    remove_reaction(signal, dependencies[i2]);
  }
}
function update_effect(effect2) {
  var flags2 = effect2.f;
  if ((flags2 & DESTROYED) !== 0) {
    return;
  }
  set_signal_status(effect2, CLEAN);
  var previous_effect = active_effect;
  var previous_component_context = component_context;
  var was_updating_effect = is_updating_effect;
  active_effect = effect2;
  is_updating_effect = true;
  if (false_default) {
    var previous_component_fn = dev_current_component_function;
    set_dev_current_component_function(effect2.component_function);
  }
  try {
    if ((flags2 & BLOCK_EFFECT) !== 0) {
      destroy_block_effect_children(effect2);
    } else {
      destroy_effect_children(effect2);
    }
    execute_effect_teardown(effect2);
    var teardown2 = update_reaction(effect2);
    effect2.teardown = typeof teardown2 === "function" ? teardown2 : null;
    effect2.wv = write_version;
    var deps = effect2.deps;
    if (false_default && tracing_mode_flag && (effect2.f & DIRTY) !== 0 && deps !== null) {
      for (let i2 = 0; i2 < deps.length; i2++) {
        var dep = deps[i2];
        if (dep.trace_need_increase) {
          dep.wv = increment_write_version();
          dep.trace_need_increase = void 0;
          dep.trace_v = void 0;
        }
      }
    }
    if (false_default) {
      dev_effect_stack.push(effect2);
    }
  } catch (error2) {
    handle_error(error2, effect2, previous_effect, previous_component_context || effect2.ctx);
  } finally {
    is_updating_effect = was_updating_effect;
    active_effect = previous_effect;
    if (false_default) {
      set_dev_current_component_function(previous_component_fn);
    }
  }
}
function log_effect_stack() {
  console.error(
    "Last ten effects were: ",
    dev_effect_stack.slice(-10).map((d) => d.fn)
  );
  dev_effect_stack = [];
}
function infinite_loop_guard() {
  try {
    effect_update_depth_exceeded();
  } catch (error2) {
    if (false_default) {
      define_property(error2, "stack", {
        value: ""
      });
    }
    if (last_scheduled_effect !== null) {
      if (false_default) {
        try {
          handle_error(error2, last_scheduled_effect, null, null);
        } catch (e) {
          log_effect_stack();
          throw e;
        }
      } else {
        handle_error(error2, last_scheduled_effect, null, null);
      }
    } else {
      if (false_default) {
        log_effect_stack();
      }
      throw error2;
    }
  }
}
function flush_queued_root_effects() {
  var was_updating_effect = is_updating_effect;
  try {
    var flush_count = 0;
    is_updating_effect = true;
    while (queued_root_effects.length > 0) {
      if (flush_count++ > 1e3) {
        infinite_loop_guard();
      }
      var root_effects = queued_root_effects;
      var length = root_effects.length;
      queued_root_effects = [];
      for (var i2 = 0; i2 < length; i2++) {
        var collected_effects = process_effects(root_effects[i2]);
        flush_queued_effects(collected_effects);
      }
    }
  } finally {
    is_flushing = false;
    is_updating_effect = was_updating_effect;
    last_scheduled_effect = null;
    if (false_default) {
      dev_effect_stack = [];
    }
    old_values.clear();
  }
}
function flush_queued_effects(effects) {
  var length = effects.length;
  if (length === 0) return;
  for (var i2 = 0; i2 < length; i2++) {
    var effect2 = effects[i2];
    if ((effect2.f & (DESTROYED | INERT)) === 0) {
      try {
        if (check_dirtiness(effect2)) {
          update_effect(effect2);
          if (effect2.deps === null && effect2.first === null && effect2.nodes_start === null) {
            if (effect2.teardown === null) {
              unlink_effect(effect2);
            } else {
              effect2.fn = null;
            }
          }
        }
      } catch (error2) {
        handle_error(error2, effect2, null, effect2.ctx);
      }
    }
  }
}
function schedule_effect(signal) {
  if (!is_flushing) {
    is_flushing = true;
    queueMicrotask(flush_queued_root_effects);
  }
  var effect2 = last_scheduled_effect = signal;
  while (effect2.parent !== null) {
    effect2 = effect2.parent;
    var flags2 = effect2.f;
    if ((flags2 & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {
      if ((flags2 & CLEAN) === 0) return;
      effect2.f ^= CLEAN;
    }
  }
  queued_root_effects.push(effect2);
}
function process_effects(root68) {
  var effects = [];
  var effect2 = root68;
  while (effect2 !== null) {
    var flags2 = effect2.f;
    var is_branch = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
    var is_skippable_branch = is_branch && (flags2 & CLEAN) !== 0;
    if (!is_skippable_branch && (flags2 & INERT) === 0) {
      if ((flags2 & EFFECT) !== 0) {
        effects.push(effect2);
      } else if (is_branch) {
        effect2.f ^= CLEAN;
      } else {
        var previous_active_reaction = active_reaction;
        try {
          active_reaction = effect2;
          if (check_dirtiness(effect2)) {
            update_effect(effect2);
          }
        } catch (error2) {
          handle_error(error2, effect2, null, effect2.ctx);
        } finally {
          active_reaction = previous_active_reaction;
        }
      }
      var child2 = effect2.first;
      if (child2 !== null) {
        effect2 = child2;
        continue;
      }
    }
    var parent2 = effect2.parent;
    effect2 = effect2.next;
    while (effect2 === null && parent2 !== null) {
      effect2 = parent2.next;
      parent2 = parent2.parent;
    }
  }
  return effects;
}
function flushSync(fn) {
  var result;
  if (fn) {
    is_flushing = true;
    flush_queued_root_effects();
    result = fn();
  }
  flush_tasks();
  while (queued_root_effects.length > 0) {
    is_flushing = true;
    flush_queued_root_effects();
    flush_tasks();
  }
  return (
    /** @type {T} */
    result
  );
}
async function tick() {
  await Promise.resolve();
  flushSync();
}
function get(signal) {
  var flags2 = signal.f;
  var is_derived = (flags2 & DERIVED) !== 0;
  if (captured_signals !== null) {
    captured_signals.add(signal);
  }
  if (active_reaction !== null && !untracking) {
    if (!reaction_sources?.includes(signal)) {
      var deps = active_reaction.deps;
      if (signal.rv < read_version) {
        signal.rv = read_version;
        if (new_deps === null && deps !== null && deps[skipped_deps] === signal) {
          skipped_deps++;
        } else if (new_deps === null) {
          new_deps = [signal];
        } else if (!skip_reaction || !new_deps.includes(signal)) {
          new_deps.push(signal);
        }
      }
    }
  } else if (is_derived && /** @type {Derived} */
  signal.deps === null && /** @type {Derived} */
  signal.effects === null) {
    var derived3 = (
      /** @type {Derived} */
      signal
    );
    var parent2 = derived3.parent;
    if (parent2 !== null && (parent2.f & UNOWNED) === 0) {
      derived3.f ^= UNOWNED;
    }
  }
  if (is_derived) {
    derived3 = /** @type {Derived} */
    signal;
    if (check_dirtiness(derived3)) {
      update_derived(derived3);
    }
  }
  if (false_default && tracing_mode_flag && tracing_expressions !== null && active_reaction !== null && tracing_expressions.reaction === active_reaction) {
    if (signal.debug) {
      signal.debug();
    } else if (signal.created) {
      var entry = tracing_expressions.entries.get(signal);
      if (entry === void 0) {
        entry = { read: [] };
        tracing_expressions.entries.set(signal, entry);
      }
      entry.read.push(get_stack("TracedAt"));
    }
  }
  if (is_destroying_effect && old_values.has(signal)) {
    return old_values.get(signal);
  }
  return signal.v;
}
function untrack(fn) {
  var previous_untracking = untracking;
  try {
    untracking = true;
    return fn();
  } finally {
    untracking = previous_untracking;
  }
}
var STATUS_MASK = ~(DIRTY | MAYBE_DIRTY | CLEAN);
function set_signal_status(signal, status) {
  signal.f = signal.f & STATUS_MASK | status;
}
function deep_read_state(value) {
  if (typeof value !== "object" || !value || value instanceof EventTarget) {
    return;
  }
  if (STATE_SYMBOL in value) {
    deep_read(value);
  } else if (!Array.isArray(value)) {
    for (let key2 in value) {
      const prop2 = value[key2];
      if (typeof prop2 === "object" && prop2 && STATE_SYMBOL in prop2) {
        deep_read(prop2);
      }
    }
  }
}
function deep_read(value, visited = /* @__PURE__ */ new Set()) {
  if (typeof value === "object" && value !== null && // We don't want to traverse DOM elements
  !(value instanceof EventTarget) && !visited.has(value)) {
    visited.add(value);
    if (value instanceof Date) {
      value.getTime();
    }
    for (let key2 in value) {
      try {
        deep_read(value[key2], visited);
      } catch (e) {
      }
    }
    const proto = get_prototype_of(value);
    if (proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype) {
      const descriptors = get_descriptors(proto);
      for (let key2 in descriptors) {
        const get4 = descriptors[key2].get;
        if (get4) {
          try {
            get4.call(value);
          } catch (e) {
          }
        }
      }
    }
  }
}

// node_modules/svelte/src/internal/client/reactivity/effects.js
function validate_effect(rune) {
  if (active_effect === null && active_reaction === null) {
    effect_orphan(rune);
  }
  if (active_reaction !== null && (active_reaction.f & UNOWNED) !== 0 && active_effect === null) {
    effect_in_unowned_derived();
  }
  if (is_destroying_effect) {
    effect_in_teardown(rune);
  }
}
function push_effect(effect2, parent_effect) {
  var parent_last = parent_effect.last;
  if (parent_last === null) {
    parent_effect.last = parent_effect.first = effect2;
  } else {
    parent_last.next = effect2;
    effect2.prev = parent_last;
    parent_effect.last = effect2;
  }
}
function create_effect(type, fn, sync, push2 = true) {
  var parent2 = active_effect;
  if (false_default) {
    while (parent2 !== null && (parent2.f & INSPECT_EFFECT) !== 0) {
      parent2 = parent2.parent;
    }
  }
  var effect2 = {
    ctx: component_context,
    deps: null,
    nodes_start: null,
    nodes_end: null,
    f: type | DIRTY,
    first: null,
    fn,
    last: null,
    next: null,
    parent: parent2,
    prev: null,
    teardown: null,
    transitions: null,
    wv: 0
  };
  if (false_default) {
    effect2.component_function = dev_current_component_function;
  }
  if (sync) {
    try {
      update_effect(effect2);
      effect2.f |= EFFECT_RAN;
    } catch (e) {
      destroy_effect(effect2);
      throw e;
    }
  } else if (fn !== null) {
    schedule_effect(effect2);
  }
  var inert = sync && effect2.deps === null && effect2.first === null && effect2.nodes_start === null && effect2.teardown === null && (effect2.f & (EFFECT_HAS_DERIVED | BOUNDARY_EFFECT)) === 0;
  if (!inert && push2) {
    if (parent2 !== null) {
      push_effect(effect2, parent2);
    }
    if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0) {
      var derived3 = (
        /** @type {Derived} */
        active_reaction
      );
      (derived3.effects ??= []).push(effect2);
    }
  }
  return effect2;
}
function teardown(fn) {
  const effect2 = create_effect(RENDER_EFFECT, null, false);
  set_signal_status(effect2, CLEAN);
  effect2.teardown = fn;
  return effect2;
}
function user_effect(fn) {
  validate_effect("$effect");
  var defer = active_effect !== null && (active_effect.f & BRANCH_EFFECT) !== 0 && component_context !== null && !component_context.m;
  if (false_default) {
    define_property(fn, "name", {
      value: "$effect"
    });
  }
  if (defer) {
    var context2 = (
      /** @type {ComponentContext} */
      component_context
    );
    (context2.e ??= []).push({
      fn,
      effect: active_effect,
      reaction: active_reaction
    });
  } else {
    var signal = effect(fn);
    return signal;
  }
}
function user_pre_effect(fn) {
  validate_effect("$effect.pre");
  if (false_default) {
    define_property(fn, "name", {
      value: "$effect.pre"
    });
  }
  return render_effect(fn);
}
function effect_root(fn) {
  const effect2 = create_effect(ROOT_EFFECT, fn, true);
  return () => {
    destroy_effect(effect2);
  };
}
function component_root(fn) {
  const effect2 = create_effect(ROOT_EFFECT, fn, true);
  return (options4 = {}) => {
    return new Promise((fulfil) => {
      if (options4.outro) {
        pause_effect(effect2, () => {
          destroy_effect(effect2);
          fulfil(void 0);
        });
      } else {
        destroy_effect(effect2);
        fulfil(void 0);
      }
    });
  };
}
function effect(fn) {
  return create_effect(EFFECT, fn, false);
}
function legacy_pre_effect(deps, fn) {
  var context2 = (
    /** @type {ComponentContextLegacy} */
    component_context
  );
  var token = { effect: null, ran: false };
  context2.l.r1.push(token);
  token.effect = render_effect(() => {
    deps();
    if (token.ran) return;
    token.ran = true;
    set(context2.l.r2, true);
    untrack(fn);
  });
}
function legacy_pre_effect_reset() {
  var context2 = (
    /** @type {ComponentContextLegacy} */
    component_context
  );
  render_effect(() => {
    if (!get(context2.l.r2)) return;
    for (var token of context2.l.r1) {
      var effect2 = token.effect;
      if ((effect2.f & CLEAN) !== 0) {
        set_signal_status(effect2, MAYBE_DIRTY);
      }
      if (check_dirtiness(effect2)) {
        update_effect(effect2);
      }
      token.ran = false;
    }
    context2.l.r2.v = false;
  });
}
function render_effect(fn) {
  return create_effect(RENDER_EFFECT, fn, true);
}
function template_effect(fn, thunks = [], d = derived) {
  const deriveds = thunks.map(d);
  const effect2 = () => fn(...deriveds.map(get));
  if (false_default) {
    define_property(effect2, "name", {
      value: "{expression}"
    });
  }
  return block(effect2);
}
function block(fn, flags2 = 0) {
  return create_effect(RENDER_EFFECT | BLOCK_EFFECT | flags2, fn, true);
}
function branch(fn, push2 = true) {
  return create_effect(RENDER_EFFECT | BRANCH_EFFECT, fn, true, push2);
}
function execute_effect_teardown(effect2) {
  var teardown2 = effect2.teardown;
  if (teardown2 !== null) {
    const previously_destroying_effect = is_destroying_effect;
    const previous_reaction = active_reaction;
    set_is_destroying_effect(true);
    set_active_reaction(null);
    try {
      teardown2.call(null);
    } finally {
      set_is_destroying_effect(previously_destroying_effect);
      set_active_reaction(previous_reaction);
    }
  }
}
function destroy_effect_children(signal, remove_dom = false) {
  var effect2 = signal.first;
  signal.first = signal.last = null;
  while (effect2 !== null) {
    var next2 = effect2.next;
    if ((effect2.f & ROOT_EFFECT) !== 0) {
      effect2.parent = null;
    } else {
      destroy_effect(effect2, remove_dom);
    }
    effect2 = next2;
  }
}
function destroy_block_effect_children(signal) {
  var effect2 = signal.first;
  while (effect2 !== null) {
    var next2 = effect2.next;
    if ((effect2.f & BRANCH_EFFECT) === 0) {
      destroy_effect(effect2);
    }
    effect2 = next2;
  }
}
function destroy_effect(effect2, remove_dom = true) {
  var removed = false;
  if ((remove_dom || (effect2.f & HEAD_EFFECT) !== 0) && effect2.nodes_start !== null) {
    var node = effect2.nodes_start;
    var end = effect2.nodes_end;
    while (node !== null) {
      var next2 = node === end ? null : (
        /** @type {TemplateNode} */
        get_next_sibling(node)
      );
      node.remove();
      node = next2;
    }
    removed = true;
  }
  destroy_effect_children(effect2, remove_dom && !removed);
  remove_reactions(effect2, 0);
  set_signal_status(effect2, DESTROYED);
  var transitions = effect2.transitions;
  if (transitions !== null) {
    for (const transition2 of transitions) {
      transition2.stop();
    }
  }
  execute_effect_teardown(effect2);
  var parent2 = effect2.parent;
  if (parent2 !== null && parent2.first !== null) {
    unlink_effect(effect2);
  }
  if (false_default) {
    effect2.component_function = null;
  }
  effect2.next = effect2.prev = effect2.teardown = effect2.ctx = effect2.deps = effect2.fn = effect2.nodes_start = effect2.nodes_end = null;
}
function unlink_effect(effect2) {
  var parent2 = effect2.parent;
  var prev = effect2.prev;
  var next2 = effect2.next;
  if (prev !== null) prev.next = next2;
  if (next2 !== null) next2.prev = prev;
  if (parent2 !== null) {
    if (parent2.first === effect2) parent2.first = next2;
    if (parent2.last === effect2) parent2.last = prev;
  }
}
function pause_effect(effect2, callback) {
  var transitions = [];
  pause_children(effect2, transitions, true);
  run_out_transitions(transitions, () => {
    destroy_effect(effect2);
    if (callback) callback();
  });
}
function run_out_transitions(transitions, fn) {
  var remaining = transitions.length;
  if (remaining > 0) {
    var check = () => --remaining || fn();
    for (var transition2 of transitions) {
      transition2.out(check);
    }
  } else {
    fn();
  }
}
function pause_children(effect2, transitions, local) {
  if ((effect2.f & INERT) !== 0) return;
  effect2.f ^= INERT;
  if (effect2.transitions !== null) {
    for (const transition2 of effect2.transitions) {
      if (transition2.is_global || local) {
        transitions.push(transition2);
      }
    }
  }
  var child2 = effect2.first;
  while (child2 !== null) {
    var sibling2 = child2.next;
    var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
    pause_children(child2, transitions, transparent ? local : false);
    child2 = sibling2;
  }
}
function resume_effect(effect2) {
  resume_children(effect2, true);
}
function resume_children(effect2, local) {
  if ((effect2.f & INERT) === 0) return;
  effect2.f ^= INERT;
  if ((effect2.f & CLEAN) === 0) {
    effect2.f ^= CLEAN;
  }
  if (check_dirtiness(effect2)) {
    set_signal_status(effect2, DIRTY);
    schedule_effect(effect2);
  }
  var child2 = effect2.first;
  while (child2 !== null) {
    var sibling2 = child2.next;
    var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
    resume_children(child2, transparent ? local : false);
    child2 = sibling2;
  }
  if (effect2.transitions !== null) {
    for (const transition2 of effect2.transitions) {
      if (transition2.is_global || local) {
        transition2.in();
      }
    }
  }
}

// node_modules/svelte/src/utils.js
var regex_return_characters = /\r/g;
function hash(str) {
  str = str.replace(regex_return_characters, "");
  let hash3 = 5381;
  let i2 = str.length;
  while (i2--) hash3 = (hash3 << 5) - hash3 ^ str.charCodeAt(i2);
  return (hash3 >>> 0).toString(36);
}
var DOM_BOOLEAN_ATTRIBUTES = [
  "allowfullscreen",
  "async",
  "autofocus",
  "autoplay",
  "checked",
  "controls",
  "default",
  "disabled",
  "formnovalidate",
  "hidden",
  "indeterminate",
  "inert",
  "ismap",
  "loop",
  "multiple",
  "muted",
  "nomodule",
  "novalidate",
  "open",
  "playsinline",
  "readonly",
  "required",
  "reversed",
  "seamless",
  "selected",
  "webkitdirectory",
  "defer",
  "disablepictureinpicture",
  "disableremoteplayback"
];
var DOM_PROPERTIES = [
  ...DOM_BOOLEAN_ATTRIBUTES,
  "formNoValidate",
  "isMap",
  "noModule",
  "playsInline",
  "readOnly",
  "value",
  "volume",
  "defaultValue",
  "defaultChecked",
  "srcObject",
  "noValidate",
  "allowFullscreen",
  "disablePictureInPicture",
  "disableRemotePlayback"
];
var PASSIVE_EVENTS = ["touchstart", "touchmove"];
function is_passive_event(name3) {
  return PASSIVE_EVENTS.includes(name3);
}
function sanitize_location(location) {
  return location?.replace(/\//g, "/\u200B");
}

// node_modules/svelte/src/internal/client/dom/elements/misc.js
function remove_textarea_child(dom) {
  if (hydrating && get_first_child(dom) !== null) {
    clear_text_content(dom);
  }
}
var listening_to_form_reset = false;
function add_form_reset_listener() {
  if (!listening_to_form_reset) {
    listening_to_form_reset = true;
    document.addEventListener(
      "reset",
      (evt) => {
        Promise.resolve().then(() => {
          if (!evt.defaultPrevented) {
            for (
              const e of
              /**@type {HTMLFormElement} */
              evt.target.elements
            ) {
              e.__on_r?.();
            }
          }
        });
      },
      // In the capture phase to guarantee we get noticed of it (no possiblity of stopPropagation)
      { capture: true }
    );
  }
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/shared.js
function without_reactive_context(fn) {
  var previous_reaction = active_reaction;
  var previous_effect = active_effect;
  set_active_reaction(null);
  set_active_effect(null);
  try {
    return fn();
  } finally {
    set_active_reaction(previous_reaction);
    set_active_effect(previous_effect);
  }
}
function listen_to_event_and_reset_event(element2, event2, handler, on_reset = handler) {
  element2.addEventListener(event2, () => without_reactive_context(handler));
  const prev = element2.__on_r;
  if (prev) {
    element2.__on_r = () => {
      prev();
      on_reset(true);
    };
  } else {
    element2.__on_r = () => on_reset(true);
  }
  add_form_reset_listener();
}

// node_modules/svelte/src/internal/client/dom/elements/events.js
var all_registered_events = /* @__PURE__ */ new Set();
var root_event_handles = /* @__PURE__ */ new Set();
function create_event(event_name, dom, handler, options4 = {}) {
  function target_handler(event2) {
    if (!options4.capture) {
      handle_event_propagation.call(dom, event2);
    }
    if (!event2.cancelBubble) {
      return without_reactive_context(() => {
        return handler?.call(this, event2);
      });
    }
  }
  if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") {
    queue_micro_task(() => {
      dom.addEventListener(event_name, target_handler, options4);
    });
  } else {
    dom.addEventListener(event_name, target_handler, options4);
  }
  return target_handler;
}
function event(event_name, dom, handler, capture, passive2) {
  var options4 = { capture, passive: passive2 };
  var target_handler = create_event(event_name, dom, handler, options4);
  if (dom === document.body || dom === window || dom === document) {
    teardown(() => {
      dom.removeEventListener(event_name, target_handler, options4);
    });
  }
}
function delegate(events2) {
  for (var i2 = 0; i2 < events2.length; i2++) {
    all_registered_events.add(events2[i2]);
  }
  for (var fn of root_event_handles) {
    fn(events2);
  }
}
function handle_event_propagation(event2) {
  var handler_element = this;
  var owner_document = (
    /** @type {Node} */
    handler_element.ownerDocument
  );
  var event_name = event2.type;
  var path2 = event2.composedPath?.() || [];
  var current_target = (
    /** @type {null | Element} */
    path2[0] || event2.target
  );
  var path_idx = 0;
  var handled_at = event2.__root;
  if (handled_at) {
    var at_idx = path2.indexOf(handled_at);
    if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */
    window)) {
      event2.__root = handler_element;
      return;
    }
    var handler_idx = path2.indexOf(handler_element);
    if (handler_idx === -1) {
      return;
    }
    if (at_idx <= handler_idx) {
      path_idx = at_idx;
    }
  }
  current_target = /** @type {Element} */
  path2[path_idx] || event2.target;
  if (current_target === handler_element) return;
  define_property(event2, "currentTarget", {
    configurable: true,
    get() {
      return current_target || owner_document;
    }
  });
  var previous_reaction = active_reaction;
  var previous_effect = active_effect;
  set_active_reaction(null);
  set_active_effect(null);
  try {
    var throw_error;
    var other_errors = [];
    while (current_target !== null) {
      var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */
      current_target.host || null;
      try {
        var delegated = current_target["__" + event_name];
        if (delegated != null && (!/** @type {any} */
        current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well
        // -> the target could not have been disabled because it emits the event in the first place
        event2.target === current_target)) {
          if (is_array(delegated)) {
            var [fn, ...data] = delegated;
            fn.apply(current_target, [event2, ...data]);
          } else {
            delegated.call(current_target, event2);
          }
        }
      } catch (error2) {
        if (throw_error) {
          other_errors.push(error2);
        } else {
          throw_error = error2;
        }
      }
      if (event2.cancelBubble || parent_element === handler_element || parent_element === null) {
        break;
      }
      current_target = parent_element;
    }
    if (throw_error) {
      for (let error2 of other_errors) {
        queueMicrotask(() => {
          throw error2;
        });
      }
      throw throw_error;
    }
  } finally {
    event2.__root = handler_element;
    delete event2.currentTarget;
    set_active_reaction(previous_reaction);
    set_active_effect(previous_effect);
  }
}

// node_modules/svelte/src/internal/client/dom/blocks/svelte-head.js
var head_anchor;
function reset_head_anchor() {
  head_anchor = void 0;
}

// node_modules/svelte/src/internal/client/dom/reconciler.js
function create_fragment_from_html(html2) {
  var elem = document.createElement("template");
  elem.innerHTML = html2;
  return elem.content;
}

// node_modules/svelte/src/internal/client/dom/template.js
function assign_nodes(start2, end) {
  var effect2 = (
    /** @type {Effect} */
    active_effect
  );
  if (effect2.nodes_start === null) {
    effect2.nodes_start = start2;
    effect2.nodes_end = end;
  }
}
// @__NO_SIDE_EFFECTS__
function template(content2, flags2) {
  var is_fragment = (flags2 & TEMPLATE_FRAGMENT) !== 0;
  var use_import_node = (flags2 & TEMPLATE_USE_IMPORT_NODE) !== 0;
  var node;
  var has_start = !content2.startsWith("<!>");
  return () => {
    if (hydrating) {
      assign_nodes(hydrate_node, null);
      return hydrate_node;
    }
    if (node === void 0) {
      node = create_fragment_from_html(has_start ? content2 : "<!>" + content2);
      if (!is_fragment) node = /** @type {Node} */
      get_first_child(node);
    }
    var clone = (
      /** @type {TemplateNode} */
      use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)
    );
    if (is_fragment) {
      var start2 = (
        /** @type {TemplateNode} */
        get_first_child(clone)
      );
      var end = (
        /** @type {TemplateNode} */
        clone.lastChild
      );
      assign_nodes(start2, end);
    } else {
      assign_nodes(clone, clone);
    }
    return clone;
  };
}
// @__NO_SIDE_EFFECTS__
function ns_template(content2, flags2, ns = "svg") {
  var has_start = !content2.startsWith("<!>");
  var is_fragment = (flags2 & TEMPLATE_FRAGMENT) !== 0;
  var wrapped = `<${ns}>${has_start ? content2 : "<!>" + content2}</${ns}>`;
  var node;
  return () => {
    if (hydrating) {
      assign_nodes(hydrate_node, null);
      return hydrate_node;
    }
    if (!node) {
      var fragment = (
        /** @type {DocumentFragment} */
        create_fragment_from_html(wrapped)
      );
      var root68 = (
        /** @type {Element} */
        get_first_child(fragment)
      );
      if (is_fragment) {
        node = document.createDocumentFragment();
        while (get_first_child(root68)) {
          node.appendChild(
            /** @type {Node} */
            get_first_child(root68)
          );
        }
      } else {
        node = /** @type {Element} */
        get_first_child(root68);
      }
    }
    var clone = (
      /** @type {TemplateNode} */
      node.cloneNode(true)
    );
    if (is_fragment) {
      var start2 = (
        /** @type {TemplateNode} */
        get_first_child(clone)
      );
      var end = (
        /** @type {TemplateNode} */
        clone.lastChild
      );
      assign_nodes(start2, end);
    } else {
      assign_nodes(clone, clone);
    }
    return clone;
  };
}
function text(value = "") {
  if (!hydrating) {
    var t4 = create_text(value + "");
    assign_nodes(t4, t4);
    return t4;
  }
  var node = hydrate_node;
  if (node.nodeType !== 3) {
    node.before(node = create_text());
    set_hydrate_node(node);
  }
  assign_nodes(node, node);
  return node;
}
function comment() {
  if (hydrating) {
    assign_nodes(hydrate_node, null);
    return hydrate_node;
  }
  var frag = document.createDocumentFragment();
  var start2 = document.createComment("");
  var anchor = create_text();
  frag.append(start2, anchor);
  assign_nodes(start2, anchor);
  return frag;
}
function append(anchor, dom) {
  if (hydrating) {
    active_effect.nodes_end = hydrate_node;
    hydrate_next();
    return;
  }
  if (anchor === null) {
    return;
  }
  anchor.before(
    /** @type {Node} */
    dom
  );
}

// node_modules/svelte/src/internal/client/render.js
var should_intro = true;
function set_text(text2, value) {
  var str = value == null ? "" : typeof value === "object" ? value + "" : value;
  if (str !== (text2.__t ??= text2.nodeValue)) {
    text2.__t = str;
    text2.nodeValue = str + "";
  }
}
function mount(component2, options4) {
  return _mount(component2, options4);
}
function hydrate(component2, options4) {
  init_operations();
  options4.intro = options4.intro ?? false;
  const target = options4.target;
  const was_hydrating = hydrating;
  const previous_hydrate_node = hydrate_node;
  try {
    var anchor = (
      /** @type {TemplateNode} */
      get_first_child(target)
    );
    while (anchor && (anchor.nodeType !== 8 || /** @type {Comment} */
    anchor.data !== HYDRATION_START)) {
      anchor = /** @type {TemplateNode} */
      get_next_sibling(anchor);
    }
    if (!anchor) {
      throw HYDRATION_ERROR;
    }
    set_hydrating(true);
    set_hydrate_node(
      /** @type {Comment} */
      anchor
    );
    hydrate_next();
    const instance2 = _mount(component2, { ...options4, anchor });
    if (hydrate_node === null || hydrate_node.nodeType !== 8 || /** @type {Comment} */
    hydrate_node.data !== HYDRATION_END) {
      hydration_mismatch();
      throw HYDRATION_ERROR;
    }
    set_hydrating(false);
    return (
      /**  @type {Exports} */
      instance2
    );
  } catch (error2) {
    if (error2 === HYDRATION_ERROR) {
      if (options4.recover === false) {
        hydration_failed();
      }
      init_operations();
      clear_text_content(target);
      set_hydrating(false);
      return mount(component2, options4);
    }
    throw error2;
  } finally {
    set_hydrating(was_hydrating);
    set_hydrate_node(previous_hydrate_node);
    reset_head_anchor();
  }
}
var document_listeners = /* @__PURE__ */ new Map();
function _mount(Component, { target, anchor, props: props2 = {}, events: events2, context: context2, intro = true }) {
  init_operations();
  var registered_events = /* @__PURE__ */ new Set();
  var event_handle = (events3) => {
    for (var i2 = 0; i2 < events3.length; i2++) {
      var event_name = events3[i2];
      if (registered_events.has(event_name)) continue;
      registered_events.add(event_name);
      var passive2 = is_passive_event(event_name);
      target.addEventListener(event_name, handle_event_propagation, { passive: passive2 });
      var n = document_listeners.get(event_name);
      if (n === void 0) {
        document.addEventListener(event_name, handle_event_propagation, { passive: passive2 });
        document_listeners.set(event_name, 1);
      } else {
        document_listeners.set(event_name, n + 1);
      }
    }
  };
  event_handle(array_from(all_registered_events));
  root_event_handles.add(event_handle);
  var component2 = void 0;
  var unmount2 = component_root(() => {
    var anchor_node = anchor ?? target.appendChild(create_text());
    branch(() => {
      if (context2) {
        push({});
        var ctx2 = (
          /** @type {ComponentContext} */
          component_context
        );
        ctx2.c = context2;
      }
      if (events2) {
        props2.$$events = events2;
      }
      if (hydrating) {
        assign_nodes(
          /** @type {TemplateNode} */
          anchor_node,
          null
        );
      }
      should_intro = intro;
      component2 = Component(anchor_node, props2) || {};
      should_intro = true;
      if (hydrating) {
        active_effect.nodes_end = hydrate_node;
      }
      if (context2) {
        pop();
      }
    });
    return () => {
      for (var event_name of registered_events) {
        target.removeEventListener(event_name, handle_event_propagation);
        var n = (
          /** @type {number} */
          document_listeners.get(event_name)
        );
        if (--n === 0) {
          document.removeEventListener(event_name, handle_event_propagation);
          document_listeners.delete(event_name);
        } else {
          document_listeners.set(event_name, n);
        }
      }
      root_event_handles.delete(event_handle);
      if (anchor_node !== anchor) {
        anchor_node.parentNode?.removeChild(anchor_node);
      }
    };
  });
  mounted_components.set(component2, unmount2);
  return component2;
}
var mounted_components = /* @__PURE__ */ new WeakMap();
function unmount(component2, options4) {
  const fn = mounted_components.get(component2);
  if (fn) {
    mounted_components.delete(component2);
    return fn(options4);
  }
  if (false_default) {
    lifecycle_double_unmount();
  }
  return Promise.resolve();
}

// node_modules/svelte/src/internal/client/dom/blocks/await.js
var PENDING = 0;
var THEN = 1;
var CATCH = 2;
function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
  if (hydrating) {
    hydrate_next();
  }
  var anchor = node;
  var runes = is_runes();
  var active_component_context = component_context;
  var component_function = false_default ? component_context?.function : null;
  var input = UNINITIALIZED;
  var pending_effect;
  var then_effect;
  var catch_effect;
  var input_source = (runes ? source : mutable_source)(
    /** @type {V} */
    void 0
  );
  var error_source = (runes ? source : mutable_source)(void 0);
  var resolved = false;
  function update3(state2, restore) {
    resolved = true;
    if (restore) {
      set_active_effect(effect2);
      set_active_reaction(effect2);
      set_component_context(active_component_context);
      if (false_default) set_dev_current_component_function(component_function);
    }
    try {
      if (state2 === PENDING && pending_fn) {
        if (pending_effect) resume_effect(pending_effect);
        else pending_effect = branch(() => pending_fn(anchor));
      }
      if (state2 === THEN && then_fn) {
        if (then_effect) resume_effect(then_effect);
        else then_effect = branch(() => then_fn(anchor, input_source));
      }
      if (state2 === CATCH && catch_fn) {
        if (catch_effect) resume_effect(catch_effect);
        else catch_effect = branch(() => catch_fn(anchor, error_source));
      }
      if (state2 !== PENDING && pending_effect) {
        pause_effect(pending_effect, () => pending_effect = null);
      }
      if (state2 !== THEN && then_effect) {
        pause_effect(then_effect, () => then_effect = null);
      }
      if (state2 !== CATCH && catch_effect) {
        pause_effect(catch_effect, () => catch_effect = null);
      }
    } finally {
      if (restore) {
        if (false_default) set_dev_current_component_function(null);
        set_component_context(null);
        set_active_reaction(null);
        set_active_effect(null);
        flushSync();
      }
    }
  }
  var effect2 = block(() => {
    if (input === (input = get_input())) return;
    if (is_promise(input)) {
      var promise = input;
      resolved = false;
      promise.then(
        (value) => {
          if (promise !== input) return;
          internal_set(input_source, value);
          update3(THEN, true);
        },
        (error2) => {
          if (promise !== input) return;
          internal_set(error_source, error2);
          update3(CATCH, true);
          if (!catch_fn) {
            throw error_source.v;
          }
        }
      );
      if (hydrating) {
        if (pending_fn) {
          pending_effect = branch(() => pending_fn(anchor));
        }
      } else {
        queue_micro_task(() => {
          if (!resolved) update3(PENDING, true);
        });
      }
    } else {
      internal_set(input_source, input);
      update3(THEN, false);
    }
    return () => input = UNINITIALIZED;
  });
  if (hydrating) {
    anchor = hydrate_node;
  }
}

// node_modules/svelte/src/internal/client/dom/blocks/if.js
function if_block(node, fn, [root_index, hydrate_index] = [0, 0]) {
  if (hydrating && root_index === 0) {
    hydrate_next();
  }
  var anchor = node;
  var consequent_effect = null;
  var alternate_effect = null;
  var condition = UNINITIALIZED;
  var flags2 = root_index > 0 ? EFFECT_TRANSPARENT : 0;
  var has_branch = false;
  const set_branch = (fn2, flag = true) => {
    has_branch = true;
    update_branch(flag, fn2);
  };
  const update_branch = (new_condition, fn2) => {
    if (condition === (condition = new_condition)) return;
    let mismatch = false;
    if (hydrating && hydrate_index !== -1) {
      if (root_index === 0) {
        const data = (
          /** @type {Comment} */
          anchor.data
        );
        if (data === HYDRATION_START) {
          hydrate_index = 0;
        } else if (data === HYDRATION_START_ELSE) {
          hydrate_index = Infinity;
        } else {
          hydrate_index = parseInt(data.substring(1));
          if (hydrate_index !== hydrate_index) {
            hydrate_index = condition ? Infinity : -1;
          }
        }
      }
      const is_else = hydrate_index > root_index;
      if (!!condition === is_else) {
        anchor = remove_nodes();
        set_hydrate_node(anchor);
        set_hydrating(false);
        mismatch = true;
        hydrate_index = -1;
      }
    }
    if (condition) {
      if (consequent_effect) {
        resume_effect(consequent_effect);
      } else if (fn2) {
        consequent_effect = branch(() => fn2(anchor));
      }
      if (alternate_effect) {
        pause_effect(alternate_effect, () => {
          alternate_effect = null;
        });
      }
    } else {
      if (alternate_effect) {
        resume_effect(alternate_effect);
      } else if (fn2) {
        alternate_effect = branch(() => fn2(anchor, [root_index + 1, hydrate_index]));
      }
      if (consequent_effect) {
        pause_effect(consequent_effect, () => {
          consequent_effect = null;
        });
      }
    }
    if (mismatch) {
      set_hydrating(true);
    }
  };
  block(() => {
    has_branch = false;
    fn(set_branch);
    if (!has_branch) {
      update_branch(null, null);
    }
  }, flags2);
  if (hydrating) {
    anchor = hydrate_node;
  }
}

// node_modules/svelte/src/internal/client/dom/blocks/each.js
var current_each_item = null;
function index(_2, i2) {
  return i2;
}
function pause_effects(state2, items, controlled_anchor, items_map) {
  var transitions = [];
  var length = items.length;
  for (var i2 = 0; i2 < length; i2++) {
    pause_children(items[i2].e, transitions, true);
  }
  var is_controlled = length > 0 && transitions.length === 0 && controlled_anchor !== null;
  if (is_controlled) {
    var parent_node = (
      /** @type {Element} */
      /** @type {Element} */
      controlled_anchor.parentNode
    );
    clear_text_content(parent_node);
    parent_node.append(
      /** @type {Element} */
      controlled_anchor
    );
    items_map.clear();
    link(state2, items[0].prev, items[length - 1].next);
  }
  run_out_transitions(transitions, () => {
    for (var i3 = 0; i3 < length; i3++) {
      var item = items[i3];
      if (!is_controlled) {
        items_map.delete(item.k);
        link(state2, item.prev, item.next);
      }
      destroy_effect(item.e, !is_controlled);
    }
  });
}
function each(node, flags2, get_collection, get_key, render_fn, fallback_fn = null) {
  var anchor = node;
  var state2 = { flags: flags2, items: /* @__PURE__ */ new Map(), first: null };
  var is_controlled = (flags2 & EACH_IS_CONTROLLED) !== 0;
  if (is_controlled) {
    var parent_node = (
      /** @type {Element} */
      node
    );
    anchor = hydrating ? set_hydrate_node(
      /** @type {Comment | Text} */
      get_first_child(parent_node)
    ) : parent_node.appendChild(create_text());
  }
  if (hydrating) {
    hydrate_next();
  }
  var fallback2 = null;
  var was_empty = false;
  var each_array = derived_safe_equal(() => {
    var collection = get_collection();
    return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
  });
  block(() => {
    var array3 = get(each_array);
    var length = array3.length;
    if (was_empty && length === 0) {
      return;
    }
    was_empty = length === 0;
    let mismatch = false;
    if (hydrating) {
      var is_else = (
        /** @type {Comment} */
        anchor.data === HYDRATION_START_ELSE
      );
      if (is_else !== (length === 0)) {
        anchor = remove_nodes();
        set_hydrate_node(anchor);
        set_hydrating(false);
        mismatch = true;
      }
    }
    if (hydrating) {
      var prev = null;
      var item;
      for (var i2 = 0; i2 < length; i2++) {
        if (hydrate_node.nodeType === 8 && /** @type {Comment} */
        hydrate_node.data === HYDRATION_END) {
          anchor = /** @type {Comment} */
          hydrate_node;
          mismatch = true;
          set_hydrating(false);
          break;
        }
        var value = array3[i2];
        var key2 = get_key(value, i2);
        item = create_item(
          hydrate_node,
          state2,
          prev,
          null,
          value,
          key2,
          i2,
          render_fn,
          flags2,
          get_collection
        );
        state2.items.set(key2, item);
        prev = item;
      }
      if (length > 0) {
        set_hydrate_node(remove_nodes());
      }
    }
    if (!hydrating) {
      reconcile(array3, state2, anchor, render_fn, flags2, get_key, get_collection);
    }
    if (fallback_fn !== null) {
      if (length === 0) {
        if (fallback2) {
          resume_effect(fallback2);
        } else {
          fallback2 = branch(() => fallback_fn(anchor));
        }
      } else if (fallback2 !== null) {
        pause_effect(fallback2, () => {
          fallback2 = null;
        });
      }
    }
    if (mismatch) {
      set_hydrating(true);
    }
    get(each_array);
  });
  if (hydrating) {
    anchor = hydrate_node;
  }
}
function reconcile(array3, state2, anchor, render_fn, flags2, get_key, get_collection) {
  var is_animated = (flags2 & EACH_IS_ANIMATED) !== 0;
  var should_update = (flags2 & (EACH_ITEM_REACTIVE | EACH_INDEX_REACTIVE)) !== 0;
  var length = array3.length;
  var items = state2.items;
  var first = state2.first;
  var current = first;
  var seen;
  var prev = null;
  var to_animate;
  var matched = [];
  var stashed = [];
  var value;
  var key2;
  var item;
  var i2;
  if (is_animated) {
    for (i2 = 0; i2 < length; i2 += 1) {
      value = array3[i2];
      key2 = get_key(value, i2);
      item = items.get(key2);
      if (item !== void 0) {
        item.a?.measure();
        (to_animate ??= /* @__PURE__ */ new Set()).add(item);
      }
    }
  }
  for (i2 = 0; i2 < length; i2 += 1) {
    value = array3[i2];
    key2 = get_key(value, i2);
    item = items.get(key2);
    if (item === void 0) {
      var child_anchor = current ? (
        /** @type {TemplateNode} */
        current.e.nodes_start
      ) : anchor;
      prev = create_item(
        child_anchor,
        state2,
        prev,
        prev === null ? state2.first : prev.next,
        value,
        key2,
        i2,
        render_fn,
        flags2,
        get_collection
      );
      items.set(key2, prev);
      matched = [];
      stashed = [];
      current = prev.next;
      continue;
    }
    if (should_update) {
      update_item(item, value, i2, flags2);
    }
    if ((item.e.f & INERT) !== 0) {
      resume_effect(item.e);
      if (is_animated) {
        item.a?.unfix();
        (to_animate ??= /* @__PURE__ */ new Set()).delete(item);
      }
    }
    if (item !== current) {
      if (seen !== void 0 && seen.has(item)) {
        if (matched.length < stashed.length) {
          var start2 = stashed[0];
          var j;
          prev = start2.prev;
          var a = matched[0];
          var b = matched[matched.length - 1];
          for (j = 0; j < matched.length; j += 1) {
            move(matched[j], start2, anchor);
          }
          for (j = 0; j < stashed.length; j += 1) {
            seen.delete(stashed[j]);
          }
          link(state2, a.prev, b.next);
          link(state2, prev, a);
          link(state2, b, start2);
          current = start2;
          prev = b;
          i2 -= 1;
          matched = [];
          stashed = [];
        } else {
          seen.delete(item);
          move(item, current, anchor);
          link(state2, item.prev, item.next);
          link(state2, item, prev === null ? state2.first : prev.next);
          link(state2, prev, item);
          prev = item;
        }
        continue;
      }
      matched = [];
      stashed = [];
      while (current !== null && current.k !== key2) {
        if ((current.e.f & INERT) === 0) {
          (seen ??= /* @__PURE__ */ new Set()).add(current);
        }
        stashed.push(current);
        current = current.next;
      }
      if (current === null) {
        continue;
      }
      item = current;
    }
    matched.push(item);
    prev = item;
    current = item.next;
  }
  if (current !== null || seen !== void 0) {
    var to_destroy = seen === void 0 ? [] : array_from(seen);
    while (current !== null) {
      if ((current.e.f & INERT) === 0) {
        to_destroy.push(current);
      }
      current = current.next;
    }
    var destroy_length = to_destroy.length;
    if (destroy_length > 0) {
      var controlled_anchor = (flags2 & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;
      if (is_animated) {
        for (i2 = 0; i2 < destroy_length; i2 += 1) {
          to_destroy[i2].a?.measure();
        }
        for (i2 = 0; i2 < destroy_length; i2 += 1) {
          to_destroy[i2].a?.fix();
        }
      }
      pause_effects(state2, to_destroy, controlled_anchor, items);
    }
  }
  if (is_animated) {
    queue_micro_task(() => {
      if (to_animate === void 0) return;
      for (item of to_animate) {
        item.a?.apply();
      }
    });
  }
  active_effect.first = state2.first && state2.first.e;
  active_effect.last = prev && prev.e;
}
function update_item(item, value, index3, type) {
  if ((type & EACH_ITEM_REACTIVE) !== 0) {
    internal_set(item.v, value);
  }
  if ((type & EACH_INDEX_REACTIVE) !== 0) {
    internal_set(
      /** @type {Value<number>} */
      item.i,
      index3
    );
  } else {
    item.i = index3;
  }
}
function create_item(anchor, state2, prev, next2, value, key2, index3, render_fn, flags2, get_collection) {
  var previous_each_item = current_each_item;
  var reactive = (flags2 & EACH_ITEM_REACTIVE) !== 0;
  var mutable = (flags2 & EACH_ITEM_IMMUTABLE) === 0;
  var v = reactive ? mutable ? mutable_source(value) : source(value) : value;
  var i2 = (flags2 & EACH_INDEX_REACTIVE) === 0 ? index3 : source(index3);
  if (false_default && reactive) {
    v.debug = () => {
      var collection_index = typeof i2 === "number" ? index3 : i2.v;
      get_collection()[collection_index];
    };
  }
  var item = {
    i: i2,
    v,
    k: key2,
    a: null,
    // @ts-expect-error
    e: null,
    prev,
    next: next2
  };
  current_each_item = item;
  try {
    item.e = branch(() => render_fn(anchor, v, i2, get_collection), hydrating);
    item.e.prev = prev && prev.e;
    item.e.next = next2 && next2.e;
    if (prev === null) {
      state2.first = item;
    } else {
      prev.next = item;
      prev.e.next = item.e;
    }
    if (next2 !== null) {
      next2.prev = item;
      next2.e.prev = item.e;
    }
    return item;
  } finally {
    current_each_item = previous_each_item;
  }
}
function move(item, next2, anchor) {
  var end = item.next ? (
    /** @type {TemplateNode} */
    item.next.e.nodes_start
  ) : anchor;
  var dest = next2 ? (
    /** @type {TemplateNode} */
    next2.e.nodes_start
  ) : anchor;
  var node = (
    /** @type {TemplateNode} */
    item.e.nodes_start
  );
  while (node !== end) {
    var next_node = (
      /** @type {TemplateNode} */
      get_next_sibling(node)
    );
    dest.before(node);
    node = next_node;
  }
}
function link(state2, prev, next2) {
  if (prev === null) {
    state2.first = next2;
  } else {
    prev.next = next2;
    prev.e.next = next2 && next2.e;
  }
  if (next2 !== null) {
    next2.prev = prev;
    next2.e.prev = prev && prev.e;
  }
}

// node_modules/svelte/src/internal/client/dom/blocks/html.js
function check_hash(element2, server_hash, value) {
  if (!server_hash || server_hash === hash(String(value ?? ""))) return;
  let location;
  const loc = element2.__svelte_meta?.loc;
  if (loc) {
    location = `near ${loc.file}:${loc.line}:${loc.column}`;
  } else if (dev_current_component_function?.[FILENAME]) {
    location = `in ${dev_current_component_function[FILENAME]}`;
  }
  hydration_html_changed(sanitize_location(location));
}
function html(node, get_value, svg2, mathml, skip_warning) {
  var anchor = node;
  var value = "";
  var effect2;
  block(() => {
    if (value === (value = get_value() ?? "")) {
      if (hydrating) {
        hydrate_next();
      }
      return;
    }
    if (effect2 !== void 0) {
      destroy_effect(effect2);
      effect2 = void 0;
    }
    if (value === "") return;
    effect2 = branch(() => {
      if (hydrating) {
        var hash3 = (
          /** @type {Comment} */
          hydrate_node.data
        );
        var next2 = hydrate_next();
        var last = next2;
        while (next2 !== null && (next2.nodeType !== 8 || /** @type {Comment} */
        next2.data !== "")) {
          last = next2;
          next2 = /** @type {TemplateNode} */
          get_next_sibling(next2);
        }
        if (next2 === null) {
          hydration_mismatch();
          throw HYDRATION_ERROR;
        }
        if (false_default && !skip_warning) {
          check_hash(
            /** @type {Element} */
            next2.parentNode,
            hash3,
            value
          );
        }
        assign_nodes(hydrate_node, last);
        anchor = set_hydrate_node(next2);
        return;
      }
      var html2 = value + "";
      if (svg2) html2 = `<svg>${html2}</svg>`;
      else if (mathml) html2 = `<math>${html2}</math>`;
      var node2 = create_fragment_from_html(html2);
      if (svg2 || mathml) {
        node2 = /** @type {Element} */
        get_first_child(node2);
      }
      assign_nodes(
        /** @type {TemplateNode} */
        get_first_child(node2),
        /** @type {TemplateNode} */
        node2.lastChild
      );
      if (svg2 || mathml) {
        while (get_first_child(node2)) {
          anchor.before(
            /** @type {Node} */
            get_first_child(node2)
          );
        }
      } else {
        anchor.before(node2);
      }
    });
  });
}

// node_modules/svelte/src/internal/client/dom/blocks/snippet.js
function snippet(node, get_snippet, ...args2) {
  var anchor = node;
  var snippet3 = noop;
  var snippet_effect;
  block(() => {
    if (snippet3 === (snippet3 = get_snippet())) return;
    if (snippet_effect) {
      destroy_effect(snippet_effect);
      snippet_effect = null;
    }
    if (false_default && snippet3 == null) {
      invalid_snippet();
    }
    snippet_effect = branch(() => (
      /** @type {SnippetFn} */
      snippet3(anchor, ...args2)
    ));
  }, EFFECT_TRANSPARENT);
  if (hydrating) {
    anchor = hydrate_node;
  }
}

// node_modules/svelte/src/internal/client/dom/elements/actions.js
function action(dom, action2, get_value) {
  effect(() => {
    var payload = untrack(() => action2(dom, get_value?.()) || {});
    if (get_value && payload?.update) {
      var inited = false;
      var prev = (
        /** @type {any} */
        {}
      );
      render_effect(() => {
        var value = get_value();
        deep_read_state(value);
        if (inited && safe_not_equal(prev, value)) {
          prev = value;
          payload.update(value);
        }
      });
      inited = true;
    }
    if (payload?.destroy) {
      return () => (
        /** @type {Function} */
        payload.destroy()
      );
    }
  });
}

// node_modules/clsx/dist/clsx.mjs
function r(e) {
  var t4, 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 (t4 = 0; t4 < o; t4++) e[t4] && (f = r(e[t4])) && (n && (n += " "), n += f);
  } else for (f in e) e[f] && (n && (n += " "), n += f);
  return n;
}
function clsx() {
  for (var e, t4, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t4 = r(e)) && (n && (n += " "), n += t4);
  return n;
}

// node_modules/svelte/src/internal/shared/attributes.js
function clsx2(value) {
  if (typeof value === "object") {
    return clsx(value);
  } else {
    return value ?? "";
  }
}
var whitespace = [..." 	\n\r\f\xA0\v\uFEFF"];
function to_class(value, hash3, directives) {
  var classname = value == null ? "" : "" + value;
  if (hash3) {
    classname = classname ? classname + " " + hash3 : hash3;
  }
  if (directives) {
    for (var key2 in directives) {
      if (directives[key2]) {
        classname = classname ? classname + " " + key2 : key2;
      } else if (classname.length) {
        var len = key2.length;
        var a = 0;
        while ((a = classname.indexOf(key2, a)) >= 0) {
          var b = a + len;
          if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) {
            classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1);
          } else {
            a = b;
          }
        }
      }
    }
  }
  return classname === "" ? null : classname;
}
function append_styles(styles, important = false) {
  var separator = important ? " !important;" : ";";
  var css = "";
  for (var key2 in styles) {
    var value = styles[key2];
    if (value != null && value !== "") {
      css += " " + key2 + ": " + value + separator;
    }
  }
  return css;
}
function to_css_name(name3) {
  if (name3[0] !== "-" || name3[1] !== "-") {
    return name3.toLowerCase();
  }
  return name3;
}
function to_style(value, styles) {
  if (styles) {
    var new_style = "";
    var normal_styles;
    var important_styles;
    if (Array.isArray(styles)) {
      normal_styles = styles[0];
      important_styles = styles[1];
    } else {
      normal_styles = styles;
    }
    if (value) {
      value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim();
      var in_str = false;
      var in_apo = 0;
      var in_comment = false;
      var reserved_names = [];
      if (normal_styles) {
        reserved_names.push(...Object.keys(normal_styles).map(to_css_name));
      }
      if (important_styles) {
        reserved_names.push(...Object.keys(important_styles).map(to_css_name));
      }
      var start_index = 0;
      var name_index = -1;
      const len = value.length;
      for (var i2 = 0; i2 < len; i2++) {
        var c = value[i2];
        if (in_comment) {
          if (c === "/" && value[i2 - 1] === "*") {
            in_comment = false;
          }
        } else if (in_str) {
          if (in_str === c) {
            in_str = false;
          }
        } else if (c === "/" && value[i2 + 1] === "*") {
          in_comment = true;
        } else if (c === '"' || c === "'") {
          in_str = c;
        } else if (c === "(") {
          in_apo++;
        } else if (c === ")") {
          in_apo--;
        }
        if (!in_comment && in_str === false && in_apo === 0) {
          if (c === ":" && name_index === -1) {
            name_index = i2;
          } else if (c === ";" || i2 === len - 1) {
            if (name_index !== -1) {
              var name3 = to_css_name(value.substring(start_index, name_index).trim());
              if (!reserved_names.includes(name3)) {
                if (c !== ";") {
                  i2++;
                }
                var property = value.substring(start_index, i2).trim();
                new_style += " " + property + ";";
              }
            }
            start_index = i2 + 1;
            name_index = -1;
          }
        }
      }
    }
    if (normal_styles) {
      new_style += append_styles(normal_styles);
    }
    if (important_styles) {
      new_style += append_styles(important_styles, true);
    }
    new_style = new_style.trim();
    return new_style === "" ? null : new_style;
  }
  return value == null ? null : String(value);
}

// node_modules/svelte/src/internal/client/dom/elements/class.js
function set_class(dom, is_html, value, hash3, prev_classes, next_classes) {
  var prev = dom.__className;
  if (hydrating || prev !== value) {
    var next_class_name = to_class(value, hash3, next_classes);
    if (!hydrating || next_class_name !== dom.getAttribute("class")) {
      if (next_class_name == null) {
        dom.removeAttribute("class");
      } else if (is_html) {
        dom.className = next_class_name;
      } else {
        dom.setAttribute("class", next_class_name);
      }
    }
    dom.__className = value;
  } else if (next_classes && prev_classes !== next_classes) {
    for (var key2 in next_classes) {
      var is_present = !!next_classes[key2];
      if (prev_classes == null || is_present !== !!prev_classes[key2]) {
        dom.classList.toggle(key2, is_present);
      }
    }
  }
  return next_classes;
}

// node_modules/svelte/src/internal/client/dom/elements/style.js
function update_styles(dom, prev = {}, next2, priority) {
  for (var key2 in next2) {
    var value = next2[key2];
    if (prev[key2] !== value) {
      if (next2[key2] == null) {
        dom.style.removeProperty(key2);
      } else {
        dom.style.setProperty(key2, value, priority);
      }
    }
  }
}
function set_style(dom, value, prev_styles, next_styles) {
  var prev = dom.__style;
  if (hydrating || prev !== value) {
    var next_style_attr = to_style(value, next_styles);
    if (!hydrating || next_style_attr !== dom.getAttribute("style")) {
      if (next_style_attr == null) {
        dom.removeAttribute("style");
      } else {
        dom.style.cssText = next_style_attr;
      }
    }
    dom.__style = value;
  } else if (next_styles) {
    if (Array.isArray(next_styles)) {
      update_styles(dom, prev_styles?.[0], next_styles[0]);
      update_styles(dom, prev_styles?.[1], next_styles[1], "important");
    } else {
      update_styles(dom, prev_styles, next_styles);
    }
  }
  return next_styles;
}

// node_modules/svelte/src/internal/client/dom/elements/attributes.js
var CLASS = Symbol("class");
var STYLE = Symbol("style");
var IS_CUSTOM_ELEMENT = Symbol("is custom element");
var IS_HTML = Symbol("is html");
function remove_input_defaults(input) {
  if (!hydrating) return;
  var already_removed = false;
  var remove_defaults = () => {
    if (already_removed) return;
    already_removed = true;
    if (input.hasAttribute("value")) {
      var value = input.value;
      set_attribute(input, "value", null);
      input.value = value;
    }
    if (input.hasAttribute("checked")) {
      var checked = input.checked;
      set_attribute(input, "checked", null);
      input.checked = checked;
    }
  };
  input.__on_r = remove_defaults;
  queue_idle_task(remove_defaults);
  add_form_reset_listener();
}
function set_value(element2, value) {
  var attributes = get_attributes(element2);
  if (attributes.value === (attributes.value = // treat null and undefined the same for the initial value
  value ?? void 0) || // @ts-expect-error
  // `progress` elements always need their value set when it's `0`
  element2.value === value && (value !== 0 || element2.nodeName !== "PROGRESS")) {
    return;
  }
  element2.value = value ?? "";
}
function set_checked(element2, checked) {
  var attributes = get_attributes(element2);
  if (attributes.checked === (attributes.checked = // treat null and undefined the same for the initial value
  checked ?? void 0)) {
    return;
  }
  element2.checked = checked;
}
function set_attribute(element2, attribute, value, skip_warning) {
  var attributes = get_attributes(element2);
  if (hydrating) {
    attributes[attribute] = element2.getAttribute(attribute);
    if (attribute === "src" || attribute === "srcset" || attribute === "href" && element2.nodeName === "LINK") {
      if (!skip_warning) {
        check_src_in_dev_hydration(element2, attribute, value ?? "");
      }
      return;
    }
  }
  if (attributes[attribute] === (attributes[attribute] = value)) return;
  if (attribute === "loading") {
    element2[LOADING_ATTR_SYMBOL] = value;
  }
  if (value == null) {
    element2.removeAttribute(attribute);
  } else if (typeof value !== "string" && get_setters(element2).includes(attribute)) {
    element2[attribute] = value;
  } else {
    element2.setAttribute(attribute, value);
  }
}
function set_custom_element_data(node, prop2, value) {
  var previous_reaction = active_reaction;
  var previous_effect = active_effect;
  let was_hydrating = hydrating;
  if (hydrating) {
    set_hydrating(false);
  }
  set_active_reaction(null);
  set_active_effect(null);
  try {
    if (
      // `style` should use `set_attribute` rather than the setter
      prop2 !== "style" && // Don't compute setters for custom elements while they aren't registered yet,
      // because during their upgrade/instantiation they might add more setters.
      // Instead, fall back to a simple "an object, then set as property" heuristic.
      (setters_cache.has(node.nodeName) || // customElements may not be available in browser extension contexts
      !customElements || customElements.get(node.tagName.toLowerCase()) ? get_setters(node).includes(prop2) : value && typeof value === "object")
    ) {
      node[prop2] = value;
    } else {
      set_attribute(node, prop2, value == null ? value : String(value));
    }
  } finally {
    set_active_reaction(previous_reaction);
    set_active_effect(previous_effect);
    if (was_hydrating) {
      set_hydrating(true);
    }
  }
}
function get_attributes(element2) {
  return (
    /** @type {Record<string | symbol, unknown>} **/
    // @ts-expect-error
    element2.__attributes ??= {
      [IS_CUSTOM_ELEMENT]: element2.nodeName.includes("-"),
      [IS_HTML]: element2.namespaceURI === NAMESPACE_HTML
    }
  );
}
var setters_cache = /* @__PURE__ */ new Map();
function get_setters(element2) {
  var setters = setters_cache.get(element2.nodeName);
  if (setters) return setters;
  setters_cache.set(element2.nodeName, setters = []);
  var descriptors;
  var proto = element2;
  var element_proto = Element.prototype;
  while (element_proto !== proto) {
    descriptors = get_descriptors(proto);
    for (var key2 in descriptors) {
      if (descriptors[key2].set) {
        setters.push(key2);
      }
    }
    proto = get_prototype_of(proto);
  }
  return setters;
}
function check_src_in_dev_hydration(element2, attribute, value) {
  if (!false_default) return;
  if (attribute === "srcset" && srcset_url_equal(element2, value)) return;
  if (src_url_equal(element2.getAttribute(attribute) ?? "", value)) return;
  hydration_attribute_changed(
    attribute,
    element2.outerHTML.replace(element2.innerHTML, element2.innerHTML && "..."),
    String(value)
  );
}
function src_url_equal(element_src, url) {
  if (element_src === url) return true;
  return new URL(element_src, document.baseURI).href === new URL(url, document.baseURI).href;
}
function split_srcset(srcset) {
  return srcset.split(",").map((src) => src.trim().split(" ").filter(Boolean));
}
function srcset_url_equal(element2, srcset) {
  var element_urls = split_srcset(element2.srcset);
  var urls = split_srcset(srcset);
  return urls.length === element_urls.length && urls.every(
    ([url, width], i2) => width === element_urls[i2][1] && // We need to test both ways because Vite will create an a full URL with
    // `new URL(asset, import.meta.url).href` for the client when `base: './'`, and the
    // relative URLs inside srcset are not automatically resolved to absolute URLs by
    // browsers (in contrast to img.src). This means both SSR and DOM code could
    // contain relative or absolute URLs.
    (src_url_equal(element_urls[i2][0], url) || src_url_equal(url, element_urls[i2][0]))
  );
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/input.js
function bind_value(input, get4, set4 = get4) {
  var runes = is_runes();
  listen_to_event_and_reset_event(input, "input", (is_reset) => {
    if (false_default && input.type === "checkbox") {
      bind_invalid_checkbox_value();
    }
    var value = is_reset ? input.defaultValue : input.value;
    value = is_numberlike_input(input) ? to_number(value) : value;
    set4(value);
    if (runes && value !== (value = get4())) {
      var start2 = input.selectionStart;
      var end = input.selectionEnd;
      input.value = value ?? "";
      if (end !== null) {
        input.selectionStart = start2;
        input.selectionEnd = Math.min(end, input.value.length);
      }
    }
  });
  if (
    // If we are hydrating and the value has since changed,
    // then use the updated value from the input instead.
    hydrating && input.defaultValue !== input.value || // If defaultValue is set, then value == defaultValue
    // TODO Svelte 6: remove input.value check and set to empty string?
    untrack(get4) == null && input.value
  ) {
    set4(is_numberlike_input(input) ? to_number(input.value) : input.value);
  }
  render_effect(() => {
    if (false_default && input.type === "checkbox") {
      bind_invalid_checkbox_value();
    }
    var value = get4();
    if (is_numberlike_input(input) && value === to_number(input.value)) {
      return;
    }
    if (input.type === "date" && !value && !input.value) {
      return;
    }
    if (value !== input.value) {
      input.value = value ?? "";
    }
  });
}
var pending = /* @__PURE__ */ new Set();
function bind_group(inputs, group_index, input, get4, set4 = get4) {
  var is_checkbox = input.getAttribute("type") === "checkbox";
  var binding_group = inputs;
  let hydration_mismatch2 = false;
  if (group_index !== null) {
    for (var index3 of group_index) {
      binding_group = binding_group[index3] ??= [];
    }
  }
  binding_group.push(input);
  listen_to_event_and_reset_event(
    input,
    "change",
    () => {
      var value = input.__value;
      if (is_checkbox) {
        value = get_binding_group_value(binding_group, value, input.checked);
      }
      set4(value);
    },
    // TODO better default value handling
    () => set4(is_checkbox ? [] : null)
  );
  render_effect(() => {
    var value = get4();
    if (hydrating && input.defaultChecked !== input.checked) {
      hydration_mismatch2 = true;
      return;
    }
    if (is_checkbox) {
      value = value || [];
      input.checked = value.includes(input.__value);
    } else {
      input.checked = is(input.__value, value);
    }
  });
  teardown(() => {
    var index4 = binding_group.indexOf(input);
    if (index4 !== -1) {
      binding_group.splice(index4, 1);
    }
  });
  if (!pending.has(binding_group)) {
    pending.add(binding_group);
    queue_micro_task(() => {
      binding_group.sort((a, b) => a.compareDocumentPosition(b) === 4 ? -1 : 1);
      pending.delete(binding_group);
    });
  }
  queue_micro_task(() => {
    if (hydration_mismatch2) {
      var value;
      if (is_checkbox) {
        value = get_binding_group_value(binding_group, value, input.checked);
      } else {
        var hydration_input = binding_group.find((input2) => input2.checked);
        value = hydration_input?.__value;
      }
      set4(value);
    }
  });
}
function bind_checked(input, get4, set4 = get4) {
  listen_to_event_and_reset_event(input, "change", (is_reset) => {
    var value = is_reset ? input.defaultChecked : input.checked;
    set4(value);
  });
  if (
    // If we are hydrating and the value has since changed,
    // then use the update value from the input instead.
    hydrating && input.defaultChecked !== input.checked || // If defaultChecked is set, then checked == defaultChecked
    untrack(get4) == null
  ) {
    set4(input.checked);
  }
  render_effect(() => {
    var value = get4();
    input.checked = Boolean(value);
  });
}
function get_binding_group_value(group2, __value, checked) {
  var value = /* @__PURE__ */ new Set();
  for (var i2 = 0; i2 < group2.length; i2 += 1) {
    if (group2[i2].checked) {
      value.add(group2[i2].__value);
    }
  }
  if (!checked) {
    value.delete(__value);
  }
  return Array.from(value);
}
function is_numberlike_input(input) {
  var type = input.type;
  return type === "number" || type === "range";
}
function to_number(value) {
  return value === "" ? null : +value;
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/select.js
function select_option(select, value, mounting) {
  if (select.multiple) {
    return select_options(select, value);
  }
  for (var option of select.options) {
    var option_value = get_option_value(option);
    if (is(option_value, value)) {
      option.selected = true;
      return;
    }
  }
  if (!mounting || value !== void 0) {
    select.selectedIndex = -1;
  }
}
function init_select(select, get_value) {
  let mounting = true;
  effect(() => {
    if (get_value) {
      select_option(select, untrack(get_value), mounting);
    }
    mounting = false;
    var observer = new MutationObserver(() => {
      var value = select.__value;
      select_option(select, value);
    });
    observer.observe(select, {
      // Listen to option element changes
      childList: true,
      subtree: true,
      // because of <optgroup>
      // Listen to option element value attribute changes
      // (doesn't get notified of select value changes,
      // because that property is not reflected as an attribute)
      attributes: true,
      attributeFilter: ["value"]
    });
    return () => {
      observer.disconnect();
    };
  });
}
function bind_select_value(select, get4, set4 = get4) {
  var mounting = true;
  listen_to_event_and_reset_event(select, "change", (is_reset) => {
    var query2 = is_reset ? "[selected]" : ":checked";
    var value;
    if (select.multiple) {
      value = [].map.call(select.querySelectorAll(query2), get_option_value);
    } else {
      var selected_option = select.querySelector(query2) ?? // will fall back to first non-disabled option if no option is selected
      select.querySelector("option:not([disabled])");
      value = selected_option && get_option_value(selected_option);
    }
    set4(value);
  });
  effect(() => {
    var value = get4();
    select_option(select, value, mounting);
    if (mounting && value === void 0) {
      var selected_option = select.querySelector(":checked");
      if (selected_option !== null) {
        value = get_option_value(selected_option);
        set4(value);
      }
    }
    select.__value = value;
    mounting = false;
  });
  init_select(select);
}
function select_options(select, value) {
  for (var option of select.options) {
    option.selected = ~value.indexOf(get_option_value(option));
  }
}
function get_option_value(option) {
  if ("__value" in option) {
    return option.__value;
  } else {
    return option.value;
  }
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/size.js
var ResizeObserverSingleton = class _ResizeObserverSingleton {
  /** */
  #listeners = /* @__PURE__ */ new WeakMap();
  /** @type {ResizeObserver | undefined} */
  #observer;
  /** @type {ResizeObserverOptions} */
  #options;
  /** @static */
  static entries = /* @__PURE__ */ new WeakMap();
  /** @param {ResizeObserverOptions} options */
  constructor(options4) {
    this.#options = options4;
  }
  /**
   * @param {Element} element
   * @param {(entry: ResizeObserverEntry) => any} listener
   */
  observe(element2, listener) {
    var listeners = this.#listeners.get(element2) || /* @__PURE__ */ new Set();
    listeners.add(listener);
    this.#listeners.set(element2, listeners);
    this.#getObserver().observe(element2, this.#options);
    return () => {
      var listeners2 = this.#listeners.get(element2);
      listeners2.delete(listener);
      if (listeners2.size === 0) {
        this.#listeners.delete(element2);
        this.#observer.unobserve(element2);
      }
    };
  }
  #getObserver() {
    return this.#observer ?? (this.#observer = new ResizeObserver(
      /** @param {any} entries */
      (entries) => {
        for (var entry of entries) {
          _ResizeObserverSingleton.entries.set(entry.target, entry);
          for (var listener of this.#listeners.get(entry.target) || []) {
            listener(entry);
          }
        }
      }
    ));
  }
};
var resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({
  box: "border-box"
});
function bind_element_size(element2, type, set4) {
  var unsub = resize_observer_border_box.observe(element2, () => set4(element2[type]));
  effect(() => {
    untrack(() => set4(element2[type]));
    return unsub;
  });
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/this.js
function is_bound_this(bound_value, element_or_component) {
  return bound_value === element_or_component || bound_value?.[STATE_SYMBOL] === element_or_component;
}
function bind_this(element_or_component = {}, update3, get_value, get_parts) {
  effect(() => {
    var old_parts;
    var parts2;
    render_effect(() => {
      old_parts = parts2;
      parts2 = get_parts?.() || [];
      untrack(() => {
        if (element_or_component !== get_value(...parts2)) {
          update3(element_or_component, ...parts2);
          if (old_parts && is_bound_this(get_value(...old_parts), element_or_component)) {
            update3(null, ...old_parts);
          }
        }
      });
    });
    return () => {
      queue_micro_task(() => {
        if (parts2 && is_bound_this(get_value(...parts2), element_or_component)) {
          update3(null, ...parts2);
        }
      });
    };
  });
  return element_or_component;
}

// node_modules/svelte/src/internal/client/dom/elements/bindings/universal.js
function bind_property(property, event_name, element2, set4, get4) {
  var handler = () => {
    set4(element2[property]);
  };
  element2.addEventListener(event_name, handler);
  if (get4) {
    render_effect(() => {
      element2[property] = get4();
    });
  } else {
    handler();
  }
  if (element2 === document.body || element2 === window || element2 === document) {
    teardown(() => {
      element2.removeEventListener(event_name, handler);
    });
  }
}

// node_modules/svelte/src/internal/client/dom/legacy/lifecycle.js
function init2(immutable = false) {
  const context2 = (
    /** @type {ComponentContextLegacy} */
    component_context
  );
  const callbacks = context2.l.u;
  if (!callbacks) return;
  let props2 = () => deep_read_state(context2.s);
  if (immutable) {
    let version = 0;
    let prev = (
      /** @type {Record<string, any>} */
      {}
    );
    const d = derived(() => {
      let changed = false;
      const props3 = context2.s;
      for (const key2 in props3) {
        if (props3[key2] !== prev[key2]) {
          prev[key2] = props3[key2];
          changed = true;
        }
      }
      if (changed) version++;
      return version;
    });
    props2 = () => get(d);
  }
  if (callbacks.b.length) {
    user_pre_effect(() => {
      observe_all(context2, props2);
      run_all(callbacks.b);
    });
  }
  user_effect(() => {
    const fns = untrack(() => callbacks.m.map(run2));
    return () => {
      for (const fn of fns) {
        if (typeof fn === "function") {
          fn();
        }
      }
    };
  });
  if (callbacks.a.length) {
    user_effect(() => {
      observe_all(context2, props2);
      run_all(callbacks.a);
    });
  }
}
function observe_all(context2, props2) {
  if (context2.l.s) {
    for (const signal of context2.l.s) get(signal);
  }
  props2();
}

// node_modules/svelte/src/internal/client/reactivity/store.js
var is_store_binding = false;
var IS_UNMOUNTED = Symbol();
function store_get(store, store_name, stores) {
  const entry = stores[store_name] ??= {
    store: null,
    source: mutable_source(void 0),
    unsubscribe: noop
  };
  if (entry.store !== store && !(IS_UNMOUNTED in stores)) {
    entry.unsubscribe();
    entry.store = store ?? null;
    if (store == null) {
      entry.source.v = void 0;
      entry.unsubscribe = noop;
    } else {
      var is_synchronous_callback = true;
      entry.unsubscribe = subscribe_to_store(store, (v) => {
        if (is_synchronous_callback) {
          entry.source.v = v;
        } else {
          set(entry.source, v);
        }
      });
      is_synchronous_callback = false;
    }
  }
  if (store && IS_UNMOUNTED in stores) {
    return get2(store);
  }
  return get(entry.source);
}
function store_set(store, value) {
  store.set(value);
  return value;
}
function invalidate_store(stores, store_name) {
  var entry = stores[store_name];
  if (entry.store !== null) {
    store_set(entry.store, entry.source.v);
  }
}
function setup_stores() {
  const stores = {};
  function cleanup() {
    teardown(() => {
      for (var store_name in stores) {
        const ref = stores[store_name];
        ref.unsubscribe();
      }
      define_property(stores, IS_UNMOUNTED, {
        enumerable: false,
        value: true
      });
    });
  }
  return [stores, cleanup];
}
function mark_store_binding() {
  is_store_binding = true;
}
function capture_store_binding(fn) {
  var previous_is_store_binding = is_store_binding;
  try {
    is_store_binding = false;
    return [fn(), is_store_binding];
  } finally {
    is_store_binding = previous_is_store_binding;
  }
}

// node_modules/svelte/src/internal/client/reactivity/props.js
function has_destroyed_component_ctx(current_value) {
  return current_value.ctx?.d ?? false;
}
function prop(props2, key2, flags2, fallback2) {
  var immutable = (flags2 & PROPS_IS_IMMUTABLE) !== 0;
  var runes = !legacy_mode_flag || (flags2 & PROPS_IS_RUNES) !== 0;
  var bindable = (flags2 & PROPS_IS_BINDABLE) !== 0;
  var lazy2 = (flags2 & PROPS_IS_LAZY_INITIAL) !== 0;
  var is_store_sub = false;
  var prop_value;
  if (bindable) {
    [prop_value, is_store_sub] = capture_store_binding(() => (
      /** @type {V} */
      props2[key2]
    ));
  } else {
    prop_value = /** @type {V} */
    props2[key2];
  }
  var is_entry_props = STATE_SYMBOL in props2 || LEGACY_PROPS in props2;
  var setter = bindable && (get_descriptor(props2, key2)?.set ?? (is_entry_props && key2 in props2 && ((v) => props2[key2] = v))) || void 0;
  var fallback_value = (
    /** @type {V} */
    fallback2
  );
  var fallback_dirty = true;
  var fallback_used = false;
  var get_fallback = () => {
    fallback_used = true;
    if (fallback_dirty) {
      fallback_dirty = false;
      if (lazy2) {
        fallback_value = untrack(
          /** @type {() => V} */
          fallback2
        );
      } else {
        fallback_value = /** @type {V} */
        fallback2;
      }
    }
    return fallback_value;
  };
  if (prop_value === void 0 && fallback2 !== void 0) {
    if (setter && runes) {
      props_invalid_value(key2);
    }
    prop_value = get_fallback();
    if (setter) setter(prop_value);
  }
  var getter;
  if (runes) {
    getter = () => {
      var value = (
        /** @type {V} */
        props2[key2]
      );
      if (value === void 0) return get_fallback();
      fallback_dirty = true;
      fallback_used = false;
      return value;
    };
  } else {
    var derived_getter = (immutable ? derived : derived_safe_equal)(
      () => (
        /** @type {V} */
        props2[key2]
      )
    );
    derived_getter.f |= LEGACY_DERIVED_PROP;
    getter = () => {
      var value = get(derived_getter);
      if (value !== void 0) fallback_value = /** @type {V} */
      void 0;
      return value === void 0 ? fallback_value : value;
    };
  }
  if ((flags2 & PROPS_IS_UPDATED) === 0) {
    return getter;
  }
  if (setter) {
    var legacy_parent = props2.$$legacy;
    return function(value, mutation) {
      if (arguments.length > 0) {
        if (!runes || !mutation || legacy_parent || is_store_sub) {
          setter(mutation ? getter() : value);
        }
        return value;
      } else {
        return getter();
      }
    };
  }
  var from_child = false;
  var was_from_child = false;
  var inner_current_value = mutable_source(prop_value);
  var current_value = derived(() => {
    var parent_value = getter();
    var child_value = get(inner_current_value);
    if (from_child) {
      from_child = false;
      was_from_child = true;
      return child_value;
    }
    was_from_child = false;
    return inner_current_value.v = parent_value;
  });
  if (bindable) {
    get(current_value);
  }
  if (!immutable) current_value.equals = safe_equals;
  return function(value, mutation) {
    if (captured_signals !== null) {
      from_child = was_from_child;
      getter();
      get(inner_current_value);
    }
    if (arguments.length > 0) {
      const new_value = mutation ? get(current_value) : runes && bindable ? proxy2(value) : value;
      if (!current_value.equals(new_value)) {
        from_child = true;
        set(inner_current_value, new_value);
        if (fallback_used && fallback_value !== void 0) {
          fallback_value = new_value;
        }
        if (has_destroyed_component_ctx(current_value)) {
          return value;
        }
        untrack(() => get(current_value));
      }
      return value;
    }
    if (has_destroyed_component_ctx(current_value)) {
      return current_value.v;
    }
    return get(current_value);
  };
}

// node_modules/svelte/src/legacy/legacy-client.js
function createClassComponent(options4) {
  return new Svelte4Component(options4);
}
var Svelte4Component = class {
  /** @type {any} */
  #events;
  /** @type {Record<string, any>} */
  #instance;
  /**
   * @param {ComponentConstructorOptions & {
   *  component: any;
   * }} options
   */
  constructor(options4) {
    var sources = /* @__PURE__ */ new Map();
    var add_source = (key2, value) => {
      var s = mutable_source(value);
      sources.set(key2, s);
      return s;
    };
    const props2 = new Proxy(
      { ...options4.props || {}, $$events: {} },
      {
        get(target, prop2) {
          return get(sources.get(prop2) ?? add_source(prop2, Reflect.get(target, prop2)));
        },
        has(target, prop2) {
          if (prop2 === LEGACY_PROPS) return true;
          get(sources.get(prop2) ?? add_source(prop2, Reflect.get(target, prop2)));
          return Reflect.has(target, prop2);
        },
        set(target, prop2, value) {
          set(sources.get(prop2) ?? add_source(prop2, value), value);
          return Reflect.set(target, prop2, value);
        }
      }
    );
    this.#instance = (options4.hydrate ? hydrate : mount)(options4.component, {
      target: options4.target,
      anchor: options4.anchor,
      props: props2,
      context: options4.context,
      intro: options4.intro ?? false,
      recover: options4.recover
    });
    if (!options4?.props?.$$host || options4.sync === false) {
      flushSync();
    }
    this.#events = props2.$$events;
    for (const key2 of Object.keys(this.#instance)) {
      if (key2 === "$set" || key2 === "$destroy" || key2 === "$on") continue;
      define_property(this, key2, {
        get() {
          return this.#instance[key2];
        },
        /** @param {any} value */
        set(value) {
          this.#instance[key2] = value;
        },
        enumerable: true
      });
    }
    this.#instance.$set = /** @param {Record<string, any>} next */
    (next2) => {
      Object.assign(props2, next2);
    };
    this.#instance.$destroy = () => {
      unmount(this.#instance);
    };
  }
  /** @param {Record<string, any>} props */
  $set(props2) {
    this.#instance.$set(props2);
  }
  /**
   * @param {string} event
   * @param {(...args: any[]) => any} callback
   * @returns {any}
   */
  $on(event2, callback) {
    this.#events[event2] = this.#events[event2] || [];
    const cb = (...args2) => callback.call(this, ...args2);
    this.#events[event2].push(cb);
    return () => {
      this.#events[event2] = this.#events[event2].filter(
        /** @param {any} fn */
        (fn) => fn !== cb
      );
    };
  }
  $destroy() {
    this.#instance.$destroy();
  }
};

// node_modules/svelte/src/internal/client/dom/elements/custom-element.js
var SvelteElement;
if (typeof HTMLElement === "function") {
  SvelteElement = class extends HTMLElement {
    /** The Svelte component constructor */
    $$ctor;
    /** Slots */
    $$s;
    /** @type {any} The Svelte component instance */
    $$c;
    /** Whether or not the custom element is connected */
    $$cn = false;
    /** @type {Record<string, any>} Component props data */
    $$d = {};
    /** `true` if currently in the process of reflecting component props back to attributes */
    $$r = false;
    /** @type {Record<string, CustomElementPropDefinition>} Props definition (name, reflected, type etc) */
    $$p_d = {};
    /** @type {Record<string, EventListenerOrEventListenerObject[]>} Event listeners */
    $$l = {};
    /** @type {Map<EventListenerOrEventListenerObject, Function>} Event listener unsubscribe functions */
    $$l_u = /* @__PURE__ */ new Map();
    /** @type {any} The managed render effect for reflecting attributes */
    $$me;
    /**
     * @param {*} $$componentCtor
     * @param {*} $$slots
     * @param {*} use_shadow_dom
     */
    constructor($$componentCtor, $$slots, use_shadow_dom) {
      super();
      this.$$ctor = $$componentCtor;
      this.$$s = $$slots;
      if (use_shadow_dom) {
        this.attachShadow({ mode: "open" });
      }
    }
    /**
     * @param {string} type
     * @param {EventListenerOrEventListenerObject} listener
     * @param {boolean | AddEventListenerOptions} [options]
     */
    addEventListener(type, listener, options4) {
      this.$$l[type] = this.$$l[type] || [];
      this.$$l[type].push(listener);
      if (this.$$c) {
        const unsub = this.$$c.$on(type, listener);
        this.$$l_u.set(listener, unsub);
      }
      super.addEventListener(type, listener, options4);
    }
    /**
     * @param {string} type
     * @param {EventListenerOrEventListenerObject} listener
     * @param {boolean | AddEventListenerOptions} [options]
     */
    removeEventListener(type, listener, options4) {
      super.removeEventListener(type, listener, options4);
      if (this.$$c) {
        const unsub = this.$$l_u.get(listener);
        if (unsub) {
          unsub();
          this.$$l_u.delete(listener);
        }
      }
    }
    async connectedCallback() {
      this.$$cn = true;
      if (!this.$$c) {
        let create_slot = function(name3) {
          return (anchor) => {
            const slot2 = document.createElement("slot");
            if (name3 !== "default") slot2.name = name3;
            append(anchor, slot2);
          };
        };
        await Promise.resolve();
        if (!this.$$cn || this.$$c) {
          return;
        }
        const $$slots = {};
        const existing_slots = get_custom_elements_slots(this);
        for (const name3 of this.$$s) {
          if (name3 in existing_slots) {
            if (name3 === "default" && !this.$$d.children) {
              this.$$d.children = create_slot(name3);
              $$slots.default = true;
            } else {
              $$slots[name3] = create_slot(name3);
            }
          }
        }
        for (const attribute of this.attributes) {
          const name3 = this.$$g_p(attribute.name);
          if (!(name3 in this.$$d)) {
            this.$$d[name3] = get_custom_element_value(name3, attribute.value, this.$$p_d, "toProp");
          }
        }
        for (const key2 in this.$$p_d) {
          if (!(key2 in this.$$d) && this[key2] !== void 0) {
            this.$$d[key2] = this[key2];
            delete this[key2];
          }
        }
        this.$$c = createClassComponent({
          component: this.$$ctor,
          target: this.shadowRoot || this,
          props: {
            ...this.$$d,
            $$slots,
            $$host: this
          }
        });
        this.$$me = effect_root(() => {
          render_effect(() => {
            this.$$r = true;
            for (const key2 of object_keys(this.$$c)) {
              if (!this.$$p_d[key2]?.reflect) continue;
              this.$$d[key2] = this.$$c[key2];
              const attribute_value = get_custom_element_value(
                key2,
                this.$$d[key2],
                this.$$p_d,
                "toAttribute"
              );
              if (attribute_value == null) {
                this.removeAttribute(this.$$p_d[key2].attribute || key2);
              } else {
                this.setAttribute(this.$$p_d[key2].attribute || key2, attribute_value);
              }
            }
            this.$$r = false;
          });
        });
        for (const type in this.$$l) {
          for (const listener of this.$$l[type]) {
            const unsub = this.$$c.$on(type, listener);
            this.$$l_u.set(listener, unsub);
          }
        }
        this.$$l = {};
      }
    }
    // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte
    // and setting attributes through setAttribute etc, this is helpful
    /**
     * @param {string} attr
     * @param {string} _oldValue
     * @param {string} newValue
     */
    attributeChangedCallback(attr2, _oldValue, newValue) {
      if (this.$$r) return;
      attr2 = this.$$g_p(attr2);
      this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp");
      this.$$c?.$set({ [attr2]: this.$$d[attr2] });
    }
    disconnectedCallback() {
      this.$$cn = false;
      Promise.resolve().then(() => {
        if (!this.$$cn && this.$$c) {
          this.$$c.$destroy();
          this.$$me();
          this.$$c = void 0;
        }
      });
    }
    /**
     * @param {string} attribute_name
     */
    $$g_p(attribute_name) {
      return object_keys(this.$$p_d).find(
        (key2) => this.$$p_d[key2].attribute === attribute_name || !this.$$p_d[key2].attribute && key2.toLowerCase() === attribute_name
      ) || attribute_name;
    }
  };
}
function get_custom_element_value(prop2, value, props_definition, transform) {
  const type = props_definition[prop2]?.type;
  value = type === "Boolean" && typeof value !== "boolean" ? value != null : value;
  if (!transform || !props_definition[prop2]) {
    return value;
  } else if (transform === "toAttribute") {
    switch (type) {
      case "Object":
      case "Array":
        return value == null ? null : JSON.stringify(value);
      case "Boolean":
        return value ? "" : null;
      case "Number":
        return value == null ? null : value;
      default:
        return value;
    }
  } else {
    switch (type) {
      case "Object":
      case "Array":
        return value && JSON.parse(value);
      case "Boolean":
        return value;
      // conversion already handled above
      case "Number":
        return value != null ? +value : value;
      default:
        return value;
    }
  }
}
function get_custom_elements_slots(element2) {
  const result = {};
  element2.childNodes.forEach((node) => {
    result[
      /** @type {Element} node */
      node.slot || "default"
    ] = true;
  });
  return result;
}

// node_modules/svelte/src/index-client.js
if (false_default) {
  let throw_rune_error = function(rune) {
    if (!(rune in globalThis)) {
      let value;
      Object.defineProperty(globalThis, rune, {
        configurable: true,
        // eslint-disable-next-line getter-return
        get: () => {
          if (value !== void 0) {
            return value;
          }
          rune_outside_svelte(rune);
        },
        set: (v) => {
          value = v;
        }
      });
    }
  };
  throw_rune_error("$state");
  throw_rune_error("$effect");
  throw_rune_error("$derived");
  throw_rune_error("$inspect");
  throw_rune_error("$props");
  throw_rune_error("$bindable");
}
function onMount(fn) {
  if (component_context === null) {
    lifecycle_outside_component("onMount");
  }
  if (legacy_mode_flag && component_context.l !== null) {
    init_update_callbacks(component_context).m.push(fn);
  } else {
    user_effect(() => {
      const cleanup = untrack(fn);
      if (typeof cleanup === "function") return (
        /** @type {() => void} */
        cleanup
      );
    });
  }
}
function init_update_callbacks(context2) {
  var l = (
    /** @type {ComponentContextLegacy} */
    context2.l
  );
  return l.u ??= { a: [], b: [], m: [] };
}

// node_modules/svelte/src/store/utils.js
function subscribe_to_store(store, run3, invalidate) {
  if (store == null) {
    run3(void 0);
    if (invalidate) invalidate(void 0);
    return noop;
  }
  const unsub = untrack(
    () => store.subscribe(
      run3,
      // @ts-expect-error
      invalidate
    )
  );
  return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}

// node_modules/svelte/src/store/shared/index.js
var subscriber_queue = [];
function readable(value, start2) {
  return {
    subscribe: writable(value, start2).subscribe
  };
}
function writable(value, start2 = noop) {
  let stop2 = null;
  const subscribers = /* @__PURE__ */ new Set();
  function set4(new_value) {
    if (safe_not_equal(value, new_value)) {
      value = new_value;
      if (stop2) {
        const run_queue = !subscriber_queue.length;
        for (const subscriber of subscribers) {
          subscriber[1]();
          subscriber_queue.push(subscriber, value);
        }
        if (run_queue) {
          for (let i2 = 0; i2 < subscriber_queue.length; i2 += 2) {
            subscriber_queue[i2][0](subscriber_queue[i2 + 1]);
          }
          subscriber_queue.length = 0;
        }
      }
    }
  }
  function update3(fn) {
    set4(fn(
      /** @type {T} */
      value
    ));
  }
  function subscribe2(run3, invalidate = noop) {
    const subscriber = [run3, invalidate];
    subscribers.add(subscriber);
    if (subscribers.size === 1) {
      stop2 = start2(set4, update3) || noop;
    }
    run3(
      /** @type {T} */
      value
    );
    return () => {
      subscribers.delete(subscriber);
      if (subscribers.size === 0 && stop2) {
        stop2();
        stop2 = null;
      }
    };
  }
  return { set: set4, update: update3, subscribe: subscribe2 };
}
function derived2(stores, fn, initial_value) {
  const single = !Array.isArray(stores);
  const stores_array = single ? [stores] : stores;
  if (!stores_array.every(Boolean)) {
    throw new Error("derived() expects stores as input, got a falsy value");
  }
  const auto = fn.length < 2;
  return readable(initial_value, (set4, update3) => {
    let started = false;
    const values = [];
    let pending2 = 0;
    let cleanup = noop;
    const sync = () => {
      if (pending2) {
        return;
      }
      cleanup();
      const result = fn(single ? values[0] : values, set4, update3);
      if (auto) {
        set4(result);
      } else {
        cleanup = typeof result === "function" ? result : noop;
      }
    };
    const unsubscribers = stores_array.map(
      (store, i2) => subscribe_to_store(
        store,
        (value) => {
          values[i2] = value;
          pending2 &= ~(1 << i2);
          if (started) {
            sync();
          }
        },
        () => {
          pending2 |= 1 << i2;
        }
      )
    );
    started = true;
    sync();
    return function stop2() {
      run_all(unsubscribers);
      cleanup();
      started = false;
    };
  });
}
function get2(store) {
  let value;
  subscribe_to_store(store, (_2) => value = _2)();
  return value;
}

// node_modules/svelte/src/reactivity/utils.js
function increment(source3) {
  set(source3, source3.v + 1);
}

// src/lib/result.ts
var Ok = class _Ok {
  constructor(value) {
    this.value = value;
  }
  is_ok = true;
  is_err = false;
  and_then(op) {
    return op(this.value);
  }
  map(op) {
    return new _Ok(op(this.value));
  }
  map_err() {
    return this;
  }
  or_else() {
    return this;
  }
  unwrap() {
    return this.value;
  }
  unwrap_err() {
    throw new Error("unwrap_err() called on Ok().");
  }
  unwrap_or() {
    return this.value;
  }
};
var Err = class _Err {
  constructor(error2) {
    this.error = error2;
  }
  is_ok = false;
  is_err = true;
  and_then() {
    return this;
  }
  map() {
    return this;
  }
  or_else(op) {
    return op(this.error);
  }
  map_err(op) {
    return new _Err(op(this.error));
  }
  unwrap() {
    throw new Error("unwrap() called on error.");
  }
  unwrap_err() {
    return this.error;
  }
  unwrap_or(val) {
    return val;
  }
};
function ok(value) {
  return new Ok(value);
}
function err2(error2) {
  return new Err(error2);
}
function collect(items) {
  const ok_values = [];
  for (const r2 of items) {
    if (r2.is_ok) {
      ok_values.push(r2.value);
    } else {
      return r2;
    }
  }
  return ok(ok_values);
}

// src/lib/json.ts
function parseJSON(data) {
  try {
    return ok(JSON.parse(data));
  } catch (error2) {
    if (error2 instanceof SyntaxError) {
      return err2(error2);
    }
    throw error2;
  }
}

// src/lib/dom.ts
var ScriptTagNotFoundError = class extends Error {
  constructor(selector) {
    super(`<script> tag not found for selector '${selector}'`);
  }
};
function getScriptTagJSON(selector) {
  const el = document.querySelector(selector);
  if (!el) {
    return err2(new ScriptTagNotFoundError(selector));
  }
  return parseJSON(el.textContent ?? "");
}
function getScriptTagValue(selector, validator2) {
  return getScriptTagJSON(selector).and_then(validator2);
}

// src/lib/validation.ts
var ValidationError = class extends Error {
};
var PrimitiveValidationError = class extends ValidationError {
  constructor(primitive) {
    super(`Validation of primitive ${primitive} failed.`);
  }
};
var InvalidDateValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of date failed: invalid date`);
  }
};
var TypeDateValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of date failed: invalid type or length`);
  }
};
var ConstantValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of constant failed`);
  }
};
var TaggedUnionObjectValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of tagged union failed: expected object`);
  }
};
var TaggedUnionInvalidTagValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of tagged union failed: invalid tag.`);
  }
};
var TaggedUnionValidationError = class extends ValidationError {
  constructor(tag, cause) {
    super(`Validation of tagged union failed for tag ${tag}.`, { cause });
  }
};
var ArrayValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of array failed.`);
  }
};
var ArrayItemValidationError = class extends ValidationError {
  constructor(index3, cause) {
    super(`Validation of array failed at key ${index3.toString()}.`, { cause });
  }
};
var TupleValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of tuple failed.`);
  }
};
var TupleItemValidationError = class extends ValidationError {
  constructor(index3, cause) {
    super(`Validation of tuple failed at key ${index3.toString()}.`, { cause });
  }
};
var ObjectValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of object failed.`);
  }
};
var ObjectKeyValidationError = class extends ValidationError {
  constructor(key2, cause) {
    super(`Validation of object failed at key ${key2}.`, { cause });
  }
};
var RecordValidationError = class extends ValidationError {
  constructor() {
    super(`Validation of record failed.`);
  }
};
var RecordKeyValidationError = class extends ValidationError {
  constructor(key2, cause) {
    super(`Validation of record failed at key ${key2}.`, { cause });
  }
};
function defaultValue(validator2, value) {
  return (json) => {
    const res2 = validator2(json);
    return res2.is_ok ? res2 : ok(value());
  };
}
var unknown = ok;
var string = (json) => typeof json === "string" ? ok(json) : err2(new PrimitiveValidationError("string"));
var optional_string = (json) => typeof json === "string" ? ok(json) : ok("");
var boolean = (json) => typeof json === "boolean" ? ok(json) : err2(new PrimitiveValidationError("boolean"));
var number = (json) => typeof json === "number" ? ok(json) : err2(new PrimitiveValidationError("number"));
var date = (json) => {
  if (json instanceof Date) {
    return ok(json);
  }
  if (typeof json === "string" && json.length === 10) {
    const parsed = new Date(json);
    return Number.isNaN(+parsed) ? err2(new InvalidDateValidationError()) : ok(parsed);
  }
  return err2(new TypeDateValidationError());
};
function constant(value) {
  return (json) => json === value ? ok(json) : err2(new ConstantValidationError());
}
function constants(...args2) {
  return (json) => args2.includes(json) ? ok(json) : err2(new ConstantValidationError());
}
function tagged_union(tag, validators) {
  return (json) => {
    if (!isJsonObject(json)) {
      return err2(new TaggedUnionObjectValidationError());
    }
    const tag_value = json[tag];
    if (typeof tag_value != "string" || !Object.hasOwn(validators, tag_value)) {
      return err2(new TaggedUnionInvalidTagValidationError());
    }
    const res2 = validators[tag_value](json);
    return res2.is_ok ? res2 : err2(new TaggedUnionValidationError(tag_value, res2.error));
  };
}
function optional(validator2) {
  return (json) => json == null ? ok(null) : validator2(json);
}
function lazy(func2) {
  return (json) => func2()(json);
}
function array(validator2) {
  return (json) => {
    if (Array.isArray(json)) {
      const result = [];
      let i2 = 0;
      for (const element2 of json) {
        const res2 = validator2(element2);
        if (res2.is_ok) {
          result.push(res2.value);
        } else {
          return err2(new ArrayItemValidationError(i2, res2.error));
        }
        i2 += 1;
      }
      return ok(result);
    }
    return err2(new ArrayValidationError());
  };
}
function tuple(...args2) {
  return (json) => {
    if (Array.isArray(json) && json.length === args2.length) {
      const result = [];
      let i2 = 0;
      for (const decoder of args2) {
        const res2 = decoder(json[i2]);
        if (res2.is_ok) {
          result[i2] = res2.value;
        } else {
          return err2(new TupleItemValidationError(i2, res2.error));
        }
        i2 += 1;
      }
      return ok(result);
    }
    return err2(new TupleValidationError());
  };
}
function isJsonObject(json) {
  return typeof json === "object" && json !== null && !Array.isArray(json);
}
function object(validators) {
  return (json) => {
    if (isJsonObject(json)) {
      const obj = {};
      for (const key2 in validators) {
        if (Object.hasOwn(validators, key2)) {
          const res2 = validators[key2](json[key2]);
          if (res2.is_ok) {
            obj[key2] = res2.value;
          } else {
            return err2(new ObjectKeyValidationError(key2, res2.error));
          }
        }
      }
      return ok(obj);
    }
    return err2(new ObjectValidationError());
  };
}
function record(decoder) {
  return (json) => {
    if (isJsonObject(json)) {
      const ret = {};
      for (const [key2, value] of Object.entries(json)) {
        const res2 = decoder(value);
        if (res2.is_ok) {
          ret[key2] = res2.value;
        } else {
          return err2(new RecordKeyValidationError(key2, res2.error));
        }
      }
      return ok(ret);
    }
    return err2(new RecordValidationError());
  };
}

// src/log.ts
function log_error(...args2) {
  console.error(...args2);
}
function assert2(condition, message, ...extraArgs) {
  console.assert(condition, message, ...extraArgs);
}

// src/i18n.ts
var translations;
var validator = record(string);
function _(text2) {
  if (translations === void 0) {
    const res2 = (
      // The DOM is not available in tests
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
      globalThis.document !== void 0 ? getScriptTagValue("#translations", validator) : ok({})
    );
    translations = res2.unwrap_or({});
    if (res2.is_err) {
      log_error(`Loading translations failed:`, res2.error);
    }
  }
  return translations[text2] ?? text2;
}
function format(text2, values) {
  return text2.replace(
    /%\(\w+\)s/g,
    (match) => values[match.slice(2, -2)] ?? "MISSING"
  );
}

// src/lib/interval.ts
var DEFAULT_INTERVAL = "month";
var INTERVALS = [
  "year",
  "quarter",
  "month",
  "week",
  "day"
];
function getInterval(s) {
  return INTERVALS.includes(s) ? s : DEFAULT_INTERVAL;
}
function intervalLabel(s) {
  return {
    year: _("Yearly"),
    quarter: _("Quarterly"),
    month: _("Monthly"),
    week: _("Weekly"),
    day: _("Daily")
  }[s];
}

// src/lib/equals.ts
function shallow_equal(a, b) {
  const l = a.length;
  if (l !== b.length) {
    return false;
  }
  for (let i2 = 0; i2 < l; i2 += 1) {
    if (a[i2] !== b[i2]) {
      return false;
    }
  }
  return true;
}

// src/lib/store.ts
function derived_array(store, getter) {
  let val = [];
  return derived2(
    store,
    (store_val, set4) => {
      const newVal = getter(store_val);
      if (!shallow_equal(val, newVal)) {
        set4(newVal);
        val = newVal;
      }
    },
    val
  );
}
function localStorageSyncedStore(key2, validator2, init4, values = () => []) {
  const fullKey = `fava-${key2}`;
  const store = writable(void 0, (set4) => {
    const stored_val = localStorage.getItem(fullKey);
    let initial = null;
    if (stored_val != null) {
      const val = parseJSON(stored_val).and_then(validator2).unwrap_or(null);
      if (val !== null) {
        initial = val;
      }
    }
    set4(initial ?? init4());
    store.subscribe((val) => {
      localStorage.setItem(fullKey, JSON.stringify(val));
    });
  });
  return { ...store, values };
}

// src/stores/index.ts
var conversion = writable("");
var interval = writable(DEFAULT_INTERVAL);
var errors = writable([]);
var ledgerData = writable();
var fava_options = derived2(ledgerData, (v) => v.fava_options);
var conversion_currencies = derived_array(
  fava_options,
  ($fava_options) => $fava_options.conversion_currencies
);
var locale = derived2(
  fava_options,
  ($fava_options) => $fava_options.locale
);
var options = derived2(ledgerData, (v) => v.options);
var ledger_title = derived2(options, ($options) => $options.title);
var operating_currency = derived_array(
  options,
  ($options) => [...$options.operating_currency].sort()
);
var precisions = derived2(ledgerData, (v) => v.precisions);
var HAVE_EXCEL = derived2(ledgerData, (v) => v.have_excel);
var incognito = derived2(ledgerData, (v) => v.incognito);
var base_url = derived2(ledgerData, (v) => v.base_url);
var extensions = derived2(ledgerData, (v) => v.extensions);
var accounts = derived_array(ledgerData, (v) => v.accounts);
var accounts_set = derived2(
  accounts,
  ($accounts) => new Set($accounts)
);
var currency_name = derived2(
  ledgerData,
  ({ currency_names }) => (c) => currency_names[c] ?? c
);
var account_details = derived2(ledgerData, (v) => v.account_details);
var currencies = derived_array(ledgerData, (v) => v.currencies);
var links = derived_array(ledgerData, (v) => v.links);
var payees = derived_array(ledgerData, (v) => v.payees);
var tags = derived_array(ledgerData, (v) => v.tags);
var years = derived_array(ledgerData, (v) => v.years);
var currencies_sorted = derived_array(
  currencies,
  ($currencies) => [...$currencies].sort()
);

// src/stores/url.ts
var urlHash = writable("");
var pathname = writable();
var search = writable();
var searchParams = derived2(
  search,
  ($search) => new URLSearchParams($search)
);
var synced_search_param_names = [
  "account",
  "charts",
  "conversion",
  "filter",
  "interval",
  "time"
];
var syncedSearchParams = derived2(
  searchParams,
  ($searchParams) => {
    const params = new URLSearchParams();
    for (const name3 of synced_search_param_names) {
      const value = $searchParams.get(name3);
      if (value != null && value) {
        params.set(name3, value);
      }
    }
    return params;
  }
);
function closeOverlay() {
  if (window.location.hash) {
    window.history.pushState(null, "", "#");
  }
  urlHash.set("");
}

// src/helpers.ts
function getUrlPath(url) {
  const $base_url = get2(base_url);
  return $base_url && url.pathname.startsWith($base_url) ? decodeURI(url.pathname.slice($base_url.length)) : null;
}
function urlForInternal($base_url, $syncedSearchParams, report, params) {
  const url = `${$base_url}${report}`;
  const urlParams = $syncedSearchParams ? new URLSearchParams($syncedSearchParams) : new URLSearchParams();
  if (params) {
    Object.entries(params).forEach(([key2, value]) => {
      if (value != null) {
        urlParams.set(key2, value.toString());
      }
    });
  }
  const urlParamString = urlParams.toString();
  return urlParamString ? `${url}?${urlParams.toString()}` : url;
}
var urlFor = derived2(
  [base_url, syncedSearchParams],
  ([$base_url, $syncedSearchParams]) => (report, params) => urlForInternal($base_url, $syncedSearchParams, report, params)
);
var urlForRaw = derived2(
  [base_url],
  ([$base_url]) => (report, params) => urlForInternal($base_url, null, report, params)
);
var use_external_editor = derived2(
  fava_options,
  ($fava_options) => $fava_options.use_external_editor
);
var urlForSource = derived2(
  [urlFor, use_external_editor],
  ([$urlFor, $use_external_editor]) => (file_path, line) => $use_external_editor ? `beancount://${file_path}?lineno=${line}` : $urlFor("editor/", { file_path, line })
);
var urlForAccount = derived2(
  urlFor,
  ($urlFor) => (account2, params) => $urlFor(`account/${account2}/`, params)
);

// src/stores/mtime.ts
var ledger_mtime_writable = writable(BigInt("0"));
var ledger_mtime = ledger_mtime_writable;
function set_mtime(text2) {
  const new_value = text2.startsWith("X") ? (
    // the timestamp is replaced by a sequence of `X` in incognito mode.
    BigInt(text2.replaceAll("X", "1"))
  ) : BigInt(text2);
  ledger_mtime_writable.update((v) => new_value > v ? new_value : v);
}
function read_mtime() {
  const el = document.getElementById("ledger-mtime");
  const text2 = el?.textContent;
  if (text2 != null) {
    el?.remove();
    set_mtime(text2);
  }
}

// src/lib/fetch.ts
var FetchError = class extends Error {
};
async function fetch2(input, init4 = {}) {
  return window.fetch(input, { credentials: "same-origin", ...init4 });
}
async function handleJSON(response) {
  const data = await response.json().catch(() => null);
  if (!response.ok) {
    throw new FetchError(
      isJsonObject(data) && typeof data.error === "string" ? data.error : response.statusText
    );
  }
  if (!isJsonObject(data)) {
    throw new FetchError("Invalid response: not a valid JSON object");
  }
  return data;
}
var response_validator = object({
  data: unknown,
  mtime: defaultValue(string, () => null)
});
async function fetchJSON(input, init4) {
  const res2 = await fetch2(input, init4).then(handleJSON);
  const validated = response_validator(res2).unwrap_or(null);
  if (validated) {
    if (typeof validated.mtime === "string") {
      set_mtime(validated.mtime);
    }
    return validated.data;
  }
  log_error(res2);
  throw new FetchError("Invalid response: missing data or mtime key.");
}
async function handleText(response) {
  if (!response.ok) {
    const msg = await response.text().catch(() => response.statusText);
    throw new FetchError(msg);
  }
  return response.text();
}

// src/lib/errors.ts
function errorWithCauses(error2) {
  const msg = error2.message;
  return error2.cause instanceof Error ? `${msg}
  Caused by: ${errorWithCauses(error2.cause)}` : error2.message;
}

// src/notifications.ts
var notificationList = /* @__PURE__ */ (() => {
  let value = null;
  return () => {
    if (value === null) {
      value = document.createElement("div");
      value.className = "notifications";
      value.style.right = "10px";
      document.body.appendChild(value);
    }
    const headerHeight = document.querySelector("header")?.getBoundingClientRect().height ?? 50;
    value.style.top = `${(headerHeight + 10).toString()}px`;
    return value;
  };
})();
function notify(msg, cls = "info", callback) {
  const notification = document.createElement("li");
  notification.classList.add(cls);
  notification.appendChild(document.createTextNode(msg));
  notificationList().append(notification);
  notification.addEventListener("click", () => {
    notification.remove();
    callback?.();
  });
  setTimeout(() => {
    notification.remove();
  }, 5e3);
}
function notify_warn(msg) {
  notify(msg, "warning");
  console.warn(msg);
}
function notify_err(error2, msg = errorWithCauses) {
  if (error2 instanceof Error) {
    notify(msg(error2), "error");
  }
  log_error(error2);
}

// src/lib/events.ts
var Events = class {
  events;
  constructor() {
    this.events = /* @__PURE__ */ new Map();
  }
  /**
   * Register an event listener.
   *
   * @returns A function to remove the event listener.
   */
  on(event2, callback) {
    const events2 = this.events.get(event2) ?? [];
    this.events.set(event2, [...events2, callback]);
    return () => {
      this.remove(event2, callback);
    };
  }
  /**
   * Register an event listener that will only be executed once.
   */
  once(event2, callback) {
    const runOnce = () => {
      this.remove(event2, runOnce);
      callback();
    };
    this.on(event2, runOnce);
  }
  /**
   * Remove an event listener.
   */
  remove(event2, callback) {
    const events2 = this.events.get(event2);
    if (events2) {
      this.events.set(
        event2,
        events2.filter((c) => c !== callback)
      );
    }
  }
  /**
   * Trigger all listeners for an event.
   */
  trigger(event2) {
    const events2 = this.events.get(event2);
    events2?.forEach((callback) => {
      callback();
    });
  }
};
function delegate2(element2, type, selector, callback) {
  element2.addEventListener(type, (event2) => {
    let { target } = event2;
    if (!(target instanceof Node)) {
      return;
    }
    if (!(target instanceof Element)) {
      target = target.parentNode;
    }
    if (target instanceof Element) {
      const closest = target.closest(selector);
      if (closest) {
        callback(event2, closest);
      }
    }
  });
}

// src/sidebar/page-title.ts
var raw_page_title = writable("");
var has_changes = writable(false);
var page_title = derived2(
  raw_page_title,
  ($raw_page_title) => {
    if ($raw_page_title.startsWith("account:")) {
      return {
        title: $raw_page_title.slice("account:".length),
        type: "account"
      };
    }
    return { title: $raw_page_title, type: "plain" };
  }
);
function updatePageTitle() {
  const v = getScriptTagValue("#page-title", string);
  if (v.is_ok) {
    raw_page_title.set(v.value);
  }
}

// src/lib/iso4217.ts
var iso4217_default = /* @__PURE__ */ new Set([
  "AED",
  "AFN",
  "ALL",
  "AMD",
  "ANG",
  "AOA",
  "ARS",
  "AUD",
  "AWG",
  "AZN",
  "BAM",
  "BBD",
  "BDT",
  "BGN",
  "BHD",
  "BIF",
  "BMD",
  "BND",
  "BOB",
  "BOV",
  "BRL",
  "BSD",
  "BTN",
  "BWP",
  "BYN",
  "BZD",
  "CAD",
  "CDF",
  "CHE",
  "CHF",
  "CHW",
  "CLF",
  "CLP",
  "CNY",
  "COP",
  "COU",
  "CRC",
  "CUC",
  "CUP",
  "CVE",
  "CZK",
  "DJF",
  "DKK",
  "DOP",
  "DZD",
  "EGP",
  "ERN",
  "ETB",
  "EUR",
  "FJD",
  "FKP",
  "GBP",
  "GEL",
  "GHS",
  "GIP",
  "GMD",
  "GNF",
  "GTQ",
  "GYD",
  "HKD",
  "HNL",
  "HRK",
  "HTG",
  "HUF",
  "IDR",
  "ILS",
  "INR",
  "IQD",
  "IRR",
  "ISK",
  "JMD",
  "JOD",
  "JPY",
  "KES",
  "KGS",
  "KHR",
  "KMF",
  "KPW",
  "KRW",
  "KWD",
  "KYD",
  "KZT",
  "LAK",
  "LBP",
  "LKR",
  "LRD",
  "LSL",
  "LYD",
  "MAD",
  "MDL",
  "MGA",
  "MKD",
  "MMK",
  "MNT",
  "MOP",
  "MRU",
  "MUR",
  "MVR",
  "MWK",
  "MXN",
  "MXV",
  "MYR",
  "MZN",
  "NAD",
  "NGN",
  "NIO",
  "NOK",
  "NPR",
  "NZD",
  "OMR",
  "PAB",
  "PEN",
  "PGK",
  "PHP",
  "PKR",
  "PLN",
  "PYG",
  "QAR",
  "RON",
  "RSD",
  "RUB",
  "RWF",
  "SAR",
  "SBD",
  "SCR",
  "SDG",
  "SEK",
  "SGD",
  "SHP",
  "SLL",
  "SOS",
  "SRD",
  "SSP",
  "STN",
  "SVC",
  "SYP",
  "SZL",
  "THB",
  "TJS",
  "TMT",
  "TND",
  "TOP",
  "TRY",
  "TTD",
  "TWD",
  "TZS",
  "UAH",
  "UGX",
  "USD",
  "USN",
  "UYI",
  "UYU",
  "UYW",
  "UZS",
  "VES",
  "VND",
  "VUV",
  "WST",
  "XAF",
  "XAG",
  "XAU",
  "XBA",
  "XBB",
  "XBC",
  "XBD",
  "XCD",
  "XDR",
  "XOF",
  "XPD",
  "XPF",
  "XPT",
  "XSU",
  "XTS",
  "XUA",
  "XXX",
  "YER",
  "ZAR",
  "ZMW",
  "ZWL"
]);

// src/stores/chart.ts
var showCharts = writable(true);
var lastActiveChartName = writable(null);
var hierarchy_chart_mode_validator = constants("treemap", "sunburst");
var hierarchyChartMode = localStorageSyncedStore(
  "hierarchy-chart-mode",
  hierarchy_chart_mode_validator,
  () => "treemap",
  () => [
    ["treemap", _("Treemap")],
    ["sunburst", _("Sunburst")]
  ]
);
var line_chart_mode_validator = constants("line", "area");
var lineChartMode = localStorageSyncedStore(
  "line-chart-mode",
  line_chart_mode_validator,
  () => "line",
  () => [
    ["line", _("Line chart")],
    ["area", _("Area chart")]
  ]
);
var bar_chart_mode_validator = constants("stacked", "single");
var barChartMode = localStorageSyncedStore(
  "bar-chart-mode",
  bar_chart_mode_validator,
  () => "stacked",
  () => [
    ["stacked", _("Stacked Bars")],
    ["single", _("Single Bars")]
  ]
);
var chartToggledCurrencies = localStorageSyncedStore(
  "chart-toggled-currencies",
  array(string),
  () => []
);
var currency_suggestions = derived2(
  [operating_currency, currencies_sorted, conversion_currencies],
  ([$operating_currency, $currencies_sorted, $conversion_currencies]) => $conversion_currencies.length > 0 ? $conversion_currencies : [
    ...$operating_currency,
    ...$currencies_sorted.filter(
      (c) => !$operating_currency.includes(c) && iso4217_default.has(c)
    )
  ]
);
var conversions = derived2(
  currency_suggestions,
  ($currency_suggestions) => [
    "at_cost",
    "at_value",
    "units",
    ...$currency_suggestions
  ]
);

// src/stores/filters.ts
var time_filter = writable("");
var account_filter = writable("");
var fql_filter = writable("");
var filter_params = derived2(
  [time_filter, account_filter, fql_filter],
  ([$time_filter, $account_filter, $fql_filter]) => ({
    time: $time_filter,
    account: $account_filter,
    filter: $fql_filter
  })
);
function getURLFilters(url) {
  return {
    account: url.searchParams.get("account") ?? "",
    filter: url.searchParams.get("filter") ?? "",
    time: url.searchParams.get("time") ?? "",
    conversion: url.searchParams.get("conversion") ?? "",
    interval: url.searchParams.get("interval") ?? ""
  };
}

// src/router.ts
function setStoreValuesFromURL() {
  const params = new URL(window.location.href).searchParams;
  account_filter.set(params.get("account") ?? "");
  fql_filter.set(params.get("filter") ?? "");
  time_filter.set(params.get("time") ?? "");
  interval.set(getInterval(params.get("interval")));
  conversion.set(params.get("conversion") ?? "at_cost");
  showCharts.set(params.get("charts") !== "false");
}
var is_loading_internal = writable(false);
var is_loading = is_loading_internal;
var Router = class extends Events {
  /** The URL hash. */
  hash;
  /** The URL pathname. */
  pathname;
  /** The URL search string. */
  search;
  /** The <article> element. */
  article;
  /** The frontend rendered routes. */
  frontend_routes;
  /** A possibly frontend rendered component. */
  frontend_route;
  /**
   * Function to intercept navigation, e.g., when there are unsaved changes.
   *
   * If they return a string, that is displayed to the user in an alert to
   * confirm navigation.
   */
  interruptHandlers;
  constructor() {
    super();
    const article = document.querySelector("article");
    if (!article) {
      throw new Error("<article> element is missing from markup");
    }
    this.article = article;
    this.hash = window.location.hash;
    this.pathname = window.location.pathname;
    this.search = window.location.search;
    this.interruptHandlers = /* @__PURE__ */ new Set();
  }
  /**
   * Whether an interrupt handler is active like on the editor or import report.
   * Avoid auto-reloading in that case.
   */
  get hasInteruptHandler() {
    return this.interruptHandlers.size > 0;
  }
  /**
   * Add an interrupt handler. Returns a function that removes it.
   * This can be used directly in a svelte onMount hook.
   */
  addInteruptHandler(handler) {
    this.interruptHandlers.add(handler);
    return () => {
      this.interruptHandlers.delete(handler);
    };
  }
  /**
   * Check whether any of the registered interruptHandlers wants to stop
   * navigation.
   */
  shouldInterrupt() {
    for (const handler of this.interruptHandlers) {
      const ret = handler();
      if (ret != null) {
        return ret;
      }
    }
    return null;
  }
  async frontendRender(url) {
    const report = getUrlPath(url);
    const route = this.frontend_routes?.find(
      (r2) => report?.startsWith(`${r2.report}/`) === true
    );
    if (route) {
      is_loading_internal.set(true);
      try {
        await route.render(this.article, url, this.frontend_route);
      } finally {
        is_loading_internal.set(false);
      }
      raw_page_title.set(route.title);
    } else {
      this.frontend_route?.destroy();
    }
    this.frontend_route = route;
  }
  /**
   * This should be called once when the page has been loaded. Initializes the
   * router and takes over clicking on links.
   */
  init(frontend_routes2) {
    this.frontend_routes = frontend_routes2;
    urlHash.set(window.location.hash.slice(1));
    this.updateState();
    this.frontendRender(new URL(window.location.href)).catch(log_error);
    window.addEventListener("beforeunload", (event2) => {
      const leaveMessage = this.shouldInterrupt();
      if (leaveMessage != null) {
        event2.preventDefault();
      }
    });
    window.addEventListener("popstate", () => {
      urlHash.set(window.location.hash.slice(1));
      if (window.location.hash !== this.hash && window.location.pathname === this.pathname && window.location.search === this.search) {
        this.updateState();
      } else if (window.location.pathname !== this.pathname || window.location.search !== this.search) {
        this.loadURL(window.location.href, false).catch(log_error);
        setStoreValuesFromURL();
      }
    });
    this.takeOverLinks();
  }
  /**
   * Go to URL. If load is `true`, load the page at URL, otherwise only update
   * the current state.
   */
  navigate(url, load = true) {
    if (load) {
      this.loadURL(url).catch(log_error);
    } else {
      window.history.pushState(null, "", url);
      this.updateState();
    }
  }
  /**
   * Set the URL parameter and push a history state for it if changed.
   */
  set_search_param(key2, value) {
    const url = new URL(window.location.href);
    const current_value = url.searchParams.get(key2) ?? "";
    if (value !== current_value) {
      if (value) {
        url.searchParams.set(key2, value);
      } else {
        url.searchParams.delete(key2);
      }
      window.history.pushState(null, "", url);
      this.updateState();
    }
  }
  /*
   * Replace <article> contents with the page at `url`.
   *
   * If `historyState` is false, do not create a history state and do not
   * scroll to top.
   */
  async loadURL(url, historyState = true) {
    const leaveMessage = this.shouldInterrupt();
    if (leaveMessage != null) {
      if (!window.confirm(leaveMessage)) {
        return;
      }
    }
    const getUrl = new URL(url, window.location.href);
    await this.frontendRender(getUrl);
    try {
      if (!this.frontend_route) {
        getUrl.searchParams.set("partial", "true");
        is_loading_internal.set(true);
        const content2 = await fetch2(getUrl.toString()).then(handleText);
        if (historyState) {
          window.history.pushState(null, "", url);
          window.scroll(0, 0);
        }
        this.updateState();
        this.article.innerHTML = content2;
      } else {
        if (historyState) {
          window.history.pushState(null, "", url);
          window.scroll(0, 0);
        }
        this.updateState();
      }
      this.trigger("page-loaded");
      setStoreValuesFromURL();
      const hash3 = window.location.hash.slice(1);
      urlHash.set(hash3);
      if (hash3) {
        document.getElementById(hash3)?.scrollIntoView();
      }
    } catch (error2) {
      notify_err(error2, (e) => `Loading ${url} failed: ${e.message}`);
    } finally {
      is_loading_internal.set(false);
    }
  }
  /*
   * Update the routers state.
   *
   * The routers state is used to distinguish between the user navigating the
   * browser history or the hash changing.
   */
  updateState() {
    this.hash = window.location.hash;
    this.pathname = window.location.pathname;
    this.search = window.location.search;
    pathname.set(this.pathname);
    search.set(this.search);
  }
  /*
   * Intercept all clicks on links (<a>) and .navigate() to the link instead.
   *
   * Doesn't intercept if
   *  - a button different from the main button is used,
   *  - a modifier key is pressed,
   *  - the link starts with a hash '#', or
   *  - the link has a `data-remote` attribute.
   */
  takeOverLinks() {
    const is_normal_click = (event2) => event2.button === 0 && !event2.altKey && !event2.ctrlKey && !event2.metaKey && !event2.shiftKey;
    const is_external_link = (link2) => link2.hasAttribute("data-remote") || link2 instanceof HTMLAnchorElement && (link2.host !== window.location.host || !link2.protocol.startsWith("http"));
    delegate2(document, "click", "a", (event2, link2) => {
      if (!(event2 instanceof MouseEvent) || !(link2 instanceof HTMLAnchorElement || link2 instanceof SVGAElement)) {
        return;
      }
      if (!is_normal_click(event2)) {
        return;
      }
      if (event2.defaultPrevented) {
        return;
      }
      if (link2.getAttribute("href")?.charAt(0) === "#") {
        return;
      }
      if (is_external_link(link2)) {
        return;
      }
      event2.preventDefault();
      const href = link2 instanceof HTMLAnchorElement ? link2.href : link2.href.baseVal;
      this.navigate(href);
    });
  }
  /*
   * Reload the page.
   */
  reload() {
    this.loadURL(window.location.href, false).catch(log_error);
  }
};
var router = new Router();
var router_default = router;
function syncToURL(store, name3, defaultValue3, shouldLoad = true) {
  store.subscribe((val) => {
    const newURL = new URL(window.location.href);
    newURL.searchParams.set(name3, val.toString());
    if (val === "" || val === defaultValue3) {
      newURL.searchParams.delete(name3);
    }
    if (newURL.href !== window.location.href) {
      router.navigate(newURL.href, shouldLoad);
    }
  });
}
function syncStoreValuesToURL() {
  syncToURL(account_filter, "account", "");
  syncToURL(fql_filter, "filter", "");
  syncToURL(time_filter, "time", "");
  syncToURL(interval, "interval", DEFAULT_INTERVAL);
  syncToURL(conversion, "conversion", "at_cost");
  syncToURL(showCharts, "charts", true, false);
}

// node_modules/d3-array/src/ascending.js
function ascending(a, b) {
  return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-array/src/descending.js
function descending(a, b) {
  return a == null || b == null ? NaN : b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

// node_modules/d3-array/src/bisector.js
function bisector(f) {
  let compare1, compare2, delta;
  if (f.length !== 2) {
    compare1 = ascending;
    compare2 = (d, x2) => ascending(f(d), x2);
    delta = (d, x2) => f(d) - x2;
  } else {
    compare1 = f === ascending || f === descending ? f : zero;
    compare2 = f;
    delta = f;
  }
  function left2(a, x2, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0) return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x2) < 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function right2(a, x2, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0) return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x2) <= 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function center2(a, x2, lo = 0, hi = a.length) {
    const i2 = left2(a, x2, lo, hi - 1);
    return i2 > lo && delta(a[i2 - 1], x2) > -delta(a[i2], x2) ? i2 - 1 : i2;
  }
  return { left: left2, center: center2, right: right2 };
}
function zero() {
  return 0;
}

// node_modules/d3-array/src/number.js
function number2(x2) {
  return x2 === null ? NaN : +x2;
}

// node_modules/d3-array/src/bisect.js
var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
var bisectLeft = ascendingBisect.left;
var bisectCenter = bisector(number2).center;
var bisect_default = bisectRight;

// node_modules/d3-array/src/extent.js
function extent(values, valueof) {
  let min3;
  let max3;
  if (valueof === void 0) {
    for (const value of values) {
      if (value != null) {
        if (min3 === void 0) {
          if (value >= value) min3 = max3 = value;
        } else {
          if (min3 > value) min3 = value;
          if (max3 < value) max3 = value;
        }
      }
    }
  } else {
    let index3 = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index3, values)) != null) {
        if (min3 === void 0) {
          if (value >= value) min3 = max3 = value;
        } else {
          if (min3 > value) min3 = value;
          if (max3 < value) max3 = value;
        }
      }
    }
  }
  return [min3, max3];
}

// node_modules/internmap/src/index.js
var InternMap = class extends Map {
  constructor(entries, key2 = keyof) {
    super();
    Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key2 } });
    if (entries != null) for (const [key3, value] of entries) this.set(key3, value);
  }
  get(key2) {
    return super.get(intern_get(this, key2));
  }
  has(key2) {
    return super.has(intern_get(this, key2));
  }
  set(key2, value) {
    return super.set(intern_set(this, key2), value);
  }
  delete(key2) {
    return super.delete(intern_delete(this, key2));
  }
};
var InternSet = class extends Set {
  constructor(values, key2 = keyof) {
    super();
    Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key2 } });
    if (values != null) for (const value of values) this.add(value);
  }
  has(value) {
    return super.has(intern_get(this, value));
  }
  add(value) {
    return super.add(intern_set(this, value));
  }
  delete(value) {
    return super.delete(intern_delete(this, value));
  }
};
function intern_get({ _intern, _key }, value) {
  const key2 = _key(value);
  return _intern.has(key2) ? _intern.get(key2) : value;
}
function intern_set({ _intern, _key }, value) {
  const key2 = _key(value);
  if (_intern.has(key2)) return _intern.get(key2);
  _intern.set(key2, value);
  return value;
}
function intern_delete({ _intern, _key }, value) {
  const key2 = _key(value);
  if (_intern.has(key2)) {
    value = _intern.get(key2);
    _intern.delete(key2);
  }
  return value;
}
function keyof(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}

// node_modules/d3-array/src/identity.js
function identity(x2) {
  return x2;
}

// node_modules/d3-array/src/group.js
function group(values, ...keys) {
  return nest(values, identity, identity, keys);
}
function rollup(values, reduce, ...keys) {
  return nest(values, identity, reduce, keys);
}
function nest(values, map2, reduce, keys) {
  return function regroup(values2, i2) {
    if (i2 >= keys.length) return reduce(values2);
    const groups2 = new InternMap();
    const keyof2 = keys[i2++];
    let index3 = -1;
    for (const value of values2) {
      const key2 = keyof2(value, ++index3, values2);
      const group2 = groups2.get(key2);
      if (group2) group2.push(value);
      else groups2.set(key2, [value]);
    }
    for (const [key2, values3] of groups2) {
      groups2.set(key2, regroup(values3, i2));
    }
    return map2(groups2);
  }(values, 0);
}

// node_modules/d3-array/src/permute.js
function permute(source3, keys) {
  return Array.from(keys, (key2) => source3[key2]);
}

// node_modules/d3-array/src/sort.js
function sort(values, ...F) {
  if (typeof values[Symbol.iterator] !== "function") throw new TypeError("values is not iterable");
  values = Array.from(values);
  let [f] = F;
  if (f && f.length !== 2 || F.length > 1) {
    const index3 = Uint32Array.from(values, (d, i2) => i2);
    if (F.length > 1) {
      F = F.map((f2) => values.map(f2));
      index3.sort((i2, j) => {
        for (const f2 of F) {
          const c = ascendingDefined(f2[i2], f2[j]);
          if (c) return c;
        }
      });
    } else {
      f = values.map(f);
      index3.sort((i2, j) => ascendingDefined(f[i2], f[j]));
    }
    return permute(values, index3);
  }
  return values.sort(compareDefined(f));
}
function compareDefined(compare2 = ascending) {
  if (compare2 === ascending) return ascendingDefined;
  if (typeof compare2 !== "function") throw new TypeError("compare is not a function");
  return (a, b) => {
    const x2 = compare2(a, b);
    if (x2 || x2 === 0) return x2;
    return (compare2(b, b) === 0) - (compare2(a, a) === 0);
  };
}
function ascendingDefined(a, b) {
  return (a == null || !(a >= a)) - (b == null || !(b >= b)) || (a < b ? -1 : a > b ? 1 : 0);
}

// node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50);
var e5 = Math.sqrt(10);
var e2 = Math.sqrt(2);
function tickSpec(start2, stop2, count2) {
  const step = (stop2 - start2) / Math.max(0, count2), power = Math.floor(Math.log10(step)), error2 = step / Math.pow(10, power), factor = error2 >= e10 ? 10 : error2 >= e5 ? 5 : error2 >= e2 ? 2 : 1;
  let i1, i2, inc;
  if (power < 0) {
    inc = Math.pow(10, -power) / factor;
    i1 = Math.round(start2 * inc);
    i2 = Math.round(stop2 * inc);
    if (i1 / inc < start2) ++i1;
    if (i2 / inc > stop2) --i2;
    inc = -inc;
  } else {
    inc = Math.pow(10, power) * factor;
    i1 = Math.round(start2 / inc);
    i2 = Math.round(stop2 / inc);
    if (i1 * inc < start2) ++i1;
    if (i2 * inc > stop2) --i2;
  }
  if (i2 < i1 && 0.5 <= count2 && count2 < 2) return tickSpec(start2, stop2, count2 * 2);
  return [i1, i2, inc];
}
function ticks(start2, stop2, count2) {
  stop2 = +stop2, start2 = +start2, count2 = +count2;
  if (!(count2 > 0)) return [];
  if (start2 === stop2) return [start2];
  const reverse = stop2 < start2, [i1, i2, inc] = reverse ? tickSpec(stop2, start2, count2) : tickSpec(start2, stop2, count2);
  if (!(i2 >= i1)) return [];
  const n = i2 - i1 + 1, ticks2 = new Array(n);
  if (reverse) {
    if (inc < 0) for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i2 - i3) / -inc;
    else for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i2 - i3) * inc;
  } else {
    if (inc < 0) for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i1 + i3) / -inc;
    else for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i1 + i3) * inc;
  }
  return ticks2;
}
function tickIncrement(start2, stop2, count2) {
  stop2 = +stop2, start2 = +start2, count2 = +count2;
  return tickSpec(start2, stop2, count2)[2];
}
function tickStep(start2, stop2, count2) {
  stop2 = +stop2, start2 = +start2, count2 = +count2;
  const reverse = stop2 < start2, inc = reverse ? tickIncrement(stop2, start2, count2) : tickIncrement(start2, stop2, count2);
  return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
}

// node_modules/d3-array/src/max.js
function max(values, valueof) {
  let max3;
  if (valueof === void 0) {
    for (const value of values) {
      if (value != null && (max3 < value || max3 === void 0 && value >= value)) {
        max3 = value;
      }
    }
  } else {
    let index3 = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index3, values)) != null && (max3 < value || max3 === void 0 && value >= value)) {
        max3 = value;
      }
    }
  }
  return max3;
}

// node_modules/d3-array/src/min.js
function min(values, valueof) {
  let min3;
  if (valueof === void 0) {
    for (const value of values) {
      if (value != null && (min3 > value || min3 === void 0 && value >= value)) {
        min3 = value;
      }
    }
  } else {
    let index3 = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index3, values)) != null && (min3 > value || min3 === void 0 && value >= value)) {
        min3 = value;
      }
    }
  }
  return min3;
}

// node_modules/d3-array/src/range.js
function range(start2, stop2, step) {
  start2 = +start2, stop2 = +stop2, step = (n = arguments.length) < 2 ? (stop2 = start2, start2 = 0, 1) : n < 3 ? 1 : +step;
  var i2 = -1, n = Math.max(0, Math.ceil((stop2 - start2) / step)) | 0, range2 = new Array(n);
  while (++i2 < n) {
    range2[i2] = start2 + i2 * step;
  }
  return range2;
}

// node_modules/d3-array/src/sum.js
function sum(values, valueof) {
  let sum2 = 0;
  if (valueof === void 0) {
    for (let value of values) {
      if (value = +value) {
        sum2 += value;
      }
    }
  } else {
    let index3 = -1;
    for (let value of values) {
      if (value = +valueof(value, ++index3, values)) {
        sum2 += value;
      }
    }
  }
  return sum2;
}

// node_modules/d3-array/src/intersection.js
function intersection(values, ...others) {
  values = new InternSet(values);
  others = others.map(set2);
  out: for (const value of values) {
    for (const other of others) {
      if (!other.has(value)) {
        values.delete(value);
        continue out;
      }
    }
  }
  return values;
}
function set2(values) {
  return values instanceof InternSet ? values : new InternSet(values);
}

// node_modules/d3-hierarchy/src/hierarchy/count.js
function count(node) {
  var sum2 = 0, children2 = node.children, i2 = children2 && children2.length;
  if (!i2) sum2 = 1;
  else while (--i2 >= 0) sum2 += children2[i2].value;
  node.value = sum2;
}
function count_default() {
  return this.eachAfter(count);
}

// node_modules/d3-hierarchy/src/hierarchy/each.js
function each_default(callback, that) {
  let index3 = -1;
  for (const node of this) {
    callback.call(that, node, ++index3, this);
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
function eachBefore_default(callback, that) {
  var node = this, nodes = [node], children2, i2, index3 = -1;
  while (node = nodes.pop()) {
    callback.call(that, node, ++index3, this);
    if (children2 = node.children) {
      for (i2 = children2.length - 1; i2 >= 0; --i2) {
        nodes.push(children2[i2]);
      }
    }
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
function eachAfter_default(callback, that) {
  var node = this, nodes = [node], next2 = [], children2, i2, n, index3 = -1;
  while (node = nodes.pop()) {
    next2.push(node);
    if (children2 = node.children) {
      for (i2 = 0, n = children2.length; i2 < n; ++i2) {
        nodes.push(children2[i2]);
      }
    }
  }
  while (node = next2.pop()) {
    callback.call(that, node, ++index3, this);
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/find.js
function find_default(callback, that) {
  let index3 = -1;
  for (const node of this) {
    if (callback.call(that, node, ++index3, this)) {
      return node;
    }
  }
}

// node_modules/d3-hierarchy/src/hierarchy/sum.js
function sum_default(value) {
  return this.eachAfter(function(node) {
    var sum2 = +value(node.data) || 0, children2 = node.children, i2 = children2 && children2.length;
    while (--i2 >= 0) sum2 += children2[i2].value;
    node.value = sum2;
  });
}

// node_modules/d3-hierarchy/src/hierarchy/sort.js
function sort_default(compare2) {
  return this.eachBefore(function(node) {
    if (node.children) {
      node.children.sort(compare2);
    }
  });
}

// node_modules/d3-hierarchy/src/hierarchy/path.js
function path_default(end) {
  var start2 = this, ancestor = leastCommonAncestor(start2, end), nodes = [start2];
  while (start2 !== ancestor) {
    start2 = start2.parent;
    nodes.push(start2);
  }
  var k = nodes.length;
  while (end !== ancestor) {
    nodes.splice(k, 0, end);
    end = end.parent;
  }
  return nodes;
}
function leastCommonAncestor(a, b) {
  if (a === b) return a;
  var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
  a = aNodes.pop();
  b = bNodes.pop();
  while (a === b) {
    c = a;
    a = aNodes.pop();
    b = bNodes.pop();
  }
  return c;
}

// node_modules/d3-hierarchy/src/hierarchy/ancestors.js
function ancestors_default() {
  var node = this, nodes = [node];
  while (node = node.parent) {
    nodes.push(node);
  }
  return nodes;
}

// node_modules/d3-hierarchy/src/hierarchy/descendants.js
function descendants_default() {
  return Array.from(this);
}

// node_modules/d3-hierarchy/src/hierarchy/leaves.js
function leaves_default() {
  var leaves = [];
  this.eachBefore(function(node) {
    if (!node.children) {
      leaves.push(node);
    }
  });
  return leaves;
}

// node_modules/d3-hierarchy/src/hierarchy/links.js
function links_default() {
  var root68 = this, links2 = [];
  root68.each(function(node) {
    if (node !== root68) {
      links2.push({ source: node.parent, target: node });
    }
  });
  return links2;
}

// node_modules/d3-hierarchy/src/hierarchy/iterator.js
function* iterator_default() {
  var node = this, current, next2 = [node], children2, i2, n;
  do {
    current = next2.reverse(), next2 = [];
    while (node = current.pop()) {
      yield node;
      if (children2 = node.children) {
        for (i2 = 0, n = children2.length; i2 < n; ++i2) {
          next2.push(children2[i2]);
        }
      }
    }
  } while (next2.length);
}

// node_modules/d3-hierarchy/src/hierarchy/index.js
function hierarchy(data, children2) {
  if (data instanceof Map) {
    data = [void 0, data];
    if (children2 === void 0) children2 = mapChildren;
  } else if (children2 === void 0) {
    children2 = objectChildren;
  }
  var root68 = new Node2(data), node, nodes = [root68], child2, childs, i2, n;
  while (node = nodes.pop()) {
    if ((childs = children2(node.data)) && (n = (childs = Array.from(childs)).length)) {
      node.children = childs;
      for (i2 = n - 1; i2 >= 0; --i2) {
        nodes.push(child2 = childs[i2] = new Node2(childs[i2]));
        child2.parent = node;
        child2.depth = node.depth + 1;
      }
    }
  }
  return root68.eachBefore(computeHeight);
}
function node_copy() {
  return hierarchy(this).eachBefore(copyData);
}
function objectChildren(d) {
  return d.children;
}
function mapChildren(d) {
  return Array.isArray(d) ? d[1] : null;
}
function copyData(node) {
  if (node.data.value !== void 0) node.value = node.data.value;
  node.data = node.data.data;
}
function computeHeight(node) {
  var height = 0;
  do
    node.height = height;
  while ((node = node.parent) && node.height < ++height);
}
function Node2(data) {
  this.data = data;
  this.depth = this.height = 0;
  this.parent = null;
}
Node2.prototype = hierarchy.prototype = {
  constructor: Node2,
  count: count_default,
  each: each_default,
  eachAfter: eachAfter_default,
  eachBefore: eachBefore_default,
  find: find_default,
  sum: sum_default,
  sort: sort_default,
  path: path_default,
  ancestors: ancestors_default,
  descendants: descendants_default,
  leaves: leaves_default,
  links: links_default,
  copy: node_copy,
  [Symbol.iterator]: iterator_default
};

// node_modules/d3-hierarchy/src/accessors.js
function required(f) {
  if (typeof f !== "function") throw new Error();
  return f;
}

// node_modules/d3-hierarchy/src/constant.js
function constantZero() {
  return 0;
}
function constant_default(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-hierarchy/src/treemap/round.js
function round_default(node) {
  node.x0 = Math.round(node.x0);
  node.y0 = Math.round(node.y0);
  node.x1 = Math.round(node.x1);
  node.y1 = Math.round(node.y1);
}

// node_modules/d3-hierarchy/src/treemap/dice.js
function dice_default(parent2, x0, y0, x1, y1) {
  var nodes = parent2.children, node, i2 = -1, n = nodes.length, k = parent2.value && (x1 - x0) / parent2.value;
  while (++i2 < n) {
    node = nodes[i2], node.y0 = y0, node.y1 = y1;
    node.x0 = x0, node.x1 = x0 += node.value * k;
  }
}

// node_modules/d3-hierarchy/src/partition.js
function partition_default() {
  var dx = 1, dy = 1, padding = 0, round = false;
  function partition(root68) {
    var n = root68.height + 1;
    root68.x0 = root68.y0 = padding;
    root68.x1 = dx;
    root68.y1 = dy / n;
    root68.eachBefore(positionNode(dy, n));
    if (round) root68.eachBefore(round_default);
    return root68;
  }
  function positionNode(dy2, n) {
    return function(node) {
      if (node.children) {
        dice_default(node, node.x0, dy2 * (node.depth + 1) / n, node.x1, dy2 * (node.depth + 2) / n);
      }
      var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding;
      if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
      node.x0 = x0;
      node.y0 = y0;
      node.x1 = x1;
      node.y1 = y1;
    };
  }
  partition.round = function(x2) {
    return arguments.length ? (round = !!x2, partition) : round;
  };
  partition.size = function(x2) {
    return arguments.length ? (dx = +x2[0], dy = +x2[1], partition) : [dx, dy];
  };
  partition.padding = function(x2) {
    return arguments.length ? (padding = +x2, partition) : padding;
  };
  return partition;
}

// node_modules/d3-hierarchy/src/treemap/slice.js
function slice_default(parent2, x0, y0, x1, y1) {
  var nodes = parent2.children, node, i2 = -1, n = nodes.length, k = parent2.value && (y1 - y0) / parent2.value;
  while (++i2 < n) {
    node = nodes[i2], node.x0 = x0, node.x1 = x1;
    node.y0 = y0, node.y1 = y0 += node.value * k;
  }
}

// node_modules/d3-hierarchy/src/treemap/squarify.js
var phi = (1 + Math.sqrt(5)) / 2;
function squarifyRatio(ratio, parent2, x0, y0, x1, y1) {
  var rows = [], nodes = parent2.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent2.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
  while (i0 < n) {
    dx = x1 - x0, dy = y1 - y0;
    do
      sumValue = nodes[i1++].value;
    while (!sumValue && i1 < n);
    minValue = maxValue = sumValue;
    alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
    beta = sumValue * sumValue * alpha;
    minRatio = Math.max(maxValue / beta, beta / minValue);
    for (; i1 < n; ++i1) {
      sumValue += nodeValue = nodes[i1].value;
      if (nodeValue < minValue) minValue = nodeValue;
      if (nodeValue > maxValue) maxValue = nodeValue;
      beta = sumValue * sumValue * alpha;
      newRatio = Math.max(maxValue / beta, beta / minValue);
      if (newRatio > minRatio) {
        sumValue -= nodeValue;
        break;
      }
      minRatio = newRatio;
    }
    rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
    if (row.dice) dice_default(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
    else slice_default(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
    value -= sumValue, i0 = i1;
  }
  return rows;
}
var squarify_default = function custom(ratio) {
  function squarify(parent2, x0, y0, x1, y1) {
    squarifyRatio(ratio, parent2, x0, y0, x1, y1);
  }
  squarify.ratio = function(x2) {
    return custom((x2 = +x2) > 1 ? x2 : 1);
  };
  return squarify;
}(phi);

// node_modules/d3-hierarchy/src/treemap/index.js
function treemap_default() {
  var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
  function treemap(root68) {
    root68.x0 = root68.y0 = 0;
    root68.x1 = dx;
    root68.y1 = dy;
    root68.eachBefore(positionNode);
    paddingStack = [0];
    if (round) root68.eachBefore(round_default);
    return root68;
  }
  function positionNode(node) {
    var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;
    if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
    if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
    node.x0 = x0;
    node.y0 = y0;
    node.x1 = x1;
    node.y1 = y1;
    if (node.children) {
      p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
      x0 += paddingLeft(node) - p;
      y0 += paddingTop(node) - p;
      x1 -= paddingRight(node) - p;
      y1 -= paddingBottom(node) - p;
      if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
      tile(node, x0, y0, x1, y1);
    }
  }
  treemap.round = function(x2) {
    return arguments.length ? (round = !!x2, treemap) : round;
  };
  treemap.size = function(x2) {
    return arguments.length ? (dx = +x2[0], dy = +x2[1], treemap) : [dx, dy];
  };
  treemap.tile = function(x2) {
    return arguments.length ? (tile = required(x2), treemap) : tile;
  };
  treemap.padding = function(x2) {
    return arguments.length ? treemap.paddingInner(x2).paddingOuter(x2) : treemap.paddingInner();
  };
  treemap.paddingInner = function(x2) {
    return arguments.length ? (paddingInner = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingInner;
  };
  treemap.paddingOuter = function(x2) {
    return arguments.length ? treemap.paddingTop(x2).paddingRight(x2).paddingBottom(x2).paddingLeft(x2) : treemap.paddingTop();
  };
  treemap.paddingTop = function(x2) {
    return arguments.length ? (paddingTop = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingTop;
  };
  treemap.paddingRight = function(x2) {
    return arguments.length ? (paddingRight = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingRight;
  };
  treemap.paddingBottom = function(x2) {
    return arguments.length ? (paddingBottom = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingBottom;
  };
  treemap.paddingLeft = function(x2) {
    return arguments.length ? (paddingLeft = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingLeft;
  };
  return treemap;
}

// src/stores/journal.ts
var defaultValue2 = [
  "balance",
  "budget",
  "cleared",
  "custom",
  "discovered",
  "document",
  "note",
  "pending",
  "query",
  "statement",
  "transaction"
];
var journalShow = localStorageSyncedStore(
  "journal-show",
  array(string),
  () => defaultValue2
);
var defaultSortOrder = ["date", "desc"];
var journalSortOrder = localStorageSyncedStore(
  "journal-sort-order",
  tuple(string, constants("asc", "desc")),
  () => defaultSortOrder
);

// src/sort/index.ts
var get_direction = (o) => o === "asc" ? 1 : -1;
var collator = Intl.Collator();
var compare_strings = collator.compare.bind(collator);
var Sorter = class _Sorter {
  constructor(column, order) {
    this.column = column;
    this.order = order;
  }
  /** Get a new sorter by switching to a possibly different column. */
  switchColumn(column) {
    if (column === this.column) {
      return new _Sorter(column, this.order === "asc" ? "desc" : "asc");
    }
    return new _Sorter(column, "asc");
  }
  /** Sort the data. */
  sort(data) {
    return this.column.sort(data, get_direction(this.order));
  }
};
function sort_by_strings(data, value) {
  return sort_internal(data, value, compare_strings, 1);
}
function sort_internal(data, value, compare2, direction) {
  const indices = Uint32Array.from(data, (_d, i2) => i2);
  const values = data.map(value);
  indices.sort((a, b) => direction * compare2(values[a], values[b]));
  return permute(data, indices);
}
var UnsortedColumn = class {
  constructor(name3) {
    this.name = name3;
  }
  sort(data) {
    return data;
  }
};
var NumberColumn = class {
  constructor(name3, value) {
    this.name = name3;
    this.value = value;
  }
  compare = (a, b) => a - b;
  sort(data, direction) {
    return sort_internal(data, this.value, this.compare, direction);
  }
};
var DateColumn = class extends NumberColumn {
  constructor(name3) {
    super(name3, (d) => new Date(d.date).valueOf());
    this.name = name3;
  }
};
var StringColumn = class {
  constructor(name3, value) {
    this.name = name3;
    this.value = value;
  }
  compare = compare_strings;
  sort(data, direction) {
    return sort_internal(data, this.value, this.compare, direction);
  }
};
function parse_number(num2) {
  const cleaned = num2.replace(/[^\-?0-9.]/g, "");
  const n = parseFloat(cleaned);
  return Number.isNaN(n) ? 0 : n;
}
function compare_numbers(a, b) {
  return parse_number(a) - parse_number(b);
}
function sortElements(parent2, elements, selector, direction, type) {
  const comparator = type === "num" ? compare_numbers : compare_strings;
  const value = (a) => {
    const el = selector(a);
    return el?.getAttribute("data-sort-value") ?? el?.textContent ?? "";
  };
  const sorted_elements = sort_internal(elements, value, comparator, direction);
  const fragment = document.createDocumentFragment();
  sorted_elements.forEach((el) => {
    fragment.appendChild(el);
  });
  parent2.appendChild(fragment);
}
function sortableJournal(ol) {
  const head2 = ol.querySelector(".head");
  if (!head2) {
    throw new Error("Journal is missing header.");
  }
  const headers = head2.querySelectorAll("span[data-sort]");
  const [initialColumn, initialOrder] = get2(journalSortOrder);
  headers.forEach((header) => {
    const headerClass = header.classList[0];
    const name3 = header.getAttribute("data-sort-name");
    const type = header.getAttribute("data-sort");
    if (headerClass == null || name3 == null || type == null) {
      throw new Error(`Journal has invalid header: ${header.innerHTML}.`);
    }
    const sort2 = (order) => {
      headers.forEach((el) => {
        el.removeAttribute("data-order");
      });
      header.setAttribute("data-order", order);
      sortElements(
        ol,
        [].slice.call(ol.children, 1),
        (li) => li.querySelector(`.${headerClass}`),
        get_direction(order),
        type
      );
    };
    if (name3 === initialColumn) {
      sort2(initialOrder);
    }
    header.addEventListener("click", () => {
      const order = header.getAttribute("data-order") === "asc" ? "desc" : "asc";
      sort2(order);
      journalSortOrder.set([name3, order]);
    });
  });
}

// src/charts/hierarchy.ts
function addInternalNodesAsLeaves({
  account: account2,
  balance,
  children: children2
}) {
  if (children2.length) {
    const c = children2.map(addInternalNodesAsLeaves);
    c.push({ account: account2, balance, children: [], dummy: true });
    return { account: account2, balance: {}, children: c, dummy: false };
  }
  return { account: account2, balance, children: [], dummy: false };
}
var HierarchyChart = class {
  constructor(name3, data) {
    this.name = name3;
    this.data = data;
    this.currencies = [...this.data.keys()];
    const first_currency = this.currencies[0];
    this.treemap_currency = first_currency != null ? writable(first_currency) : null;
  }
  type = "hierarchy";
  /** All currencies for which we have an hierarchy. */
  currencies;
  /** The currency to show the treemap of. */
  treemap_currency;
};
var sort_children = (values) => sort_by_strings(values, (v) => v.account);
var inventory = record(number);
var account_hierarchy_validator = object({
  account: string,
  balance: inventory,
  balance_children: inventory,
  children: lazy(
    () => (json) => array(account_hierarchy_validator)(json).map(sort_children)
  ),
  cost: optional(inventory),
  cost_children: optional(inventory),
  has_txns: defaultValue(boolean, () => false)
});
function hierarchy_from_parsed_data(label, data, { currencies: currencies2 }) {
  const root68 = addInternalNodesAsLeaves(data);
  return new HierarchyChart(
    label,
    new Map(
      currencies2.map((currency) => {
        const r2 = hierarchy(root68);
        const root_balance = sum(
          r2.descendants(),
          (n) => n.data.balance[currency] ?? 0
        );
        const sign = root_balance ? Math.sign(root_balance) : 1;
        r2.sum(
          (d) => sign * Math.max(sign * (d.balance[currency] ?? 0), 0)
        ).sort((a, b) => sign * ((b.value ?? 0) - (a.value ?? 0)));
        return [currency, r2];
      }).filter(([, h]) => h.value != null && h.value !== 0)
    )
  );
}
var hierarchy_data_with_modifier = object({
  modifier: number,
  root: unknown
});
function hierarchy2(label, json, $chartContext) {
  const with_modifier = hierarchy_data_with_modifier(json);
  if (with_modifier.is_ok) {
    notify_warn(
      "Tree for the hierarchy chart should now be specified at the top-level directly.\n{ modifier: 1, root: { ...children } } -> { ...children }"
    );
  }
  const root68 = with_modifier.is_ok ? with_modifier.value.root : json;
  return account_hierarchy_validator(root68).map(
    (r2) => hierarchy_from_parsed_data(label, r2, $chartContext)
  );
}

// src/entries/amount.ts
var Amount = class _Amount {
  constructor(number7, currency) {
    this.number = number7;
    this.currency = currency;
  }
  /** Render to a string. */
  str($ctx) {
    return $ctx.amount(this.number, this.currency);
  }
  static raw_validator = object({ number, currency: string });
  static validator = (json) => _Amount.raw_validator(json).map(
    ({ number: number7, currency }) => new _Amount(number7, currency)
  );
};

// node_modules/d3-format/src/formatDecimal.js
function formatDecimal_default(x2) {
  return Math.abs(x2 = Math.round(x2)) >= 1e21 ? x2.toLocaleString("en").replace(/,/g, "") : x2.toString(10);
}
function formatDecimalParts(x2, p) {
  if ((i2 = (x2 = p ? x2.toExponential(p - 1) : x2.toExponential()).indexOf("e")) < 0) return null;
  var i2, coefficient = x2.slice(0, i2);
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x2.slice(i2 + 1)
  ];
}

// node_modules/d3-format/src/exponent.js
function exponent_default(x2) {
  return x2 = formatDecimalParts(Math.abs(x2)), x2 ? x2[1] : NaN;
}

// node_modules/d3-format/src/formatGroup.js
function formatGroup_default(grouping, thousands) {
  return function(value, width) {
    var i2 = value.length, t4 = [], j = 0, g = grouping[0], length = 0;
    while (i2 > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t4.push(value.substring(i2 -= g, i2 + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }
    return t4.reverse().join(thousands);
  };
}

// node_modules/d3-format/src/formatNumerals.js
function formatNumerals_default(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i2) {
      return numerals[+i2];
    });
  };
}

// node_modules/d3-format/src/formatSpecifier.js
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
  if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match;
  return new FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}
formatSpecifier.prototype = FormatSpecifier.prototype;
function FormatSpecifier(specifier) {
  this.fill = specifier.fill === void 0 ? " " : specifier.fill + "";
  this.align = specifier.align === void 0 ? ">" : specifier.align + "";
  this.sign = specifier.sign === void 0 ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === void 0 ? void 0 : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === void 0 ? "" : specifier.type + "";
}
FormatSpecifier.prototype.toString = function() {
  return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type;
};

// node_modules/d3-format/src/formatTrim.js
function formatTrim_default(s) {
  out: for (var n = s.length, i2 = 1, i0 = -1, i1; i2 < n; ++i2) {
    switch (s[i2]) {
      case ".":
        i0 = i1 = i2;
        break;
      case "0":
        if (i0 === 0) i0 = i2;
        i1 = i2;
        break;
      default:
        if (!+s[i2]) break out;
        if (i0 > 0) i0 = 0;
        break;
    }
  }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}

// node_modules/d3-format/src/formatPrefixAuto.js
var prefixExponent;
function formatPrefixAuto_default(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d) return x2 + "";
  var coefficient = d[0], exponent = d[1], i2 = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length;
  return i2 === n ? coefficient : i2 > n ? coefficient + new Array(i2 - n + 1).join("0") : i2 > 0 ? coefficient.slice(0, i2) + "." + coefficient.slice(i2) : "0." + new Array(1 - i2).join("0") + formatDecimalParts(x2, Math.max(0, p + i2 - 1))[0];
}

// node_modules/d3-format/src/formatRounded.js
function formatRounded_default(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d) return x2 + "";
  var coefficient = d[0], exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

// node_modules/d3-format/src/formatTypes.js
var formatTypes_default = {
  "%": (x2, p) => (x2 * 100).toFixed(p),
  "b": (x2) => Math.round(x2).toString(2),
  "c": (x2) => x2 + "",
  "d": formatDecimal_default,
  "e": (x2, p) => x2.toExponential(p),
  "f": (x2, p) => x2.toFixed(p),
  "g": (x2, p) => x2.toPrecision(p),
  "o": (x2) => Math.round(x2).toString(8),
  "p": (x2, p) => formatRounded_default(x2 * 100, p),
  "r": formatRounded_default,
  "s": formatPrefixAuto_default,
  "X": (x2) => Math.round(x2).toString(16).toUpperCase(),
  "x": (x2) => Math.round(x2).toString(16)
};

// node_modules/d3-format/src/identity.js
function identity_default(x2) {
  return x2;
}

// node_modules/d3-format/src/locale.js
var map = Array.prototype.map;
var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
function locale_default(locale4) {
  var group2 = locale4.grouping === void 0 || locale4.thousands === void 0 ? identity_default : formatGroup_default(map.call(locale4.grouping, Number), locale4.thousands + ""), currencyPrefix = locale4.currency === void 0 ? "" : locale4.currency[0] + "", currencySuffix = locale4.currency === void 0 ? "" : locale4.currency[1] + "", decimal2 = locale4.decimal === void 0 ? "." : locale4.decimal + "", numerals = locale4.numerals === void 0 ? identity_default : formatNumerals_default(map.call(locale4.numerals, String)), percent = locale4.percent === void 0 ? "%" : locale4.percent + "", minus = locale4.minus === void 0 ? "\u2212" : locale4.minus + "", nan = locale4.nan === void 0 ? "NaN" : locale4.nan + "";
  function newFormat(specifier) {
    specifier = formatSpecifier(specifier);
    var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero3 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type;
    if (type === "n") comma = true, type = "g";
    else if (!formatTypes_default[type]) precision === void 0 && (precision = 12), trim = true, type = "g";
    if (zero3 || fill === "0" && align === "=") zero3 = true, fill = "0", align = "=";
    var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
    var formatType = formatTypes_default[type], maybeSuffix = /[defgprs%]/.test(type);
    precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
    function format3(value) {
      var valuePrefix = prefix, valueSuffix = suffix, i2, n, c;
      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;
        var valueNegative = value < 0 || 1 / value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
        if (trim) value = formatTrim_default(value);
        if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
        valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
        if (maybeSuffix) {
          i2 = -1, n = value.length;
          while (++i2 < n) {
            if (c = value.charCodeAt(i2), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal2 + value.slice(i2 + 1) : value.slice(i2)) + valueSuffix;
              value = value.slice(0, i2);
              break;
            }
          }
        }
      }
      if (comma && !zero3) value = group2(value, Infinity);
      var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
      if (comma && zero3) value = group2(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
      switch (align) {
        case "<":
          value = valuePrefix + value + valueSuffix + padding;
          break;
        case "=":
          value = valuePrefix + padding + value + valueSuffix;
          break;
        case "^":
          value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
          break;
        default:
          value = padding + valuePrefix + value + valueSuffix;
          break;
      }
      return numerals(value);
    }
    format3.toString = function() {
      return specifier + "";
    };
    return format3;
  }
  function formatPrefix2(specifier, value) {
    var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3];
    return function(value2) {
      return f(k * value2) + prefix;
    };
  }
  return {
    format: newFormat,
    formatPrefix: formatPrefix2
  };
}

// node_modules/d3-format/src/defaultLocale.js
var locale2;
var format2;
var formatPrefix;
defaultLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
function defaultLocale(definition) {
  locale2 = locale_default(definition);
  format2 = locale2.format;
  formatPrefix = locale2.formatPrefix;
  return locale2;
}

// node_modules/d3-format/src/precisionFixed.js
function precisionFixed_default(step) {
  return Math.max(0, -exponent_default(Math.abs(step)));
}

// node_modules/d3-format/src/precisionPrefix.js
function precisionPrefix_default(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3 - exponent_default(Math.abs(step)));
}

// node_modules/d3-format/src/precisionRound.js
function precisionRound_default(step, max3) {
  step = Math.abs(step), max3 = Math.abs(max3) - step;
  return Math.max(0, exponent_default(max3) - exponent_default(step)) + 1;
}

// node_modules/d3-time/src/interval.js
var t0 = /* @__PURE__ */ new Date();
var t1 = /* @__PURE__ */ new Date();
function timeInterval(floori, offseti, count2, field) {
  function interval2(date4) {
    return floori(date4 = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date4)), date4;
  }
  interval2.floor = (date4) => {
    return floori(date4 = /* @__PURE__ */ new Date(+date4)), date4;
  };
  interval2.ceil = (date4) => {
    return floori(date4 = new Date(date4 - 1)), offseti(date4, 1), floori(date4), date4;
  };
  interval2.round = (date4) => {
    const d0 = interval2(date4), d1 = interval2.ceil(date4);
    return date4 - d0 < d1 - date4 ? d0 : d1;
  };
  interval2.offset = (date4, step) => {
    return offseti(date4 = /* @__PURE__ */ new Date(+date4), step == null ? 1 : Math.floor(step)), date4;
  };
  interval2.range = (start2, stop2, step) => {
    const range2 = [];
    start2 = interval2.ceil(start2);
    step = step == null ? 1 : Math.floor(step);
    if (!(start2 < stop2) || !(step > 0)) return range2;
    let previous;
    do
      range2.push(previous = /* @__PURE__ */ new Date(+start2)), offseti(start2, step), floori(start2);
    while (previous < start2 && start2 < stop2);
    return range2;
  };
  interval2.filter = (test) => {
    return timeInterval((date4) => {
      if (date4 >= date4) while (floori(date4), !test(date4)) date4.setTime(date4 - 1);
    }, (date4, step) => {
      if (date4 >= date4) {
        if (step < 0) while (++step <= 0) {
          while (offseti(date4, -1), !test(date4)) {
          }
        }
        else while (--step >= 0) {
          while (offseti(date4, 1), !test(date4)) {
          }
        }
      }
    });
  };
  if (count2) {
    interval2.count = (start2, end) => {
      t0.setTime(+start2), t1.setTime(+end);
      floori(t0), floori(t1);
      return Math.floor(count2(t0, t1));
    };
    interval2.every = (step) => {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval2 : interval2.filter(field ? (d) => field(d) % step === 0 : (d) => interval2.count(0, d) % step === 0);
    };
  }
  return interval2;
}

// node_modules/d3-time/src/millisecond.js
var millisecond = timeInterval(() => {
}, (date4, step) => {
  date4.setTime(+date4 + step);
}, (start2, end) => {
  return end - start2;
});
millisecond.every = (k) => {
  k = Math.floor(k);
  if (!isFinite(k) || !(k > 0)) return null;
  if (!(k > 1)) return millisecond;
  return timeInterval((date4) => {
    date4.setTime(Math.floor(date4 / k) * k);
  }, (date4, step) => {
    date4.setTime(+date4 + step * k);
  }, (start2, end) => {
    return (end - start2) / k;
  });
};
var milliseconds = millisecond.range;

// node_modules/d3-time/src/duration.js
var durationSecond = 1e3;
var durationMinute = durationSecond * 60;
var durationHour = durationMinute * 60;
var durationDay = durationHour * 24;
var durationWeek = durationDay * 7;
var durationMonth = durationDay * 30;
var durationYear = durationDay * 365;

// node_modules/d3-time/src/second.js
var second = timeInterval((date4) => {
  date4.setTime(date4 - date4.getMilliseconds());
}, (date4, step) => {
  date4.setTime(+date4 + step * durationSecond);
}, (start2, end) => {
  return (end - start2) / durationSecond;
}, (date4) => {
  return date4.getUTCSeconds();
});
var seconds = second.range;

// node_modules/d3-time/src/minute.js
var timeMinute = timeInterval((date4) => {
  date4.setTime(date4 - date4.getMilliseconds() - date4.getSeconds() * durationSecond);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationMinute);
}, (start2, end) => {
  return (end - start2) / durationMinute;
}, (date4) => {
  return date4.getMinutes();
});
var timeMinutes = timeMinute.range;
var utcMinute = timeInterval((date4) => {
  date4.setUTCSeconds(0, 0);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationMinute);
}, (start2, end) => {
  return (end - start2) / durationMinute;
}, (date4) => {
  return date4.getUTCMinutes();
});
var utcMinutes = utcMinute.range;

// node_modules/d3-time/src/hour.js
var timeHour = timeInterval((date4) => {
  date4.setTime(date4 - date4.getMilliseconds() - date4.getSeconds() * durationSecond - date4.getMinutes() * durationMinute);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationHour);
}, (start2, end) => {
  return (end - start2) / durationHour;
}, (date4) => {
  return date4.getHours();
});
var timeHours = timeHour.range;
var utcHour = timeInterval((date4) => {
  date4.setUTCMinutes(0, 0, 0);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationHour);
}, (start2, end) => {
  return (end - start2) / durationHour;
}, (date4) => {
  return date4.getUTCHours();
});
var utcHours = utcHour.range;

// node_modules/d3-time/src/day.js
var timeDay = timeInterval(
  (date4) => date4.setHours(0, 0, 0, 0),
  (date4, step) => date4.setDate(date4.getDate() + step),
  (start2, end) => (end - start2 - (end.getTimezoneOffset() - start2.getTimezoneOffset()) * durationMinute) / durationDay,
  (date4) => date4.getDate() - 1
);
var timeDays = timeDay.range;
var utcDay = timeInterval((date4) => {
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCDate(date4.getUTCDate() + step);
}, (start2, end) => {
  return (end - start2) / durationDay;
}, (date4) => {
  return date4.getUTCDate() - 1;
});
var utcDays = utcDay.range;
var unixDay = timeInterval((date4) => {
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCDate(date4.getUTCDate() + step);
}, (start2, end) => {
  return (end - start2) / durationDay;
}, (date4) => {
  return Math.floor(date4 / durationDay);
});
var unixDays = unixDay.range;

// node_modules/d3-time/src/week.js
function timeWeekday(i2) {
  return timeInterval((date4) => {
    date4.setDate(date4.getDate() - (date4.getDay() + 7 - i2) % 7);
    date4.setHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setDate(date4.getDate() + step * 7);
  }, (start2, end) => {
    return (end - start2 - (end.getTimezoneOffset() - start2.getTimezoneOffset()) * durationMinute) / durationWeek;
  });
}
var timeSunday = timeWeekday(0);
var timeMonday = timeWeekday(1);
var timeTuesday = timeWeekday(2);
var timeWednesday = timeWeekday(3);
var timeThursday = timeWeekday(4);
var timeFriday = timeWeekday(5);
var timeSaturday = timeWeekday(6);
var timeSundays = timeSunday.range;
var timeMondays = timeMonday.range;
var timeTuesdays = timeTuesday.range;
var timeWednesdays = timeWednesday.range;
var timeThursdays = timeThursday.range;
var timeFridays = timeFriday.range;
var timeSaturdays = timeSaturday.range;
function utcWeekday(i2) {
  return timeInterval((date4) => {
    date4.setUTCDate(date4.getUTCDate() - (date4.getUTCDay() + 7 - i2) % 7);
    date4.setUTCHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setUTCDate(date4.getUTCDate() + step * 7);
  }, (start2, end) => {
    return (end - start2) / durationWeek;
  });
}
var utcSunday = utcWeekday(0);
var utcMonday = utcWeekday(1);
var utcTuesday = utcWeekday(2);
var utcWednesday = utcWeekday(3);
var utcThursday = utcWeekday(4);
var utcFriday = utcWeekday(5);
var utcSaturday = utcWeekday(6);
var utcSundays = utcSunday.range;
var utcMondays = utcMonday.range;
var utcTuesdays = utcTuesday.range;
var utcWednesdays = utcWednesday.range;
var utcThursdays = utcThursday.range;
var utcFridays = utcFriday.range;
var utcSaturdays = utcSaturday.range;

// node_modules/d3-time/src/month.js
var timeMonth = timeInterval((date4) => {
  date4.setDate(1);
  date4.setHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setMonth(date4.getMonth() + step);
}, (start2, end) => {
  return end.getMonth() - start2.getMonth() + (end.getFullYear() - start2.getFullYear()) * 12;
}, (date4) => {
  return date4.getMonth();
});
var timeMonths = timeMonth.range;
var utcMonth = timeInterval((date4) => {
  date4.setUTCDate(1);
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCMonth(date4.getUTCMonth() + step);
}, (start2, end) => {
  return end.getUTCMonth() - start2.getUTCMonth() + (end.getUTCFullYear() - start2.getUTCFullYear()) * 12;
}, (date4) => {
  return date4.getUTCMonth();
});
var utcMonths = utcMonth.range;

// node_modules/d3-time/src/year.js
var timeYear = timeInterval((date4) => {
  date4.setMonth(0, 1);
  date4.setHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setFullYear(date4.getFullYear() + step);
}, (start2, end) => {
  return end.getFullYear() - start2.getFullYear();
}, (date4) => {
  return date4.getFullYear();
});
timeYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date4) => {
    date4.setFullYear(Math.floor(date4.getFullYear() / k) * k);
    date4.setMonth(0, 1);
    date4.setHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setFullYear(date4.getFullYear() + step * k);
  });
};
var timeYears = timeYear.range;
var utcYear = timeInterval((date4) => {
  date4.setUTCMonth(0, 1);
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCFullYear(date4.getUTCFullYear() + step);
}, (start2, end) => {
  return end.getUTCFullYear() - start2.getUTCFullYear();
}, (date4) => {
  return date4.getUTCFullYear();
});
utcYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date4) => {
    date4.setUTCFullYear(Math.floor(date4.getUTCFullYear() / k) * k);
    date4.setUTCMonth(0, 1);
    date4.setUTCHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setUTCFullYear(date4.getUTCFullYear() + step * k);
  });
};
var utcYears = utcYear.range;

// node_modules/d3-time/src/ticks.js
function ticker(year, month, week, day2, hour, minute) {
  const tickIntervals = [
    [second, 1, durationSecond],
    [second, 5, 5 * durationSecond],
    [second, 15, 15 * durationSecond],
    [second, 30, 30 * durationSecond],
    [minute, 1, durationMinute],
    [minute, 5, 5 * durationMinute],
    [minute, 15, 15 * durationMinute],
    [minute, 30, 30 * durationMinute],
    [hour, 1, durationHour],
    [hour, 3, 3 * durationHour],
    [hour, 6, 6 * durationHour],
    [hour, 12, 12 * durationHour],
    [day2, 1, durationDay],
    [day2, 2, 2 * durationDay],
    [week, 1, durationWeek],
    [month, 1, durationMonth],
    [month, 3, 3 * durationMonth],
    [year, 1, durationYear]
  ];
  function ticks2(start2, stop2, count2) {
    const reverse = stop2 < start2;
    if (reverse) [start2, stop2] = [stop2, start2];
    const interval2 = count2 && typeof count2.range === "function" ? count2 : tickInterval(start2, stop2, count2);
    const ticks3 = interval2 ? interval2.range(start2, +stop2 + 1) : [];
    return reverse ? ticks3.reverse() : ticks3;
  }
  function tickInterval(start2, stop2, count2) {
    const target = Math.abs(stop2 - start2) / count2;
    const i2 = bisector(([, , step2]) => step2).right(tickIntervals, target);
    if (i2 === tickIntervals.length) return year.every(tickStep(start2 / durationYear, stop2 / durationYear, count2));
    if (i2 === 0) return millisecond.every(Math.max(tickStep(start2, stop2, count2), 1));
    const [t4, step] = tickIntervals[target / tickIntervals[i2 - 1][2] < tickIntervals[i2][2] / target ? i2 - 1 : i2];
    return t4.every(step);
  }
  return [ticks2, tickInterval];
}
var [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcSunday, unixDay, utcHour, utcMinute);
var [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute);

// node_modules/d3-time-format/src/locale.js
function localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date4 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date4.setFullYear(d.y);
    return date4;
  }
  return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date4 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date4.setUTCFullYear(d.y);
    return date4;
  }
  return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y2, m2, d) {
  return { y: y2, m: m2, d, H: 0, M: 0, S: 0, L: 0 };
}
function formatLocale(locale4) {
  var locale_dateTime = locale4.dateTime, locale_date = locale4.date, locale_time = locale4.time, locale_periods = locale4.periods, locale_weekdays = locale4.days, locale_shortWeekdays = locale4.shortDays, locale_months = locale4.months, locale_shortMonths = locale4.shortMonths;
  var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths);
  var formats = {
    "a": formatShortWeekday,
    "A": formatWeekday,
    "b": formatShortMonth,
    "B": formatMonth,
    "c": null,
    "d": formatDayOfMonth,
    "e": formatDayOfMonth,
    "f": formatMicroseconds,
    "g": formatYearISO,
    "G": formatFullYearISO,
    "H": formatHour24,
    "I": formatHour12,
    "j": formatDayOfYear,
    "L": formatMilliseconds,
    "m": formatMonthNumber,
    "M": formatMinutes,
    "p": formatPeriod,
    "q": formatQuarter,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatSeconds,
    "u": formatWeekdayNumberMonday,
    "U": formatWeekNumberSunday,
    "V": formatWeekNumberISO,
    "w": formatWeekdayNumberSunday,
    "W": formatWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatYear,
    "Y": formatFullYear,
    "Z": formatZone,
    "%": formatLiteralPercent
  };
  var utcFormats = {
    "a": formatUTCShortWeekday,
    "A": formatUTCWeekday,
    "b": formatUTCShortMonth,
    "B": formatUTCMonth,
    "c": null,
    "d": formatUTCDayOfMonth,
    "e": formatUTCDayOfMonth,
    "f": formatUTCMicroseconds,
    "g": formatUTCYearISO,
    "G": formatUTCFullYearISO,
    "H": formatUTCHour24,
    "I": formatUTCHour12,
    "j": formatUTCDayOfYear,
    "L": formatUTCMilliseconds,
    "m": formatUTCMonthNumber,
    "M": formatUTCMinutes,
    "p": formatUTCPeriod,
    "q": formatUTCQuarter,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatUTCSeconds,
    "u": formatUTCWeekdayNumberMonday,
    "U": formatUTCWeekNumberSunday,
    "V": formatUTCWeekNumberISO,
    "w": formatUTCWeekdayNumberSunday,
    "W": formatUTCWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatUTCYear,
    "Y": formatUTCFullYear,
    "Z": formatUTCZone,
    "%": formatLiteralPercent
  };
  var parses = {
    "a": parseShortWeekday,
    "A": parseWeekday,
    "b": parseShortMonth,
    "B": parseMonth,
    "c": parseLocaleDateTime,
    "d": parseDayOfMonth,
    "e": parseDayOfMonth,
    "f": parseMicroseconds,
    "g": parseYear,
    "G": parseFullYear,
    "H": parseHour24,
    "I": parseHour24,
    "j": parseDayOfYear,
    "L": parseMilliseconds,
    "m": parseMonthNumber,
    "M": parseMinutes,
    "p": parsePeriod,
    "q": parseQuarter,
    "Q": parseUnixTimestamp,
    "s": parseUnixTimestampSeconds,
    "S": parseSeconds,
    "u": parseWeekdayNumberMonday,
    "U": parseWeekNumberSunday,
    "V": parseWeekNumberISO,
    "w": parseWeekdayNumberSunday,
    "W": parseWeekNumberMonday,
    "x": parseLocaleDate,
    "X": parseLocaleTime,
    "y": parseYear,
    "Y": parseFullYear,
    "Z": parseZone,
    "%": parseLiteralPercent
  };
  formats.x = newFormat(locale_date, formats);
  formats.X = newFormat(locale_time, formats);
  formats.c = newFormat(locale_dateTime, formats);
  utcFormats.x = newFormat(locale_date, utcFormats);
  utcFormats.X = newFormat(locale_time, utcFormats);
  utcFormats.c = newFormat(locale_dateTime, utcFormats);
  function newFormat(specifier, formats2) {
    return function(date4) {
      var string4 = [], i2 = -1, j = 0, n = specifier.length, c, pad2, format3;
      if (!(date4 instanceof Date)) date4 = /* @__PURE__ */ new Date(+date4);
      while (++i2 < n) {
        if (specifier.charCodeAt(i2) === 37) {
          string4.push(specifier.slice(j, i2));
          if ((pad2 = pads[c = specifier.charAt(++i2)]) != null) c = specifier.charAt(++i2);
          else pad2 = c === "e" ? " " : "0";
          if (format3 = formats2[c]) c = format3(date4, pad2);
          string4.push(c);
          j = i2 + 1;
        }
      }
      string4.push(specifier.slice(j, i2));
      return string4.join("");
    };
  }
  function newParse(specifier, Z) {
    return function(string4) {
      var d = newDate(1900, void 0, 1), i2 = parseSpecifier(d, specifier, string4 += "", 0), week, day2;
      if (i2 != string4.length) return null;
      if ("Q" in d) return new Date(d.Q);
      if ("s" in d) return new Date(d.s * 1e3 + ("L" in d ? d.L : 0));
      if (Z && !("Z" in d)) d.Z = 0;
      if ("p" in d) d.H = d.H % 12 + d.p * 12;
      if (d.m === void 0) d.m = "q" in d ? d.q : 0;
      if ("V" in d) {
        if (d.V < 1 || d.V > 53) return null;
        if (!("w" in d)) d.w = 1;
        if ("Z" in d) {
          week = utcDate(newDate(d.y, 0, 1)), day2 = week.getUTCDay();
          week = day2 > 4 || day2 === 0 ? utcMonday.ceil(week) : utcMonday(week);
          week = utcDay.offset(week, (d.V - 1) * 7);
          d.y = week.getUTCFullYear();
          d.m = week.getUTCMonth();
          d.d = week.getUTCDate() + (d.w + 6) % 7;
        } else {
          week = localDate(newDate(d.y, 0, 1)), day2 = week.getDay();
          week = day2 > 4 || day2 === 0 ? timeMonday.ceil(week) : timeMonday(week);
          week = timeDay.offset(week, (d.V - 1) * 7);
          d.y = week.getFullYear();
          d.m = week.getMonth();
          d.d = week.getDate() + (d.w + 6) % 7;
        }
      } else if ("W" in d || "U" in d) {
        if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
        day2 = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();
        d.m = 0;
        d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day2 + 5) % 7 : d.w + d.U * 7 - (day2 + 6) % 7;
      }
      if ("Z" in d) {
        d.H += d.Z / 100 | 0;
        d.M += d.Z % 100;
        return utcDate(d);
      }
      return localDate(d);
    };
  }
  function parseSpecifier(d, specifier, string4, j) {
    var i2 = 0, n = specifier.length, m2 = string4.length, c, parse;
    while (i2 < n) {
      if (j >= m2) return -1;
      c = specifier.charCodeAt(i2++);
      if (c === 37) {
        c = specifier.charAt(i2++);
        parse = parses[c in pads ? specifier.charAt(i2++) : c];
        if (!parse || (j = parse(d, string4, j)) < 0) return -1;
      } else if (c != string4.charCodeAt(j++)) {
        return -1;
      }
    }
    return j;
  }
  function parsePeriod(d, string4, i2) {
    var n = periodRe.exec(string4.slice(i2));
    return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i2 + n[0].length) : -1;
  }
  function parseShortWeekday(d, string4, i2) {
    var n = shortWeekdayRe.exec(string4.slice(i2));
    return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i2 + n[0].length) : -1;
  }
  function parseWeekday(d, string4, i2) {
    var n = weekdayRe.exec(string4.slice(i2));
    return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i2 + n[0].length) : -1;
  }
  function parseShortMonth(d, string4, i2) {
    var n = shortMonthRe.exec(string4.slice(i2));
    return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i2 + n[0].length) : -1;
  }
  function parseMonth(d, string4, i2) {
    var n = monthRe.exec(string4.slice(i2));
    return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i2 + n[0].length) : -1;
  }
  function parseLocaleDateTime(d, string4, i2) {
    return parseSpecifier(d, locale_dateTime, string4, i2);
  }
  function parseLocaleDate(d, string4, i2) {
    return parseSpecifier(d, locale_date, string4, i2);
  }
  function parseLocaleTime(d, string4, i2) {
    return parseSpecifier(d, locale_time, string4, i2);
  }
  function formatShortWeekday(d) {
    return locale_shortWeekdays[d.getDay()];
  }
  function formatWeekday(d) {
    return locale_weekdays[d.getDay()];
  }
  function formatShortMonth(d) {
    return locale_shortMonths[d.getMonth()];
  }
  function formatMonth(d) {
    return locale_months[d.getMonth()];
  }
  function formatPeriod(d) {
    return locale_periods[+(d.getHours() >= 12)];
  }
  function formatQuarter(d) {
    return 1 + ~~(d.getMonth() / 3);
  }
  function formatUTCShortWeekday(d) {
    return locale_shortWeekdays[d.getUTCDay()];
  }
  function formatUTCWeekday(d) {
    return locale_weekdays[d.getUTCDay()];
  }
  function formatUTCShortMonth(d) {
    return locale_shortMonths[d.getUTCMonth()];
  }
  function formatUTCMonth(d) {
    return locale_months[d.getUTCMonth()];
  }
  function formatUTCPeriod(d) {
    return locale_periods[+(d.getUTCHours() >= 12)];
  }
  function formatUTCQuarter(d) {
    return 1 + ~~(d.getUTCMonth() / 3);
  }
  return {
    format: function(specifier) {
      var f = newFormat(specifier += "", formats);
      f.toString = function() {
        return specifier;
      };
      return f;
    },
    parse: function(specifier) {
      var p = newParse(specifier += "", false);
      p.toString = function() {
        return specifier;
      };
      return p;
    },
    utcFormat: function(specifier) {
      var f = newFormat(specifier += "", utcFormats);
      f.toString = function() {
        return specifier;
      };
      return f;
    },
    utcParse: function(specifier) {
      var p = newParse(specifier += "", true);
      p.toString = function() {
        return specifier;
      };
      return p;
    }
  };
}
var pads = { "-": "", "_": " ", "0": "0" };
var numberRe = /^\s*\d+/;
var percentRe = /^%/;
var requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
  var sign = value < 0 ? "-" : "", string4 = (sign ? -value : value) + "", length = string4.length;
  return sign + (length < width ? new Array(width - length + 1).join(fill) + string4 : string4);
}
function requote(s) {
  return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
  return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
  return new Map(names.map((name3, i2) => [name3.toLowerCase(), i2]));
}
function parseWeekdayNumberSunday(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 1));
  return n ? (d.w = +n[0], i2 + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 1));
  return n ? (d.u = +n[0], i2 + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.U = +n[0], i2 + n[0].length) : -1;
}
function parseWeekNumberISO(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.V = +n[0], i2 + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.W = +n[0], i2 + n[0].length) : -1;
}
function parseFullYear(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 4));
  return n ? (d.y = +n[0], i2 + n[0].length) : -1;
}
function parseYear(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i2 + n[0].length) : -1;
}
function parseZone(d, string4, i2) {
  var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string4.slice(i2, i2 + 6));
  return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i2 + n[0].length) : -1;
}
function parseQuarter(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 1));
  return n ? (d.q = n[0] * 3 - 3, i2 + n[0].length) : -1;
}
function parseMonthNumber(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.m = n[0] - 1, i2 + n[0].length) : -1;
}
function parseDayOfMonth(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.d = +n[0], i2 + n[0].length) : -1;
}
function parseDayOfYear(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 3));
  return n ? (d.m = 0, d.d = +n[0], i2 + n[0].length) : -1;
}
function parseHour24(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.H = +n[0], i2 + n[0].length) : -1;
}
function parseMinutes(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.M = +n[0], i2 + n[0].length) : -1;
}
function parseSeconds(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 2));
  return n ? (d.S = +n[0], i2 + n[0].length) : -1;
}
function parseMilliseconds(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 3));
  return n ? (d.L = +n[0], i2 + n[0].length) : -1;
}
function parseMicroseconds(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2, i2 + 6));
  return n ? (d.L = Math.floor(n[0] / 1e3), i2 + n[0].length) : -1;
}
function parseLiteralPercent(d, string4, i2) {
  var n = percentRe.exec(string4.slice(i2, i2 + 1));
  return n ? i2 + n[0].length : -1;
}
function parseUnixTimestamp(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2));
  return n ? (d.Q = +n[0], i2 + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string4, i2) {
  var n = numberRe.exec(string4.slice(i2));
  return n ? (d.s = +n[0], i2 + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
  return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
  return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
  return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
  return pad(1 + timeDay.count(timeYear(d), d), p, 3);
}
function formatMilliseconds(d, p) {
  return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
  return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
  return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
  return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
  return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
  var day2 = d.getDay();
  return day2 === 0 ? 7 : day2;
}
function formatWeekNumberSunday(d, p) {
  return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);
}
function dISO(d) {
  var day2 = d.getDay();
  return day2 >= 4 || day2 === 0 ? timeThursday(d) : timeThursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
  d = dISO(d);
  return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);
}
function formatWeekdayNumberSunday(d) {
  return d.getDay();
}
function formatWeekNumberMonday(d, p) {
  return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);
}
function formatYear(d, p) {
  return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
  d = dISO(d);
  return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatFullYearISO(d, p) {
  var day2 = d.getDay();
  d = day2 >= 4 || day2 === 0 ? timeThursday(d) : timeThursday.ceil(d);
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatZone(d) {
  var z = d.getTimezoneOffset();
  return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
  return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
  return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
  return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
  return pad(1 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
  return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
  return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
  return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
  return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
  return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
  var dow = d.getUTCDay();
  return dow === 0 ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
  return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
  var day2 = d.getUTCDay();
  return day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
  d = UTCdISO(d);
  return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
  return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
  d = UTCdISO(d);
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
  return pad(d.getUTCFullYear() % 1e4, p, 4);
}
function formatUTCFullYearISO(d, p) {
  var day2 = d.getUTCDay();
  d = day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d);
  return pad(d.getUTCFullYear() % 1e4, p, 4);
}
function formatUTCZone() {
  return "+0000";
}
function formatLiteralPercent() {
  return "%";
}
function formatUnixTimestamp(d) {
  return +d;
}
function formatUnixTimestampSeconds(d) {
  return Math.floor(+d / 1e3);
}

// node_modules/d3-time-format/src/defaultLocale.js
var locale3;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;
defaultLocale2({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
function defaultLocale2(definition) {
  locale3 = formatLocale(definition);
  timeFormat = locale3.format;
  timeParse = locale3.parse;
  utcFormat = locale3.utcFormat;
  utcParse = locale3.utcParse;
  return locale3;
}

// src/format.ts
function localeFormatter(locale4, precision = 2) {
  if (locale4 == null) {
    return format2(`.${precision.toString()}f`);
  }
  const digits = Math.max(0, Math.min(precision, 20));
  const fmt = new Intl.NumberFormat(locale4.replace("_", "-"), {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits
  });
  return fmt.format.bind(fmt);
}
var formatterPer = format2(".2f");
function formatPercentage(number7) {
  return `${formatterPer(Math.abs(number7) * 100)}%`;
}
var replaceNumbers = (num2) => num2.replace(/[0-9]/g, "X");
function formatter_context(incognito2, locale4, precisions2) {
  const formatter = localeFormatter(locale4);
  const currencyFormatters = Object.fromEntries(
    Object.entries(precisions2).map(([currency, prec2]) => [
      currency,
      localeFormatter(locale4, prec2)
    ])
  );
  const num_raw = (n, c) => (currencyFormatters[c] ?? formatter)(n);
  const num2 = incognito2 ? (n, c) => replaceNumbers(num_raw(n, c)) : num_raw;
  return {
    amount: (n, c) => `${num2(n, c)} ${c}`,
    num: num2
  };
}
var day = utcFormat("%Y-%m-%d");
var dateFormat = {
  year: utcFormat("%Y"),
  quarter: (date4) => `${date4.getUTCFullYear().toString()}Q${(Math.floor(date4.getUTCMonth() / 3) + 1).toString()}`,
  month: utcFormat("%b %Y"),
  week: utcFormat("%GW%V"),
  day
};
var timeFilterDateFormat = {
  year: utcFormat("%Y"),
  quarter: (date4) => `${date4.getUTCFullYear().toString()}-Q${(Math.floor(date4.getUTCMonth() / 3) + 1).toString()}`,
  month: utcFormat("%Y-%m"),
  week: utcFormat("%G-W%V"),
  day
};
var local_day = timeFormat("%Y-%m-%d");
function todayAsString() {
  return local_day(/* @__PURE__ */ new Date());
}

// src/entries/cost.ts
var Cost = class _Cost {
  constructor(number7, currency, date4, label) {
    this.number = number7;
    this.currency = currency;
    this.date = date4;
    this.label = label;
  }
  /** Render to a string. */
  str($ctx) {
    const strs = [$ctx.amount(this.number, this.currency)];
    if (this.date) {
      strs.push(day(this.date));
    }
    if (this.label != null && this.label) {
      strs.push(`"${this.label}"`);
    }
    return strs.join(", ");
  }
  static raw_validator = object({
    number,
    currency: string,
    date: optional(date),
    label: optional_string
  });
  static validator = (json) => _Cost.raw_validator(json).map(
    ({ number: number7, currency, date: date4, label }) => new _Cost(number7, currency, date4, label)
  );
};

// src/lib/objects.ts
function is_empty(obj) {
  return Object.keys(obj).length === 0;
}

// src/entries/metadata.ts
var entry_meta_item = (json) => {
  if (typeof json == "boolean" || typeof json == "number" || typeof json == "string") {
    return ok(json);
  }
  return ok("Unsupported metadata value");
};
function meta_value_to_string(value) {
  if (typeof value === "boolean") {
    return value ? "TRUE" : "FALSE";
  }
  return typeof value === "string" ? value : value.toString();
}
function string_to_meta_value(s) {
  if (s === "TRUE") {
    return true;
  }
  if (s === "FALSE") {
    return false;
  }
  return s;
}
var EntryMetadata = class _EntryMetadata {
  #meta;
  constructor(meta2) {
    this.#meta = meta2 ?? {};
  }
  /** Whether the metadata is empty. */
  is_empty() {
    return is_empty(this.#meta);
  }
  /** Get the filename, falling back to an empty string if missing. */
  get filename() {
    return this.#meta.filename?.toString() ?? "";
  }
  /** Get the line number as a string, falling back to an empty string if missing. */
  get lineno() {
    return this.#meta.lineno?.toString() ?? "";
  }
  toJSON() {
    return this.#meta;
  }
  /** Delete a key from the metadata and return an updated copy. */
  delete(key2) {
    const { [key2]: ignored, ...rest } = this.#meta;
    return new _EntryMetadata(rest);
  }
  /** All metadata entries (values as strings), filtering out hidden ones. */
  entries() {
    return Object.entries(this.#meta).filter(
      ([key2]) => !key2.startsWith("_") && key2 !== "filename" && key2 !== "lineno"
    ).map(([key2, value]) => [key2, meta_value_to_string(value)]);
  }
  /** Get the value for a key. */
  get(key2) {
    return this.#meta[key2];
  }
  /** Set the value for a key and return an updated copy. */
  set(key2, value) {
    return new _EntryMetadata({ ...this.#meta, [key2]: value });
  }
  /** Set the value for a key from a string and return an updated copy. */
  set_string(key2, value) {
    return this.set(key2, string_to_meta_value(value));
  }
  /** Add a new empty key and value and return an updated copy. */
  add() {
    return this.set("", "");
  }
  /** Change a key and a return an updated copy. */
  update_key(current_key, new_key) {
    return new _EntryMetadata(
      Object.fromEntries(
        Object.entries(this.#meta).map(([key2, value]) => [
          key2 === current_key ? new_key : key2,
          value
        ])
      )
    );
  }
  static raw_validator = record(entry_meta_item);
  static validator = (json) => _EntryMetadata.raw_validator(json).map((meta2) => new _EntryMetadata(meta2));
};

// src/entries/position.ts
var Position = class _Position {
  constructor(units, cost) {
    this.units = units;
    this.cost = cost;
  }
  static raw_validator = object({
    units: Amount.validator,
    cost: optional(Cost.validator)
  });
  static validator = (json) => _Position.raw_validator(json).map(
    ({ units, cost }) => new _Position(units, cost)
  );
};

// src/entries/index.ts
var Posting = class _Posting {
  constructor(meta2, account2, amount) {
    this.meta = meta2;
    this.account = account2;
    this.amount = amount;
  }
  /** Create a new empty Posting. */
  static empty() {
    return new _Posting(new EntryMetadata(), "", "");
  }
  is_empty() {
    return !this.account && !this.amount && this.meta.is_empty();
  }
  /** Set a property and return an updated copy. */
  set(key2, value) {
    const copy2 = new _Posting(this.meta, this.account, this.amount);
    copy2[key2] = value;
    return copy2;
  }
  static raw_validator = object({
    meta: defaultValue(EntryMetadata.validator, () => new EntryMetadata()),
    account: string,
    amount: string
  });
  static validator = (json) => _Posting.raw_validator(json).map(
    ({ meta: meta2, account: account2, amount }) => new _Posting(meta2, account2, amount)
  );
};
var entryBaseValidator = object({
  t: string,
  meta: EntryMetadata.validator,
  date: string
});
var EntryBase = class {
  constructor(t4, meta2, date4) {
    this.t = t4;
    this.meta = meta2;
    this.date = date4;
  }
  /** Clone. */
  clone() {
    const copy2 = Object.assign(
      // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
      Object.create(Object.getPrototypeOf(this)),
      this
    );
    return copy2;
  }
  /** Set a property and return an updated copy. */
  set(key2, value) {
    const copy2 = this.clone();
    copy2[key2] = value;
    return copy2;
  }
  /** Set the value for a key and return an updated copy. */
  set_meta(key2, value) {
    const copy2 = this.clone();
    copy2.meta = this.meta.set(key2, value);
    return copy2;
  }
  /** Check whether the given entry is marked as duplicate (used in imports). */
  is_duplicate() {
    const value = this.meta.get("__duplicate__");
    return value != null && value !== false;
  }
};
var Balance = class _Balance extends EntryBase {
  constructor(meta2, date4, account2, amount) {
    super("Balance", meta2, date4);
    this.account = account2;
    this.amount = amount;
  }
  /** Create a new empty Balance entry on the date. */
  static empty(date4) {
    return new _Balance(new EntryMetadata(), date4, "", {
      number: "",
      currency: ""
    });
  }
  static raw_validator = object({
    t: constant("Balance"),
    meta: EntryMetadata.validator,
    date: string,
    account: string,
    amount: object({ number: string, currency: string })
  });
  static validator = (json) => _Balance.raw_validator(json).map(
    ({ date: date4, meta: meta2, account: account2, amount }) => new _Balance(meta2, date4, account2, amount)
  );
};
var Document = class _Document extends EntryBase {
  constructor(meta2, date4, account2, filename) {
    super("Document", meta2, date4);
    this.account = account2;
    this.filename = filename;
  }
  static raw_validator = object({
    t: constant("Document"),
    meta: EntryMetadata.validator,
    date: string,
    account: string,
    filename: string
  });
  static validator = (json) => _Document.raw_validator(json).map(
    ({ date: date4, meta: meta2, account: account2, filename }) => new _Document(meta2, date4, account2, filename)
  );
};
var Event2 = class _Event extends EntryBase {
  constructor(meta2, date4, type, description) {
    super("Event", meta2, date4);
    this.type = type;
    this.description = description;
  }
  static raw_validator = object({
    t: constant("Event"),
    meta: EntryMetadata.validator,
    date: string,
    type: string,
    description: string
  });
  static validator = (json) => _Event.raw_validator(json).map(
    ({ meta: meta2, date: date4, type, description }) => new _Event(meta2, date4, type, description)
  );
};
var Note = class _Note extends EntryBase {
  constructor(meta2, date4, account2, comment3) {
    super("Note", meta2, date4);
    this.account = account2;
    this.comment = comment3;
  }
  /** Create a new empty Note entry on the date. */
  static empty(date4) {
    return new _Note(new EntryMetadata(), date4, "", "");
  }
  static raw_validator = object({
    t: constant("Note"),
    meta: EntryMetadata.validator,
    date: string,
    account: string,
    comment: string
  });
  static validator = (json) => _Note.raw_validator(json).map(
    ({ meta: meta2, date: date4, account: account2, comment: comment3 }) => new _Note(meta2, date4, account2, comment3)
  );
};
var TAGS_RE = /(?:^|\s)#([A-Za-z0-9\-_/.]+)/g;
var LINKS_RE = /(?:^|\s)\^([A-Za-z0-9\-_/.]+)/g;
var Transaction = class _Transaction extends EntryBase {
  constructor(meta2, date4, flag, payee, narration, tags3, links2, postings) {
    super("Transaction", meta2, date4);
    this.flag = flag;
    this.payee = payee;
    this.narration = narration;
    this.tags = tags3;
    this.links = links2;
    this.postings = postings;
  }
  /** Create a new empty Transaction entry on the date. */
  static empty(date4) {
    return new _Transaction(new EntryMetadata(), date4, "*", "", "", [], [], []);
  }
  /** Combine narration, tags, and links for a single `<input>`. */
  get_narration_tags_links() {
    let val = this.narration;
    if (this.tags.length) {
      val += ` ${this.tags.map((t4) => `#${t4}`).join(" ")}`;
    }
    if (this.links.length) {
      val += ` ${this.links.map((t4) => `^${t4}`).join(" ")}`;
    }
    return val;
  }
  /** Set narration, tags, and links from a single string. */
  set_narration_tags_links(value) {
    const tags3 = [...value.matchAll(TAGS_RE)].map((a) => a[1] ?? "");
    const links2 = [...value.matchAll(LINKS_RE)].map((a) => a[1] ?? "");
    const narration = value.replaceAll(TAGS_RE, "").replaceAll(LINKS_RE, "").trim();
    return new _Transaction(
      this.meta,
      this.date,
      this.flag,
      this.payee,
      narration,
      tags3,
      links2,
      this.postings
    );
  }
  toString() {
    const postings = this.postings.map((p) => `  ${p.account}  ${p.amount}`);
    return `${this.date} ${this.flag} "${this.payee}" "${this.narration}"
${postings.join("\n")}`;
  }
  toJSON() {
    return {
      t: this.t,
      meta: this.meta,
      date: this.date,
      flag: this.flag,
      payee: this.payee,
      narration: this.narration,
      tags: this.tags,
      links: this.links,
      postings: this.postings.filter((p) => !p.is_empty())
    };
  }
  static raw_validator = object({
    t: constant("Transaction"),
    meta: EntryMetadata.validator,
    date: string,
    flag: string,
    payee: optional_string,
    narration: optional_string,
    tags: array(string),
    links: array(string),
    postings: array(Posting.validator)
  });
  static validator = (json) => _Transaction.raw_validator(json).map(
    ({ meta: meta2, date: date4, flag, payee, narration, tags: tags3, links: links2, postings }) => new _Transaction(
      meta2,
      date4,
      flag,
      payee,
      narration,
      tags3,
      links2,
      postings
    )
  );
};
var entryValidator = tagged_union("t", {
  Balance: Balance.validator,
  Document: Document.validator,
  Event: Event2.validator,
  Note: Note.validator,
  Transaction: Transaction.validator
});

// src/reports/query/query_table.ts
var query_column_type = constants(
  "bool",
  "date",
  "int",
  "object",
  "set",
  "str",
  "Amount",
  "Decimal",
  "Inventory",
  "Position"
);
var query_type = object({
  dtype: query_column_type,
  name: string
});
var query_table_raw = object({
  types: array(query_type),
  rows: array(array(unknown))
});
var optional_number_record = optional(record(number));
var Inventory = class _Inventory {
  constructor(value) {
    this.value = value;
  }
  static validator = (json) => optional_number_record(json).map((v) => new _Inventory(v ?? {}));
};
var StringSortedQueryColumn = class extends StringColumn {
  constructor(type, index3, validator2, str_value_for_sorting) {
    super(type.name, (row) => str_value_for_sorting(row[index3]));
    this.index = index3;
    this.validator = validator2;
    this.dtype = type.dtype;
  }
  dtype;
};
var NumberSortedQueryColumn = class extends NumberColumn {
  constructor(type, index3, validator2, num_value_for_sorting) {
    super(type.name, (row) => num_value_for_sorting(row[index3]));
    this.index = index3;
    this.validator = validator2;
    this.dtype = type.dtype;
  }
  dtype;
};
function get_query_column(type, index3) {
  switch (type.dtype) {
    case "bool":
      return new StringSortedQueryColumn(
        type,
        index3,
        boolean,
        (v) => v.toString()
      );
    case "date":
      return new NumberSortedQueryColumn(
        type,
        index3,
        optional(date),
        (v) => v == null ? 0 : +v
      );
    case "int":
    case "Decimal":
      return new NumberSortedQueryColumn(
        type,
        index3,
        optional(number),
        (v) => v ?? 0
      );
    case "set":
      return new StringSortedQueryColumn(
        type,
        index3,
        array(string),
        (v) => v.join(",")
      );
    case "object":
    case "str":
      return new StringSortedQueryColumn(
        type,
        index3,
        defaultValue(string, () => ""),
        (v) => v
      );
    case "Amount":
      return new NumberSortedQueryColumn(
        type,
        index3,
        Amount.validator,
        (v) => v.number
      );
    case "Inventory":
      return new NumberSortedQueryColumn(
        type,
        index3,
        Inventory.validator,
        (v) => sum(Object.values(v.value))
      );
    case "Position":
      return new NumberSortedQueryColumn(
        type,
        index3,
        Position.validator,
        (v) => v.units.number
      );
    default:
      return type.dtype;
  }
}
var query_table_validator = (json) => query_table_raw(json).and_then(({ types: types2, rows }) => {
  const columns3 = types2.map(get_query_column);
  const validators = columns3.map((c) => c.validator);
  const parsed_rows = collect(
    rows.map(
      (row) => collect(validators.map((validator2, index3) => validator2(row[index3])))
    )
  );
  return parsed_rows.map((r2) => ({ t: "table", columns: columns3, rows: r2 }));
});
var query_validator = tagged_union("t", {
  string: object({ t: constant("string"), contents: string }),
  table: query_table_validator
});

// src/api/validators.ts
var error_validator = object({
  type: string,
  message: string,
  source: optional(object({ filename: string, lineno: number }))
});
var account_details2 = record(
  object({
    balance_string: optional(string),
    close_date: optional(date),
    last_entry: optional(object({ date, entry_hash: string })),
    uptodate_status: optional(string)
  })
);
var fava_options2 = object({
  auto_reload: boolean,
  currency_column: number,
  conversion_currencies: array(string),
  collapse_pattern: array(string),
  import_config: optional(string),
  indent: number,
  invert_income_liabilities_equity: boolean,
  show_closed_accounts: boolean,
  show_accounts_with_zero_balance: boolean,
  show_accounts_with_zero_transactions: boolean,
  locale: optional(string),
  uptodate_indicator_grey_lookback_days: number,
  insert_entry: array(
    object({ date: string, filename: string, lineno: number, re: string })
  ),
  use_external_editor: boolean
});
var options2 = object({
  documents: array(string),
  filename: string,
  include: array(string),
  name_assets: string,
  name_equity: string,
  name_expenses: string,
  name_income: string,
  name_liabilities: string,
  operating_currency: array(string),
  title: string
});
var extensions2 = array(
  object({
    name: string,
    report_title: optional(string),
    has_js_module: boolean
  })
);
var ledgerDataValidator = object({
  account_details: account_details2,
  accounts: array(string),
  base_url: string,
  currencies: array(string),
  currency_names: record(string),
  errors: array(error_validator),
  extensions: extensions2,
  fava_options: fava_options2,
  have_excel: boolean,
  incognito: boolean,
  links: array(string),
  options: options2,
  other_ledgers: array(tuple(string, string)),
  payees: array(string),
  precisions: record(number),
  sidebar_links: array(tuple(string, string)),
  tags: array(string),
  upcoming_events_count: number,
  user_queries: array(object({ name: string, query_string: string })),
  years: array(string)
});
var importable_files_validator = array(
  object({
    name: string,
    basename: string,
    importers: array(
      object({
        account: string,
        importer_name: string,
        date: string,
        name: string
      })
    )
  })
);
var date_range = object({ begin: date, end: date });
var commodities = array(
  object({ base: string, quote: string, prices: array(tuple(date, number)) })
);
var context = object({
  entry: entryBaseValidator,
  balances_before: optional(record(array(string))),
  balances_after: optional(record(array(string))),
  sha256sum: string,
  slice: string
});
var account_budget = object({
  budget: record(number),
  budget_children: record(number)
});
var source2 = object({
  file_path: string,
  sha256sum: string,
  source: string
});
var tree_report = object({
  charts: unknown,
  trees: array(account_hierarchy_validator),
  date_range: optional(date_range)
});
var getAPIValidators = {
  balance_sheet: tree_report,
  account_report: object({
    charts: unknown,
    journal: optional(string),
    dates: optional(array(date_range)),
    interval_balances: optional(array(account_hierarchy_validator)),
    budgets: optional(record(array(account_budget)))
  }),
  changed: boolean,
  commodities,
  context,
  documents: array(Document.validator),
  errors: array(error_validator),
  events: array(Event2.validator),
  extract: array(entryValidator),
  imports: importable_files_validator,
  income_statement: tree_report,
  ledger_data: ledgerDataValidator,
  move: string,
  options: object({
    fava_options: record(string),
    beancount_options: record(string)
  }),
  payee_accounts: array(string),
  payee_transaction: Transaction.validator,
  query: query_validator,
  source: source2,
  trial_balance: tree_report
};

// src/api/index.ts
var InvalidResponseDataError = class extends Error {
  constructor(cause) {
    super("Invalid data returned in API request.", { cause });
    notify_err(this);
  }
};
async function put(endpoint, body2) {
  const opts2 = body2 instanceof FormData ? { body: body2 } : {
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body2)
  };
  const $urlForRaw = get2(urlForRaw);
  const url = $urlForRaw(`api/${endpoint}`);
  const json = await fetchJSON(url, { method: "PUT", ...opts2 });
  const res2 = string(json);
  if (res2.is_ok) {
    return res2.value;
  }
  throw new InvalidResponseDataError(res2.error);
}
async function get3(endpoint, ...[params]) {
  const $urlForRaw = get2(urlForRaw);
  const url = $urlForRaw(`api/${endpoint}`, params);
  const json = await fetchJSON(url);
  const res2 = getAPIValidators[endpoint](json);
  if (res2.is_ok) {
    return res2.value;
  }
  throw new InvalidResponseDataError(res2.error);
}
async function doDelete(endpoint, params) {
  const $urlForRaw = get2(urlForRaw);
  const url = $urlForRaw(`api/${endpoint}`, params);
  const json = await fetchJSON(url, { method: "DELETE" });
  const res2 = string(json);
  if (res2.is_ok) {
    return res2.value;
  }
  throw new InvalidResponseDataError(res2.error);
}
async function moveDocument(filename, account2, new_name) {
  try {
    const msg = await get3("move", { filename, account: account2, new_name });
    notify(msg);
    return true;
  } catch (error2) {
    notify_err(error2);
    return false;
  }
}
async function deleteDocument(filename) {
  try {
    const msg = await doDelete("document", { filename });
    notify(msg);
    return true;
  } catch (error2) {
    notify_err(error2);
    return false;
  }
}
async function saveEntries(entries) {
  if (!entries.length) {
    return;
  }
  try {
    const data = await put("add_entries", { entries });
    router_default.reload();
    notify(data);
  } catch (error2) {
    notify_err(error2, (e) => `Saving failed: ${e.message}`);
    throw error2;
  }
}

// src/clipboard.ts
var CopyableText = class extends HTMLElement {
  constructor() {
    super();
    this.addEventListener("click", (event2) => {
      const text2 = this.getAttribute("data-clipboard-text");
      if (text2 != null) {
        navigator.clipboard.writeText(text2).catch(log_error);
      }
      event2.stopPropagation();
    });
  }
};

// node_modules/@marijn/find-cluster-break/src/index.js
var rangeFrom = [];
var 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(code) {
  if (code < 768) return false;
  for (let from = 0, to = rangeFrom.length; ; ) {
    let mid = from + to >> 1;
    if (code < rangeFrom[mid]) to = mid;
    else if (code >= rangeTo[mid]) from = mid + 1;
    else return true;
    if (from == to) return false;
  }
}
function isRegionalIndicator(code) {
  return code >= 127462 && code <= 127487;
}
var ZWJ = 8205;
function findClusterBreak(str, pos, forward = true, includeExtending = true) {
  return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
}
function nextClusterBreak(str, pos, includeExtending) {
  if (pos == str.length) return pos;
  if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--;
  let prev = codePointAt(str, pos);
  pos += codePointSize(prev);
  while (pos < str.length) {
    let next2 = codePointAt(str, pos);
    if (prev == ZWJ || next2 == ZWJ || includeExtending && isExtendingChar(next2)) {
      pos += codePointSize(next2);
      prev = next2;
    } else if (isRegionalIndicator(next2)) {
      let countBefore = 0, i2 = pos - 2;
      while (i2 >= 0 && isRegionalIndicator(codePointAt(str, i2))) {
        countBefore++;
        i2 -= 2;
      }
      if (countBefore % 2 == 0) break;
      else pos += 2;
    } else {
      break;
    }
  }
  return pos;
}
function prevClusterBreak(str, pos, includeExtending) {
  while (pos > 0) {
    let found = nextClusterBreak(str, pos - 2, includeExtending);
    if (found < pos) return found;
    pos--;
  }
  return 0;
}
function codePointAt(str, pos) {
  let code0 = str.charCodeAt(pos);
  if (!surrogateHigh(code0) || pos + 1 == str.length) return code0;
  let code1 = str.charCodeAt(pos + 1);
  if (!surrogateLow(code1)) return code0;
  return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
}
function surrogateLow(ch) {
  return ch >= 56320 && ch < 57344;
}
function surrogateHigh(ch) {
  return ch >= 55296 && ch < 56320;
}
function codePointSize(code) {
  return code < 65536 ? 1 : 2;
}

// node_modules/@codemirror/state/dist/index.js
var Text2 = class _Text {
  /**
  Get the line description around the given position.
  */
  lineAt(pos) {
    if (pos < 0 || pos > this.length)
      throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
    return this.lineInner(pos, 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, to, text2) {
    [from, to] = clip(this, from, to);
    let parts2 = [];
    this.decompose(
      0,
      from,
      parts2,
      2
      /* Open.To */
    );
    if (text2.length)
      text2.decompose(
        0,
        text2.length,
        parts2,
        1 | 2
        /* Open.To */
      );
    this.decompose(
      to,
      this.length,
      parts2,
      1
      /* Open.From */
    );
    return TextNode.from(parts2, this.length - (to - 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, to = this.length) {
    [from, to] = clip(this, from, to);
    let parts2 = [];
    this.decompose(from, to, parts2, 0);
    return TextNode.from(parts2, to - 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 start2 = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
    let a = new RawTextCursor(this), b = new RawTextCursor(other);
    for (let skip2 = start2, pos = start2; ; ) {
      a.next(skip2);
      b.next(skip2);
      skip2 = 0;
      if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
        return false;
      pos += a.value.length;
      if (a.done || pos >= 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, to = this.length) {
    return new PartialTextCursor(this, from, to);
  }
  /**
  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, to) {
    let inner;
    if (from == null) {
      inner = this.iter();
    } else {
      if (to == null)
        to = this.lines + 1;
      let start2 = this.line(from).from;
      inner = this.iterRange(start2, Math.max(start2, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 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, []));
  }
};
var TextLeaf = class _TextLeaf extends Text2 {
  constructor(text2, length = textLength(text2)) {
    super();
    this.text = text2;
    this.length = length;
  }
  get lines() {
    return this.text.length;
  }
  get children() {
    return null;
  }
  lineInner(target, isLine, line, offset) {
    for (let i2 = 0; ; i2++) {
      let string4 = this.text[i2], end = offset + string4.length;
      if ((isLine ? line : end) >= target)
        return new Line(offset, end, line, string4);
      offset = end + 1;
      line++;
    }
  }
  decompose(from, to, target, open) {
    let text2 = from <= 0 && to >= this.length ? this : new _TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
    if (open & 1) {
      let prev = target.pop();
      let joined = appendText(text2.text, prev.text.slice(), 0, text2.length);
      if (joined.length <= 32) {
        target.push(new _TextLeaf(joined, prev.length + text2.length));
      } else {
        let mid = joined.length >> 1;
        target.push(new _TextLeaf(joined.slice(0, mid)), new _TextLeaf(joined.slice(mid)));
      }
    } else {
      target.push(text2);
    }
  }
  replace(from, to, text2) {
    if (!(text2 instanceof _TextLeaf))
      return super.replace(from, to, text2);
    [from, to] = clip(this, from, to);
    let lines = appendText(this.text, appendText(text2.text, sliceText(this.text, 0, from)), to);
    let newLen = this.length + text2.length - (to - from);
    if (lines.length <= 32)
      return new _TextLeaf(lines, newLen);
    return TextNode.from(_TextLeaf.split(lines, []), newLen);
  }
  sliceString(from, to = this.length, lineSep = "\n") {
    [from, to] = clip(this, from, to);
    let result = "";
    for (let pos = 0, i2 = 0; pos <= to && i2 < this.text.length; i2++) {
      let line = this.text[i2], end = pos + line.length;
      if (pos > from && i2)
        result += lineSep;
      if (from < end && to > pos)
        result += line.slice(Math.max(0, from - pos), to - pos);
      pos = end + 1;
    }
    return result;
  }
  flatten(target) {
    for (let line of this.text)
      target.push(line);
  }
  scanIdentical() {
    return 0;
  }
  static split(text2, target) {
    let part = [], len = -1;
    for (let line of text2) {
      part.push(line);
      len += line.length + 1;
      if (part.length == 32) {
        target.push(new _TextLeaf(part, len));
        part = [];
        len = -1;
      }
    }
    if (len > -1)
      target.push(new _TextLeaf(part, len));
    return target;
  }
};
var TextNode = class _TextNode extends Text2 {
  constructor(children2, length) {
    super();
    this.children = children2;
    this.length = length;
    this.lines = 0;
    for (let child2 of children2)
      this.lines += child2.lines;
  }
  lineInner(target, isLine, line, offset) {
    for (let i2 = 0; ; i2++) {
      let child2 = this.children[i2], end = offset + child2.length, endLine = line + child2.lines - 1;
      if ((isLine ? endLine : end) >= target)
        return child2.lineInner(target, isLine, line, offset);
      offset = end + 1;
      line = endLine + 1;
    }
  }
  decompose(from, to, target, open) {
    for (let i2 = 0, pos = 0; pos <= to && i2 < this.children.length; i2++) {
      let child2 = this.children[i2], end = pos + child2.length;
      if (from <= end && to >= pos) {
        let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0));
        if (pos >= from && end <= to && !childOpen)
          target.push(child2);
        else
          child2.decompose(from - pos, to - pos, target, childOpen);
      }
      pos = end + 1;
    }
  }
  replace(from, to, text2) {
    [from, to] = clip(this, from, to);
    if (text2.lines < this.lines)
      for (let i2 = 0, pos = 0; i2 < this.children.length; i2++) {
        let child2 = this.children[i2], end = pos + child2.length;
        if (from >= pos && to <= end) {
          let updated = child2.replace(from - pos, to - pos, text2);
          let totalLines = this.lines - child2.lines + updated.lines;
          if (updated.lines < totalLines >> 5 - 1 && updated.lines > totalLines >> 5 + 1) {
            let copy2 = this.children.slice();
            copy2[i2] = updated;
            return new _TextNode(copy2, this.length - (to - from) + text2.length);
          }
          return super.replace(pos, end, updated);
        }
        pos = end + 1;
      }
    return super.replace(from, to, text2);
  }
  sliceString(from, to = this.length, lineSep = "\n") {
    [from, to] = clip(this, from, to);
    let result = "";
    for (let i2 = 0, pos = 0; i2 < this.children.length && pos <= to; i2++) {
      let child2 = this.children[i2], end = pos + child2.length;
      if (pos > from && i2)
        result += lineSep;
      if (from < end && to > pos)
        result += child2.sliceString(from - pos, to - pos, lineSep);
      pos = end + 1;
    }
    return result;
  }
  flatten(target) {
    for (let child2 of this.children)
      child2.flatten(target);
  }
  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, ch) => l + ch.length + 1, -1)) {
    let lines = 0;
    for (let ch of children2)
      lines += ch.lines;
    if (lines < 32) {
      let flat = [];
      for (let ch of children2)
        ch.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 add3(child2) {
      let last;
      if (child2.lines > maxChunk && child2 instanceof _TextNode) {
        for (let node of child2.children)
          add3(node);
      } else if (child2.lines > minChunk && (currentLines > minChunk || !currentLines)) {
        flush();
        chunked.push(child2);
      } else if (child2 instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child2.lines + last.lines <= 32) {
        currentLines += child2.lines;
        currentLen += child2.length + 1;
        currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child2.text), last.length + 1 + child2.length);
      } else {
        if (currentLines + child2.lines > chunk)
          flush();
        currentLines += child2.lines;
        currentLen += child2.length + 1;
        currentChunk.push(child2);
      }
    }
    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 child2 of children2)
      add3(child2);
    flush();
    return chunked.length == 1 ? chunked[0] : new _TextNode(chunked, length);
  }
};
Text2.empty = /* @__PURE__ */ new TextLeaf([""], 0);
function textLength(text2) {
  let length = -1;
  for (let line of text2)
    length += line.length + 1;
  return length;
}
function appendText(text2, target, from = 0, to = 1e9) {
  for (let pos = 0, i2 = 0, first = true; i2 < text2.length && pos <= to; i2++) {
    let line = text2[i2], end = pos + line.length;
    if (end >= from) {
      if (end > to)
        line = line.slice(0, to - pos);
      if (pos < from)
        line = line.slice(from - pos);
      if (first) {
        target[target.length - 1] += line;
        first = false;
      } else
        target.push(line);
    }
    pos = end + 1;
  }
  return target;
}
function sliceText(text2, from, to) {
  return appendText(text2, [""], from, to);
}
var RawTextCursor = class {
  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(skip2, dir) {
    this.done = this.lineBreak = false;
    for (; ; ) {
      let last = this.nodes.length - 1;
      let top3 = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
      let size = top3 instanceof TextLeaf ? top3.text.length : top3.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 (skip2 == 0) {
          this.lineBreak = true;
          this.value = "\n";
          return this;
        }
        skip2--;
      } else if (top3 instanceof TextLeaf) {
        let next2 = top3.text[offset + (dir < 0 ? -1 : 0)];
        this.offsets[last] += dir;
        if (next2.length > Math.max(0, skip2)) {
          this.value = skip2 == 0 ? next2 : dir > 0 ? next2.slice(skip2) : next2.slice(0, next2.length - skip2);
          return this;
        }
        skip2 -= next2.length;
      } else {
        let next2 = top3.children[offset + (dir < 0 ? -1 : 0)];
        if (skip2 > next2.length) {
          skip2 -= next2.length;
          this.offsets[last] += dir;
        } else {
          if (dir < 0)
            this.offsets[last]--;
          this.nodes.push(next2);
          this.offsets.push(dir > 0 ? 1 : (next2 instanceof TextLeaf ? next2.text.length : next2.children.length) << 1);
        }
      }
    }
  }
  next(skip2 = 0) {
    if (skip2 < 0) {
      this.nextInner(-skip2, -this.dir);
      skip2 = this.value.length;
    }
    return this.nextInner(skip2, this.dir);
  }
};
var PartialTextCursor = class {
  constructor(text2, start2, end) {
    this.value = "";
    this.done = false;
    this.cursor = new RawTextCursor(text2, start2 > end ? -1 : 1);
    this.pos = start2 > end ? text2.length : 0;
    this.from = Math.min(start2, end);
    this.to = Math.max(start2, end);
  }
  nextInner(skip2, dir) {
    if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
      this.value = "";
      this.done = true;
      return this;
    }
    skip2 += 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 (skip2 > limit)
      skip2 = limit;
    limit -= skip2;
    let { value } = this.cursor.next(skip2);
    this.pos += (value.length + skip2) * dir;
    this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
    this.done = !this.value;
    return this;
  }
  next(skip2 = 0) {
    if (skip2 < 0)
      skip2 = Math.max(skip2, this.from - this.pos);
    else if (skip2 > 0)
      skip2 = Math.min(skip2, this.to - this.pos);
    return this.nextInner(skip2, this.cursor.dir);
  }
  get lineBreak() {
    return this.cursor.lineBreak && this.value != "";
  }
};
var LineCursor = class {
  constructor(inner) {
    this.inner = inner;
    this.afterBreak = true;
    this.value = "";
    this.done = false;
  }
  next(skip2 = 0) {
    let { done, lineBreak, value } = this.inner.next(skip2);
    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 = value;
      this.afterBreak = false;
    }
    return this;
  }
  get lineBreak() {
    return false;
  }
};
if (typeof Symbol != "undefined") {
  Text2.prototype[Symbol.iterator] = function() {
    return this.iter();
  };
  RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
}
var Line = class {
  /**
  @internal
  */
  constructor(from, to, number7, text2) {
    this.from = from;
    this.to = to;
    this.number = number7;
    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, to) {
  from = Math.max(0, Math.min(text2.length, from));
  return [from, Math.max(from, Math.min(text2.length, to))];
}
function findClusterBreak2(str, pos, forward = true, includeExtending = true) {
  return findClusterBreak(str, pos, forward, includeExtending);
}
function surrogateLow2(ch) {
  return ch >= 56320 && ch < 57344;
}
function surrogateHigh2(ch) {
  return ch >= 55296 && ch < 56320;
}
function codePointAt2(str, pos) {
  let code0 = str.charCodeAt(pos);
  if (!surrogateHigh2(code0) || pos + 1 == str.length)
    return code0;
  let code1 = str.charCodeAt(pos + 1);
  if (!surrogateLow2(code1))
    return code0;
  return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
}
function fromCodePoint(code) {
  if (code <= 65535)
    return String.fromCharCode(code);
  code -= 65536;
  return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
}
function codePointSize2(code) {
  return code < 65536 ? 1 : 2;
}
var 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 = {}));
var ChangeDesc = 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 result = 0;
    for (let i2 = 0; i2 < this.sections.length; i2 += 2)
      result += this.sections[i2];
    return result;
  }
  /**
  The length of the document after the change.
  */
  get newLength() {
    let result = 0;
    for (let i2 = 0; i2 < this.sections.length; i2 += 2) {
      let ins = this.sections[i2 + 1];
      result += ins < 0 ? this.sections[i2] : ins;
    }
    return result;
  }
  /**
  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(pos, 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 > pos)
          return posB + (pos - posA);
        posB += len;
      } else {
        if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos))
          return null;
        if (endA > pos || endA == pos && assoc < 0 && !len)
          return pos == posA || assoc < 0 ? posB : posB + ins;
        posB += ins;
      }
      posA = endA;
    }
    if (pos > posA)
      throw new RangeError(`Position ${pos} 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, to = from) {
    for (let i2 = 0, pos = 0; i2 < this.sections.length && pos <= to; ) {
      let len = this.sections[i2++], ins = this.sections[i2++], end = pos + len;
      if (ins >= 0 && pos <= to && end >= from)
        return pos < from && end > to ? "cover" : true;
      pos = end;
    }
    return false;
  }
  /**
  @internal
  */
  toString() {
    let result = "";
    for (let i2 = 0; i2 < this.sections.length; ) {
      let len = this.sections[i2++], ins = this.sections[i2++];
      result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
    }
    return result;
  }
  /**
  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);
  }
};
var ChangeSet = 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, pos = 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 index3 = i2 >> 1;
        while (inserted.length < index3)
          inserted.push(Text2.empty);
        inserted.push(len ? doc2.slice(pos, pos + len) : Text2.empty);
      }
      pos += 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, pos = 0; ; ) {
      let next2 = i2 == ranges.length ? 1e9 : ranges[i2++];
      while (pos < next2 || pos == next2 && iter.len == 0) {
        if (iter.done)
          break done;
        let len = Math.min(iter.len, next2 - pos);
        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);
        pos += len;
      }
      let end = ranges[i2++];
      while (pos < end) {
        if (iter.done)
          break done;
        let len = Math.min(iter.len, end - pos);
        addSection(resultSections, len, -1);
        addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
        iter.forward(len);
        pos += len;
      }
    }
    return {
      changes: new _ChangeSet(resultSections, resultInserted),
      filtered: ChangeDesc.create(filteredSections)
    };
  }
  /**
  Serialize this change set to a JSON-representable value.
  */
  toJSON() {
    let parts2 = [];
    for (let i2 = 0; i2 < this.sections.length; i2 += 2) {
      let len = this.sections[i2], ins = this.sections[i2 + 1];
      if (ins < 0)
        parts2.push(len);
      else if (ins == 0)
        parts2.push([len]);
      else
        parts2.push([len].concat(this.inserted[i2 >> 1].toJSON()));
    }
    return parts2;
  }
  /**
  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 = [], pos = 0;
    let total = null;
    function flush(force = false) {
      if (!force && !sections.length)
        return;
      if (pos < length)
        addSection(sections, length - pos, -1);
      let set4 = new _ChangeSet(sections, inserted);
      total = total ? total.compose(set4.map(total)) : set4;
      sections = [];
      inserted = [];
      pos = 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 = from, insert: insert2 } = spec;
        if (from > to || from < 0 || to > length)
          throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
        let insText = !insert2 ? Text2.empty : typeof insert2 == "string" ? Text2.of(insert2.split(lineSep || DefaultSplit)) : insert2;
        let insLen = insText.length;
        if (from == to && insLen == 0)
          return;
        if (from < pos)
          flush();
        if (from > pos)
          addSection(sections, from - pos, -1);
        addSection(sections, to - from, insLen);
        addInsert(inserted, sections, insText);
        pos = to;
      }
    }
    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(Text2.empty);
        inserted[i2] = Text2.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, value) {
  if (value.length == 0)
    return;
  let index3 = sections.length - 2 >> 1;
  if (index3 < values.length) {
    values[values.length - 1] = values[values.length - 1].append(value);
  } else {
    while (values.length < index3)
      values.push(Text2.empty);
    values.push(value);
  }
}
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 = Text2.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, left2 = a.len;
      while (left2) {
        if (b.ins == -1) {
          let piece = Math.min(left2, b.len);
          len += piece;
          left2 -= piece;
          b.forward(piece);
        } else if (b.ins == 0 && b.len < left2) {
          left2 -= 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 - left2);
    } 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);
    }
  }
}
var SectionIter = class {
  constructor(set4) {
    this.set = set4;
    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, index3 = this.i - 2 >> 1;
    return index3 >= inserted.length ? Text2.empty : inserted[index3];
  }
  textBit(len) {
    let { inserted } = this.set, index3 = this.i - 2 >> 1;
    return index3 >= inserted.length && !len ? Text2.empty : inserted[index3].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;
    }
  }
};
var SelectionRange = class _SelectionRange {
  constructor(from, to, flags2) {
    this.from = from;
    this.to = to;
    this.flags = flags2;
  }
  /**
  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 value = this.flags >> 6;
    return value == 16777215 ? void 0 : value;
  }
  /**
  Map this range through a change, producing a valid range in the
  updated document.
  */
  map(change, assoc = -1) {
    let from, to;
    if (this.empty) {
      from = to = change.mapPos(this.from, assoc);
    } else {
      from = change.mapPos(this.from, 1);
      to = change.mapPos(this.to, -1);
    }
    return from == this.from && to == this.to ? this : new _SelectionRange(from, to, this.flags);
  }
  /**
  Extend this range to cover at least `from` to `to`.
  */
  extend(from, to = from) {
    if (from <= this.anchor && to >= this.anchor)
      return EditorSelection.range(from, to);
    let head2 = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
    return EditorSelection.range(this.anchor, head2);
  }
  /**
  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, to, flags2) {
    return new _SelectionRange(from, to, flags2);
  }
};
var EditorSelection = 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(range2, main = true) {
    return _EditorSelection.create([range2].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(range2, which = this.mainIndex) {
    let ranges = this.ranges.slice();
    ranges[which] = range2;
    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, head2 = anchor) {
    return new _EditorSelection([_EditorSelection.range(anchor, head2)], 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 pos = 0, i2 = 0; i2 < ranges.length; i2++) {
      let range2 = ranges[i2];
      if (range2.empty ? range2.from <= pos : range2.from < pos)
        return _EditorSelection.normalized(ranges.slice(), mainIndex);
      pos = range2.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(pos, assoc = 0, bidiLevel, goalColumn) {
    return SelectionRange.create(pos, pos, (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, head2, goalColumn, bidiLevel) {
    let flags2 = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
    return head2 < anchor ? SelectionRange.create(head2, anchor, 32 | 16 | flags2) : SelectionRange.create(anchor, head2, (head2 > anchor ? 8 : 0) | flags2);
  }
  /**
  @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 range2 = ranges[i2], prev = ranges[i2 - 1];
      if (range2.empty ? range2.from <= prev.to : range2.from < prev.to) {
        let from = prev.from, to = Math.max(range2.to, prev.to);
        if (i2 <= mainIndex)
          mainIndex--;
        ranges.splice(--i2, 2, range2.anchor > range2.head ? _EditorSelection.range(to, from) : _EditorSelection.range(from, to));
      }
    }
    return new _EditorSelection(ranges, mainIndex);
  }
};
function checkSelection(selection2, docLength) {
  for (let range2 of selection2.ranges)
    if (range2.to > docLength)
      throw new RangeError("Selection points outside of document");
}
var nextID = 0;
var Facet = 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 : (a, b) => a === b), !!config2.static, config2.enables);
  }
  /**
  Returns an extension that adds the given value to this facet.
  */
  of(value) {
    return new FacetProvider([], this, 0, value);
  }
  /**
  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, get4) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 1, get4);
  }
  /**
  Create an extension that computes zero or more values for this
  facet from a state.
  */
  computeN(deps, get4) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 2, get4);
  }
  from(field, get4) {
    if (!get4)
      get4 = (x2) => x2;
    return this.compute([field], (state2) => get4(state2.field(field)));
  }
};
function sameArray(a, b) {
  return a == b || a.length == b.length && a.every((e, i2) => e === b[i2]);
}
var FacetProvider = class {
  constructor(dependencies, facet, type, value) {
    this.dependencies = dependencies;
    this.facet = facet;
    this.type = type;
    this.value = value;
    this.id = nextID++;
  }
  dynamicSlot(addresses) {
    var _a2;
    let getter = this.value;
    let compare2 = this.facet.compareInput;
    let id3 = this.id, idx = addresses[id3] >> 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(state2) {
        state2.values[idx] = getter(state2);
        return 1;
      },
      update(state2, tr) {
        if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state2, depAddrs)) {
          let newVal = getter(state2);
          if (multi ? !compareArray(newVal, state2.values[idx], compare2) : !compare2(newVal, state2.values[idx])) {
            state2.values[idx] = newVal;
            return 1;
          }
        }
        return 0;
      },
      reconfigure: (state2, oldState) => {
        let newVal, oldAddr = oldState.config.address[id3];
        if (oldAddr != null) {
          let oldVal = getAddr(oldState, oldAddr);
          if (this.dependencies.every((dep) => {
            return dep instanceof Facet ? oldState.facet(dep) === state2.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state2.field(dep, false) : true;
          }) || (multi ? compareArray(newVal = getter(state2), oldVal, compare2) : compare2(newVal = getter(state2), oldVal))) {
            state2.values[idx] = oldVal;
            return 0;
          }
        } else {
          newVal = getter(state2);
        }
        state2.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(state2, addrs) {
  let changed = false;
  for (let addr2 of addrs)
    if (ensureAddr(state2, addr2) & 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 get4(state2) {
    let values = [];
    for (let i2 = 0; i2 < providerAddrs.length; i2++) {
      let value = getAddr(state2, providerAddrs[i2]);
      if (providerTypes[i2] == 2)
        for (let val of value)
          values.push(val);
      else
        values.push(value);
    }
    return facet.combine(values);
  }
  return {
    create(state2) {
      for (let addr2 of providerAddrs)
        ensureAddr(state2, addr2);
      state2.values[idx] = get4(state2);
      return 1;
    },
    update(state2, tr) {
      if (!ensureAll(state2, dynamic))
        return 0;
      let value = get4(state2);
      if (facet.compare(value, state2.values[idx]))
        return 0;
      state2.values[idx] = value;
      return 1;
    },
    reconfigure(state2, oldState) {
      let depChanged = ensureAll(state2, providerAddrs);
      let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
      if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
        state2.values[idx] = oldValue;
        return 0;
      }
      let value = get4(state2);
      if (facet.compare(value, oldValue)) {
        state2.values[idx] = oldValue;
        return 0;
      }
      state2.values[idx] = value;
      return 1;
    }
  };
}
var initField = /* @__PURE__ */ Facet.define({ static: true });
var StateField = class _StateField {
  constructor(id3, createF, updateF, compareF, spec) {
    this.id = id3;
    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(state2) {
    let init4 = state2.facet(initField).find((i2) => i2.field == this);
    return ((init4 === null || init4 === void 0 ? void 0 : init4.create) || this.createF)(state2);
  }
  /**
  @internal
  */
  slot(addresses) {
    let idx = addresses[this.id] >> 1;
    return {
      create: (state2) => {
        state2.values[idx] = this.create(state2);
        return 1;
      },
      update: (state2, tr) => {
        let oldVal = state2.values[idx];
        let value = this.updateF(oldVal, tr);
        if (this.compareF(oldVal, value))
          return 0;
        state2.values[idx] = value;
        return 1;
      },
      reconfigure: (state2, oldState) => {
        let init4 = state2.facet(initField), oldInit = oldState.facet(initField), reInit;
        if ((reInit = init4.find((i2) => i2.field == this)) && reInit != oldInit.find((i2) => i2.field == this)) {
          state2.values[idx] = reInit.create(state2);
          return 1;
        }
        if (oldState.config.address[this.id] != null) {
          state2.values[idx] = oldState.field(this);
          return 0;
        }
        state2.values[idx] = this.create(state2);
        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(create) {
    return [this, initField.of({ field: this, create })];
  }
  /**
  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;
  }
};
var Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
function prec(value) {
  return (ext2) => new PrecExtension(ext2, value);
}
var 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)
};
var PrecExtension = class {
  constructor(inner, prec2) {
    this.inner = inner;
    this.prec = prec2;
  }
};
var Compartment = class _Compartment {
  /**
  Create an instance of this compartment to add to your [state
  configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
  */
  of(ext2) {
    return new CompartmentInstance(this, ext2);
  }
  /**
  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(state2) {
    return state2.config.compartments.get(this);
  }
};
var CompartmentInstance = class {
  constructor(compartment, inner) {
    this.compartment = compartment;
    this.inner = inner;
  }
};
var Configuration = 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 addr2 = this.address[facet.id];
    return addr2 == null ? facet.default : this.staticValues[addr2 >> 1];
  }
  static resolve(base2, compartments, oldState) {
    let fields = [];
    let facets = /* @__PURE__ */ Object.create(null);
    let newCompartments = /* @__PURE__ */ new Map();
    for (let ext2 of flatten(base2, compartments, newCompartments)) {
      if (ext2 instanceof StateField)
        fields.push(ext2);
      else
        (facets[ext2.facet.id] || (facets[ext2.facet.id] = [])).push(ext2);
    }
    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 id3 in facets) {
      let providers = facets[id3], facet = providers[0].facet;
      let oldProviders = oldFacets && oldFacets[id3] || [];
      if (providers.every(
        (p) => p.type == 0
        /* Provider.Static */
      )) {
        address[facet.id] = staticValues.length << 1 | 1;
        if (sameArray(oldProviders, providers)) {
          staticValues.push(oldState.facet(facet));
        } else {
          let value = facet.combine(providers.map((p) => p.value));
          staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
        }
      } 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 result = [[], [], [], [], []];
  let seen = /* @__PURE__ */ new Map();
  function inner(ext2, prec2) {
    let known = seen.get(ext2);
    if (known != null) {
      if (known <= prec2)
        return;
      let found = result[known].indexOf(ext2);
      if (found > -1)
        result[known].splice(found, 1);
      if (ext2 instanceof CompartmentInstance)
        newCompartments.delete(ext2.compartment);
    }
    seen.set(ext2, prec2);
    if (Array.isArray(ext2)) {
      for (let e of ext2)
        inner(e, prec2);
    } else if (ext2 instanceof CompartmentInstance) {
      if (newCompartments.has(ext2.compartment))
        throw new RangeError(`Duplicate use of compartment in extensions`);
      let content2 = compartments.get(ext2.compartment) || ext2.inner;
      newCompartments.set(ext2.compartment, content2);
      inner(content2, prec2);
    } else if (ext2 instanceof PrecExtension) {
      inner(ext2.inner, ext2.prec);
    } else if (ext2 instanceof StateField) {
      result[prec2].push(ext2);
      if (ext2.provides)
        inner(ext2.provides, prec2);
    } else if (ext2 instanceof FacetProvider) {
      result[prec2].push(ext2);
      if (ext2.facet.extensions)
        inner(ext2.facet.extensions, Prec_.default);
    } else {
      let content2 = ext2.extension;
      if (!content2)
        throw new Error(`Unrecognized extension value in extension set (${ext2}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
      inner(content2, prec2);
    }
  }
  inner(extension, Prec_.default);
  return result.reduce((a, b) => a.concat(b));
}
function ensureAddr(state2, addr2) {
  if (addr2 & 1)
    return 2;
  let idx = addr2 >> 1;
  let status = state2.status[idx];
  if (status == 4)
    throw new Error("Cyclic dependency between fields and/or facets");
  if (status & 2)
    return status;
  state2.status[idx] = 4;
  let changed = state2.computeSlot(state2, state2.config.dynamicSlots[idx]);
  return state2.status[idx] = 2 | changed;
}
function getAddr(state2, addr2) {
  return addr2 & 1 ? state2.config.staticValues[addr2 >> 1] : state2.values[addr2 >> 1];
}
var languageData = /* @__PURE__ */ Facet.define();
var allowMultipleSelections = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((v) => v),
  static: true
});
var lineSeparator = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : void 0,
  static: true
});
var changeFilter = /* @__PURE__ */ Facet.define();
var transactionFilter = /* @__PURE__ */ Facet.define();
var transactionExtender = /* @__PURE__ */ Facet.define();
var readOnly = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : false
});
var Annotation = class {
  /**
  @internal
  */
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  /**
  Define a new type of annotation.
  */
  static define() {
    return new AnnotationType();
  }
};
var AnnotationType = class {
  /**
  Create an instance of this annotation.
  */
  of(value) {
    return new Annotation(this, value);
  }
};
var StateEffectType = class {
  /**
  @internal
  */
  constructor(map2) {
    this.map = map2;
  }
  /**
  Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
  type.
  */
  of(value) {
    return new StateEffect(this, value);
  }
};
var StateEffect = class _StateEffect {
  /**
  @internal
  */
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  /**
  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 result = [];
    for (let effect2 of effects) {
      let mapped = effect2.map(mapping);
      if (mapped)
        result.push(mapped);
    }
    return result;
  }
};
StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define();
StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define();
var Transaction2 = class _Transaction {
  constructor(startState, changes, selection2, effects, annotations, scrollIntoView3) {
    this.startState = startState;
    this.changes = changes;
    this.selection = selection2;
    this.effects = effects;
    this.annotations = annotations;
    this.scrollIntoView = scrollIntoView3;
    this._doc = null;
    this._state = null;
    if (selection2)
      checkSelection(selection2, changes.newLength);
    if (!annotations.some((a) => a.type == _Transaction.time))
      this.annotations = annotations.concat(_Transaction.time.of(Date.now()));
  }
  /**
  @internal
  */
  static create(startState, changes, selection2, effects, annotations, scrollIntoView3) {
    return new _Transaction(startState, changes, selection2, effects, annotations, scrollIntoView3);
  }
  /**
  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(event2) {
    let e = this.annotation(_Transaction.userEvent);
    return !!(e && (e == event2 || e.length > event2.length && e.slice(0, event2.length) == event2 && e[event2.length] == "."));
  }
};
Transaction2.time = /* @__PURE__ */ Annotation.define();
Transaction2.userEvent = /* @__PURE__ */ Annotation.define();
Transaction2.addToHistory = /* @__PURE__ */ Annotation.define();
Transaction2.remote = /* @__PURE__ */ Annotation.define();
function joinRanges(a, b) {
  let result = [];
  for (let iA = 0, iB = 0; ; ) {
    let from, to;
    if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
      from = a[iA++];
      to = a[iA++];
    } else if (iB < b.length) {
      from = b[iB++];
      to = b[iB++];
    } else
      return result;
    if (!result.length || result[result.length - 1] < from)
      result.push(from, to);
    else if (result[result.length - 1] < to)
      result[result.length - 1] = to;
  }
}
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(state2, spec, docSize) {
  let sel = spec.selection, annotations = asArray(spec.annotations);
  if (spec.userEvent)
    annotations = annotations.concat(Transaction2.userEvent.of(spec.userEvent));
  return {
    changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state2.facet(lineSeparator)),
    selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
    effects: asArray(spec.effects),
    annotations,
    scrollIntoView: !!spec.scrollIntoView
  };
}
function resolveTransaction(state2, specs, filter2) {
  let s = resolveTransactionInner(state2, specs.length ? specs[0] : {}, state2.doc.length);
  if (specs.length && specs[0].filter === false)
    filter2 = false;
  for (let i2 = 1; i2 < specs.length; i2++) {
    if (specs[i2].filter === false)
      filter2 = false;
    let seq = !!specs[i2].sequential;
    s = mergeTransaction(s, resolveTransactionInner(state2, specs[i2], seq ? s.changes.newLength : state2.doc.length), seq);
  }
  let tr = Transaction2.create(state2, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
  return extendTransaction(filter2 ? filterTransaction(tr) : tr);
}
function filterTransaction(tr) {
  let state2 = tr.startState;
  let result = true;
  for (let filter2 of state2.facet(changeFilter)) {
    let value = filter2(tr);
    if (value === false) {
      result = false;
      break;
    }
    if (Array.isArray(value))
      result = result === true ? value : joinRanges(result, value);
  }
  if (result !== true) {
    let changes, back;
    if (result === false) {
      back = tr.changes.invertedDesc;
      changes = ChangeSet.empty(state2.doc.length);
    } else {
      let filtered = tr.changes.filter(result);
      changes = filtered.changes;
      back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
    }
    tr = Transaction2.create(state2, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
  }
  let filters = state2.facet(transactionFilter);
  for (let i2 = filters.length - 1; i2 >= 0; i2--) {
    let filtered = filters[i2](tr);
    if (filtered instanceof Transaction2)
      tr = filtered;
    else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction2)
      tr = filtered[0];
    else
      tr = resolveTransaction(state2, asArray(filtered), false);
  }
  return tr;
}
function extendTransaction(tr) {
  let state2 = tr.startState, extenders = state2.facet(transactionExtender), spec = tr;
  for (let i2 = extenders.length - 1; i2 >= 0; i2--) {
    let extension = extenders[i2](tr);
    if (extension && Object.keys(extension).length)
      spec = mergeTransaction(spec, resolveTransactionInner(state2, extension, tr.changes.newLength), true);
  }
  return spec == tr ? tr : Transaction2.create(state2, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
}
var none = [];
function asArray(value) {
  return value == null ? none : Array.isArray(value) ? value : [value];
}
var CharCategory = /* @__PURE__ */ function(CharCategory2) {
  CharCategory2[CharCategory2["Word"] = 0] = "Word";
  CharCategory2[CharCategory2["Space"] = 1] = "Space";
  CharCategory2[CharCategory2["Other"] = 2] = "Other";
  return CharCategory2;
}(CharCategory || (CharCategory = {}));
var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
var wordChar;
try {
  wordChar = /* @__PURE__ */ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
} catch (_2) {
}
function hasWordChar(str) {
  if (wordChar)
    return wordChar.test(str);
  for (let i2 = 0; i2 < str.length; i2++) {
    let ch = str[i2];
    if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
      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;
  };
}
var EditorState = class _EditorState {
  constructor(config2, doc2, selection2, values, computeSlot, tr) {
    this.config = config2;
    this.doc = doc2;
    this.selection = selection2;
    this.values = values;
    this.status = config2.statusTemplate.slice();
    this.computeSlot = computeSlot;
    if (tr)
      tr._state = this;
    for (let i2 = 0; i2 < this.config.dynamicSlots.length; i2++)
      ensureAddr(this, i2 << 1);
    this.computeSlot = null;
  }
  field(field, require2 = true) {
    let addr2 = this.config.address[field.id];
    if (addr2 == null) {
      if (require2)
        throw new RangeError("Field is not present in this state");
      return void 0;
    }
    ensureAddr(this, addr2);
    return getAddr(this, addr2);
  }
  /**
  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(tr) {
    let conf = this.config, { base: base2, compartments } = conf;
    for (let effect2 of tr.effects) {
      if (effect2.is(Compartment.reconfigure)) {
        if (conf) {
          compartments = /* @__PURE__ */ new Map();
          conf.compartments.forEach((val, key2) => compartments.set(key2, val));
          conf = null;
        }
        compartments.set(effect2.value.compartment, effect2.value.extension);
      } else if (effect2.is(StateEffect.reconfigure)) {
        conf = null;
        base2 = effect2.value;
      } else if (effect2.is(StateEffect.appendConfig)) {
        conf = null;
        base2 = asArray(base2).concat(effect2.value);
      }
    }
    let startValues;
    if (!conf) {
      conf = Configuration.resolve(base2, compartments, this);
      let intermediateState = new _EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state2, slot2) => slot2.reconfigure(state2, this), null);
      startValues = intermediateState.values;
    } else {
      startValues = tr.startState.values.slice();
    }
    let selection2 = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
    new _EditorState(conf, tr.newDoc, selection2, startValues, (state2, slot2) => slot2.update(state2, tr), tr);
  }
  /**
  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((range2) => ({
      changes: { from: range2.from, to: range2.to, insert: text2 },
      range: EditorSelection.cursor(range2.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 result = f(sel.ranges[i2]);
      let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
      for (let j = 0; j < i2; j++)
        ranges[j] = ranges[j].map(newMapped);
      let mapBy = changes.mapDesc(newChanges, true);
      ranges.push(result.range.map(mapBy));
      changes = changes.compose(newMapped);
      effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.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(string4) {
    return Text2.of(string4.split(this.facet(_EditorState.lineSeparator) || DefaultSplit));
  }
  /**
  Return the given range of the document as a string.
  */
  sliceDoc(from = 0, to = this.doc.length) {
    return this.doc.sliceString(from, to, this.lineBreak);
  }
  /**
  Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
  */
  facet(facet) {
    let addr2 = this.config.address[facet.id];
    if (addr2 == null)
      return facet.default;
    ensureAddr(this, addr2);
    return getAddr(this, addr2);
  }
  /**
  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 result = {
      doc: this.sliceDoc(),
      selection: this.selection.toJSON()
    };
    if (fields)
      for (let prop2 in fields) {
        let value = fields[prop2];
        if (value instanceof StateField && this.config.address[value.id] != null)
          result[prop2] = value.spec.toJSON(this.field(fields[prop2]), this);
      }
    return result;
  }
  /**
  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 prop2 in fields) {
        if (Object.prototype.hasOwnProperty.call(json, prop2)) {
          let field = fields[prop2], value = json[prop2];
          fieldInit.push(field.init((state2) => field.spec.fromJSON(value, state2)));
        }
      }
    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 Text2 ? config2.doc : Text2.of((config2.doc || "").split(configuration.staticFacet(_EditorState.lineSeparator) || DefaultSplit));
    let selection2 = !config2.selection ? EditorSelection.single(0) : config2.selection instanceof EditorSelection ? config2.selection : EditorSelection.single(config2.selection.anchor, config2.selection.head);
    checkSelection(selection2, doc2.length);
    if (!configuration.staticFacet(allowMultipleSelections))
      selection2 = selection2.asSingle();
    return new _EditorState(configuration, doc2, selection2, configuration.dynamicSlots.map(() => null), (state2, slot2) => slot2.create(state2), 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(phrase2, ...insert2) {
    for (let map2 of this.facet(_EditorState.phrases))
      if (Object.prototype.hasOwnProperty.call(map2, phrase2)) {
        phrase2 = map2[phrase2];
        break;
      }
    if (insert2.length)
      phrase2 = phrase2.replace(/\$(\$|\d*)/g, (m2, i2) => {
        if (i2 == "$")
          return "$";
        let n = +(i2 || 1);
        return !n || n > insert2.length ? m2 : insert2[n - 1];
      });
    return phrase2;
  }
  /**
  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(name3, pos, side = -1) {
    let values = [];
    for (let provider of this.facet(languageData)) {
      for (let result of provider(this, pos, side)) {
        if (Object.prototype.hasOwnProperty.call(result, name3))
          values.push(result[name3]);
      }
    }
    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(at) {
    return makeCategorizer(this.languageDataAt("wordChars", at).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(pos) {
    let { text: text2, from, length } = this.doc.lineAt(pos);
    let cat = this.charCategorizer(pos);
    let start2 = pos - from, end = pos - from;
    while (start2 > 0) {
      let prev = findClusterBreak2(text2, start2, false);
      if (cat(text2.slice(prev, start2)) != CharCategory.Word)
        break;
      start2 = prev;
    }
    while (end < length) {
      let next2 = findClusterBreak2(text2, end);
      if (cat(text2.slice(end, next2)) != CharCategory.Word)
        break;
      end = next2;
    }
    return start2 == end ? null : EditorSelection.range(start2 + 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, defaults3, combine = {}) {
  let result = {};
  for (let config2 of configs)
    for (let key2 of Object.keys(config2)) {
      let value = config2[key2], current = result[key2];
      if (current === void 0)
        result[key2] = value;
      else if (current === value || value === void 0) ;
      else if (Object.hasOwnProperty.call(combine, key2))
        result[key2] = combine[key2](current, value);
      else
        throw new Error("Config merge conflict for field " + key2);
    }
  for (let key2 in defaults3)
    if (result[key2] === void 0)
      result[key2] = defaults3[key2];
  return result;
}
var RangeValue = class {
  /**
  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, to = from) {
    return Range.create(from, to, this);
  }
};
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
RangeValue.prototype.point = false;
RangeValue.prototype.mapMode = MapMode.TrackDel;
var Range = class _Range {
  constructor(from, to, value) {
    this.from = from;
    this.to = to;
    this.value = value;
  }
  /**
  @internal
  */
  static create(from, to, value) {
    return new _Range(from, to, value);
  }
};
function cmpRange(a, b) {
  return a.from - b.from || a.value.startSide - b.value.startSide;
}
var Chunk = class _Chunk {
  constructor(from, to, value, maxPoint) {
    this.from = from;
    this.to = to;
    this.value = value;
    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(pos, side, end, startAt = 0) {
    let arr = end ? this.to : this.from;
    for (let lo = startAt, hi = arr.length; ; ) {
      if (lo == hi)
        return lo;
      let mid = lo + hi >> 1;
      let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
      if (mid == lo)
        return diff >= 0 ? lo : hi;
      if (diff >= 0)
        hi = mid;
      else
        lo = mid + 1;
    }
  }
  between(offset, from, to, f) {
    for (let i2 = this.findIndex(from, -1e9, true), e = this.findIndex(to, 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 value = [], from = [], to = [], 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);
      value.push(val);
      from.push(newFrom - newPos);
      to.push(newTo - newPos);
    }
    return { mapped: value.length ? new _Chunk(from, to, value, maxPoint) : null, pos: newPos };
  }
};
var RangeSet = 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(index3) {
    return this.chunkPos[index3] + this.chunk[index3].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: add3 = [], sort: sort2 = false, filterFrom = 0, filterTo = this.length } = updateSpec;
    let filter2 = updateSpec.filter;
    if (add3.length == 0 && !filter2)
      return this;
    if (sort2)
      add3 = add3.slice().sort(cmpRange);
    if (this.isEmpty)
      return add3.length ? _RangeSet.of(add3) : this;
    let cur2 = new LayerCursor(this, null, -1).goto(0), i2 = 0, spill = [];
    let builder = new RangeSetBuilder();
    while (cur2.value || i2 < add3.length) {
      if (i2 < add3.length && (cur2.from - add3[i2].from || cur2.startSide - add3[i2].value.startSide) >= 0) {
        let range2 = add3[i2++];
        if (!builder.addInner(range2.from, range2.to, range2.value))
          spill.push(range2);
      } else if (cur2.rangeIndex == 1 && cur2.chunkIndex < this.chunk.length && (i2 == add3.length || this.chunkEnd(cur2.chunkIndex) < add3[i2].from) && (!filter2 || filterFrom > this.chunkEnd(cur2.chunkIndex) || filterTo < this.chunkPos[cur2.chunkIndex]) && builder.addChunk(this.chunkPos[cur2.chunkIndex], this.chunk[cur2.chunkIndex])) {
        cur2.nextChunk();
      } else {
        if (!filter2 || filterFrom > cur2.to || filterTo < cur2.from || filter2(cur2.from, cur2.to, cur2.value)) {
          if (!builder.addInner(cur2.from, cur2.to, cur2.value))
            spill.push(Range.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: filter2, 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 start2 = this.chunkPos[i2], chunk = this.chunk[i2];
      let touch = changes.touchesRange(start2, start2 + chunk.length);
      if (touch === false) {
        maxPoint = Math.max(maxPoint, chunk.maxPoint);
        chunks.push(chunk);
        chunkPos.push(changes.mapPos(start2));
      } else if (touch === true) {
        let { mapped, pos } = chunk.map(start2, changes);
        if (mapped) {
          maxPoint = Math.max(maxPoint, mapped.maxPoint);
          chunks.push(mapped);
          chunkPos.push(pos);
        }
      }
    }
    let next2 = this.nextLayer.map(changes);
    return chunks.length == 0 ? next2 : new _RangeSet(chunkPos, chunks, next2 || _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, to, f) {
    if (this.isEmpty)
      return;
    for (let i2 = 0; i2 < this.chunk.length; i2++) {
      let start2 = this.chunkPos[i2], chunk = this.chunk[i2];
      if (to >= start2 && from <= start2 + chunk.length && chunk.between(start2, from - start2, to - start2, f) === false)
        return;
    }
    this.nextLayer.between(from, to, 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((set4) => set4.maxPoint > 0 || !set4.isEmpty && set4.maxPoint >= minPointSize);
    let b = newSets.filter((set4) => set4.maxPoint > 0 || !set4.isEmpty && set4.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(sideA, fromA, sideB, fromB, length, comparator));
    if (textDiff.empty && textDiff.length == 0)
      compare(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, to) {
    if (to == null)
      to = 1e9 - 1;
    let a = oldSets.filter((set4) => !set4.isEmpty && newSets.indexOf(set4) < 0);
    let b = newSets.filter((set4) => !set4.isEmpty && oldSets.indexOf(set4) < 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 > to)
        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, to, iterator, minPointSize = -1) {
    let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
    let openRanges = cursor.openStart;
    for (; ; ) {
      let curTo = Math.min(cursor.to, to);
      if (cursor.point) {
        let active = cursor.activeForPoint(cursor.to);
        let openCount = cursor.pointFrom < from ? active.length + 1 : cursor.point.startSide < 0 ? active.length : Math.min(active.length, openRanges);
        iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
        openRanges = Math.min(cursor.openEnd(curTo), active.length);
      } else if (curTo > pos) {
        iterator.span(pos, curTo, cursor.active, openRanges);
        openRanges = cursor.openEnd(curTo);
      }
      if (cursor.to > to)
        return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
      pos = 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, sort2 = false) {
    let build = new RangeSetBuilder();
    for (let range2 of ranges instanceof Range ? [ranges] : sort2 ? lazySort(ranges) : ranges)
      build.add(range2.from, range2.to, range2.value);
    return build.finish();
  }
  /**
  Join an array of range sets into a single set.
  */
  static join(sets) {
    if (!sets.length)
      return _RangeSet.empty;
    let result = sets[sets.length - 1];
    for (let i2 = sets.length - 2; i2 >= 0; i2--) {
      for (let layer2 = sets[i2]; layer2 != _RangeSet.empty; layer2 = layer2.nextLayer)
        result = new _RangeSet(layer2.chunkPos, layer2.chunk, result, Math.max(layer2.maxPoint, result.maxPoint));
    }
    return result;
  }
};
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;
var RangeSetBuilder = 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, to, value) {
    if (!this.addInner(from, to, value))
      (this.nextLayer || (this.nextLayer = new _RangeSetBuilder())).add(from, to, value);
  }
  /**
  @internal
  */
  addInner(from, to, value) {
    let diff = from - this.lastTo || value.startSide - this.last.endSide;
    if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
      throw new Error("Ranges must be added sorted by `from` position and `startSide`");
    if (diff < 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(to - this.chunkStart);
    this.last = value;
    this.lastFrom = from;
    this.lastTo = to;
    this.value.push(value);
    if (value.point)
      this.maxPoint = Math.max(this.maxPoint, to - 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(next2) {
    if (this.from.length)
      this.finishChunk(false);
    if (this.chunks.length == 0)
      return next2;
    let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next2) : next2, this.setMaxPoint);
    this.from = null;
    return result;
  }
};
function findSharedChunks(a, b, textDiff) {
  let inA = /* @__PURE__ */ new Map();
  for (let set4 of a)
    for (let i2 = 0; i2 < set4.chunk.length; i2++)
      if (set4.chunk[i2].maxPoint <= 0)
        inA.set(set4.chunk[i2], set4.chunkPos[i2]);
  let shared = /* @__PURE__ */ new Set();
  for (let set4 of b)
    for (let i2 = 0; i2 < set4.chunk.length; i2++) {
      let known = inA.get(set4.chunk[i2]);
      if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set4.chunkPos[i2] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set4.chunk[i2].length)))
        shared.add(set4.chunk[i2]);
    }
  return shared;
}
var LayerCursor = class {
  constructor(layer2, skip2, minPoint, rank = 0) {
    this.layer = layer2;
    this.skip = skip2;
    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(pos, side = -1e9) {
    this.chunkIndex = this.rangeIndex = 0;
    this.gotoInner(pos, side, false);
    return this;
  }
  gotoInner(pos, side, forward) {
    while (this.chunkIndex < this.layer.chunk.length) {
      let next2 = this.layer.chunk[this.chunkIndex];
      if (!(this.skip && this.skip.has(next2) || this.layer.chunkEnd(this.chunkIndex) < pos || next2.maxPoint < this.minPoint))
        break;
      this.chunkIndex++;
      forward = false;
    }
    if (this.chunkIndex < this.layer.chunk.length) {
      let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
      if (!forward || this.rangeIndex < rangeIndex)
        this.setRangeIndex(rangeIndex);
    }
    this.next();
  }
  forward(pos, side) {
    if ((this.to - pos || this.endSide - side) < 0)
      this.gotoInner(pos, 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(index3) {
    if (index3 == 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 = index3;
    }
  }
  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;
  }
};
var HeapCursor = class _HeapCursor {
  constructor(heap) {
    this.heap = heap;
  }
  static from(sets, skip2 = null, minPoint = -1) {
    let heap = [];
    for (let i2 = 0; i2 < sets.length; i2++) {
      for (let cur2 = sets[i2]; !cur2.isEmpty; cur2 = cur2.nextLayer) {
        if (cur2.maxPoint >= minPoint)
          heap.push(new LayerCursor(cur2, skip2, minPoint, i2));
      }
    }
    return heap.length == 1 ? heap[0] : new _HeapCursor(heap);
  }
  get startSide() {
    return this.value ? this.value.startSide : 0;
  }
  goto(pos, side = -1e9) {
    for (let cur2 of this.heap)
      cur2.goto(pos, side);
    for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)
      heapBubble(this.heap, i2);
    this.next();
    return this;
  }
  forward(pos, side) {
    for (let cur2 of this.heap)
      cur2.forward(pos, side);
    for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)
      heapBubble(this.heap, i2);
    if ((this.to - pos || 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 top3 = this.heap[0];
      this.from = top3.from;
      this.to = top3.to;
      this.value = top3.value;
      this.rank = top3.rank;
      if (top3.value)
        top3.next();
      heapBubble(this.heap, 0);
    }
  }
};
function heapBubble(heap, index3) {
  for (let cur2 = heap[index3]; ; ) {
    let childIndex = (index3 << 1) + 1;
    if (childIndex >= heap.length)
      break;
    let child2 = heap[childIndex];
    if (childIndex + 1 < heap.length && child2.compare(heap[childIndex + 1]) >= 0) {
      child2 = heap[childIndex + 1];
      childIndex++;
    }
    if (cur2.compare(child2) < 0)
      break;
    heap[childIndex] = cur2;
    heap[index3] = child2;
    index3 = childIndex;
  }
}
var SpanCursor = class {
  constructor(sets, skip2, 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, skip2, minPoint);
  }
  goto(pos, side = -1e9) {
    this.cursor.goto(pos, side);
    this.active.length = this.activeTo.length = this.activeRank.length = 0;
    this.minActive = -1;
    this.to = pos;
    this.endSide = side;
    this.openStart = -1;
    this.next();
    return this;
  }
  forward(pos, side) {
    while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
      this.removeActive(this.minActive);
    this.cursor.forward(pos, side);
  }
  removeActive(index3) {
    remove(this.active, index3);
    remove(this.activeTo, index3);
    remove(this.activeRank, index3);
    this.minActive = findMinIndex(this.active, this.activeTo);
  }
  addActive(trackOpen) {
    let i2 = 0, { value, to, rank } = this.cursor;
    while (i2 < this.activeRank.length && (rank - this.activeRank[i2] || to - this.activeTo[i2]) > 0)
      i2++;
    insert(this.active, i2, value);
    insert(this.activeTo, i2, to);
    insert(this.activeRank, i2, rank);
    if (trackOpen)
      insert(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(to) {
    if (!this.active.length)
      return this.active;
    let active = [];
    for (let i2 = this.active.length - 1; i2 >= 0; i2--) {
      if (this.activeRank[i2] < this.pointRank)
        break;
      if (this.activeTo[i2] > to || this.activeTo[i2] == to && this.active[i2].endSide >= this.point.endSide)
        active.push(this.active[i2]);
    }
    return active.reverse();
  }
  openEnd(to) {
    let open = 0;
    for (let i2 = this.activeTo.length - 1; i2 >= 0 && this.activeTo[i2] > to; i2--)
      open++;
    return open;
  }
};
function compare(a, startA, b, startB, length, comparator) {
  a.goto(startA);
  b.goto(startB);
  let endB = startB + length;
  let pos = startB, dPos = startB - startA;
  for (; ; ) {
    let dEnd = a.to + dPos - b.to, diff = dEnd || a.endSide - b.endSide;
    let end = diff < 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(pos, clipEnd, a.point, b.point);
    } else {
      if (clipEnd > pos && !sameValues(a.active, b.active))
        comparator.compareRange(pos, clipEnd, a.active, b.active);
    }
    if (end > endB)
      break;
    if ((dEnd || a.openEnd != b.openEnd) && comparator.boundChange)
      comparator.boundChange(end);
    pos = end;
    if (diff <= 0)
      a.next();
    if (diff >= 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(array3, index3) {
  for (let i2 = index3, e = array3.length - 1; i2 < e; i2++)
    array3[i2] = array3[i2 + 1];
  array3.pop();
}
function insert(array3, index3, value) {
  for (let i2 = array3.length - 1; i2 >= index3; i2--)
    array3[i2 + 1] = array3[i2];
  array3[index3] = value;
}
function findMinIndex(value, array3) {
  let found = -1, foundPos = 1e9;
  for (let i2 = 0; i2 < array3.length; i2++)
    if ((array3[i2] - foundPos || value[i2].endSide - value[found].endSide) < 0) {
      found = i2;
      foundPos = array3[i2];
    }
  return found;
}
function countColumn(string4, tabSize, to = string4.length) {
  let n = 0;
  for (let i2 = 0; i2 < to && i2 < string4.length; ) {
    if (string4.charCodeAt(i2) == 9) {
      n += tabSize - n % tabSize;
      i2++;
    } else {
      n++;
      i2 = findClusterBreak2(string4, i2);
    }
  }
  return n;
}
function findColumn(string4, col, tabSize, strict) {
  for (let i2 = 0, n = 0; ; ) {
    if (n >= col)
      return i2;
    if (i2 == string4.length)
      break;
    n += string4.charCodeAt(i2) == 9 ? tabSize - n % tabSize : 1;
    i2 = findClusterBreak2(string4, i2);
  }
  return strict === true ? -1 : string4.length;
}

// node_modules/style-mod/src/style-mod.js
var C = "\u037C";
var COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
var SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
var top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
var StyleModule = class {
  // :: (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, options4) {
    this.rules = [];
    let { finish } = options4 || {};
    function splitSelector(selector) {
      return /^@/.test(selector) ? [selector] : selector.split(/,\s*/);
    }
    function render(selectors, spec2, target, isKeyframes) {
      let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes";
      if (isAt && spec2 == null) return target.push(selectors[0] + ";");
      for (let prop2 in spec2) {
        let value = spec2[prop2];
        if (/&/.test(prop2)) {
          render(
            prop2.split(/,\s*/).map((part) => selectors.map((sel) => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),
            value,
            target
          );
        } else if (value && typeof value == "object") {
          if (!isAt) throw new RangeError("The value of a property (" + prop2 + ") should be a primitive value.");
          render(splitSelector(prop2), value, local, keyframes);
        } else if (value != null) {
          local.push(prop2.replace(/_.*/, "").replace(/[A-Z]/g, (l) => "-" + l.toLowerCase()) + ": " + value + ";");
        }
      }
      if (local.length || keyframes) {
        target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}");
      }
    }
    for (let prop2 in spec) render(splitSelector(prop2), spec[prop2], 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 id3 = top[COUNT] || 1;
    top[COUNT] = id3 + 1;
    return C + id3.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(root68, modules, options4) {
    let set4 = root68[SET], nonce = options4 && options4.nonce;
    if (!set4) set4 = new StyleSet(root68, nonce);
    else if (nonce) set4.setNonce(nonce);
    set4.mount(Array.isArray(modules) ? modules : [modules], root68);
  }
};
var adoptedSet = /* @__PURE__ */ new Map();
var StyleSet = class {
  constructor(root68, nonce) {
    let doc2 = root68.ownerDocument || root68, win = doc2.defaultView;
    if (!root68.head && root68.adoptedStyleSheets && win.CSSStyleSheet) {
      let adopted = adoptedSet.get(doc2);
      if (adopted) return root68[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 = [];
    root68[SET] = this;
  }
  mount(modules, root68) {
    let sheet = this.sheet;
    let pos = 0, j = 0;
    for (let i2 = 0; i2 < modules.length; i2++) {
      let mod = modules[i2], index3 = this.modules.indexOf(mod);
      if (index3 < j && index3 > -1) {
        this.modules.splice(index3, 1);
        j--;
        index3 = -1;
      }
      if (index3 == -1) {
        this.modules.splice(j++, 0, mod);
        if (sheet) for (let k = 0; k < mod.rules.length; k++)
          sheet.insertRule(mod.rules[k], pos++);
      } else {
        while (j < index3) pos += this.modules[j++].rules.length;
        pos += mod.rules.length;
        j++;
      }
    }
    if (sheet) {
      if (root68.adoptedStyleSheets.indexOf(this.sheet) < 0)
        root68.adoptedStyleSheets = [this.sheet, ...root68.adoptedStyleSheets];
    } else {
      let text2 = "";
      for (let i2 = 0; i2 < this.modules.length; i2++)
        text2 += this.modules[i2].getRules() + "\n";
      this.styleTag.textContent = text2;
      let target = root68.head || root68;
      if (this.styleTag.parentNode != target)
        target.insertBefore(this.styleTag, target.firstChild);
    }
  }
  setNonce(nonce) {
    if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
      this.styleTag.setAttribute("nonce", nonce);
  }
};

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

// node_modules/@codemirror/view/dist/index.js
function getSelection(root68) {
  let target;
  if (root68.nodeType == 11) {
    target = root68.getSelection ? root68 : root68.ownerDocument;
  } else {
    target = root68;
  }
  return target.getSelection();
}
function contains(dom, node) {
  return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
}
function hasSelection(dom, selection2) {
  if (!selection2.anchorNode)
    return false;
  try {
    return contains(dom, selection2.anchorNode);
  } catch (_2) {
    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(node, off, targetNode, targetOff) {
  return targetNode ? scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1) : false;
}
function domIndex(node) {
  for (var index3 = 0; ; index3++) {
    node = node.previousSibling;
    if (!node)
      return index3;
  }
}
function isBlockElement(node) {
  return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
}
function scanFor(node, off, targetNode, targetOff, dir) {
  for (; ; ) {
    if (node == targetNode && off == targetOff)
      return true;
    if (off == (dir < 0 ? 0 : maxOffset(node))) {
      if (node.nodeName == "DIV")
        return false;
      let parent2 = node.parentNode;
      if (!parent2 || parent2.nodeType != 1)
        return false;
      off = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent2;
    } else if (node.nodeType == 1) {
      node = node.childNodes[off + (dir < 0 ? -1 : 0)];
      if (node.nodeType == 1 && node.contentEditable == "false")
        return false;
      off = dir < 0 ? maxOffset(node) : 0;
    } else {
      return false;
    }
  }
}
function maxOffset(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function flattenRect(rect, left2) {
  let x2 = left2 ? 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, y2, xMargin, yMargin, ltr) {
  let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
  for (let cur2 = dom, stop2 = false; cur2 && !stop2; ) {
    if (cur2.nodeType == 1) {
      let bounding, top3 = cur2 == doc2.body;
      let scaleX = 1, scaleY = 1;
      if (top3) {
        bounding = windowRect(win);
      } else {
        if (/^(fixed|sticky)$/.test(getComputedStyle(cur2).position))
          stop2 = 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 (y2 == "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 = y2 == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y2 == "start" || y2 == "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 (top3) {
          win.scrollBy(moveX, moveY);
        } else {
          let movedX = 0, movedY = 0;
          if (moveY) {
            let start2 = cur2.scrollTop;
            cur2.scrollTop += moveY / scaleY;
            movedY = (cur2.scrollTop - start2) * scaleY;
          }
          if (moveX) {
            let start2 = cur2.scrollLeft;
            cur2.scrollLeft += moveX / scaleX;
            movedX = (cur2.scrollLeft - start2) * 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)
            y2 = "nearest";
        }
      }
      if (top3)
        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, y2;
  for (let cur2 = dom.parentNode; cur2; ) {
    if (cur2 == doc2.body || x2 && y2) {
      break;
    } else if (cur2.nodeType == 1) {
      if (!y2 && cur2.scrollHeight > cur2.clientHeight)
        y2 = 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: y2 };
}
var DOMSelectionState = class {
  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(range2) {
    let { anchorNode, focusNode } = range2;
    this.set(anchorNode, Math.min(range2.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range2.focusOffset, focusNode ? maxOffset(focusNode) : 0));
  }
  set(anchorNode, anchorOffset, focusNode, focusOffset) {
    this.anchorNode = anchorNode;
    this.anchorOffset = anchorOffset;
    this.focusNode = focusNode;
    this.focusOffset = focusOffset;
  }
};
var 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++], top3 = stack2[i2++], left2 = stack2[i2++];
      if (elt.scrollTop != top3)
        elt.scrollTop = top3;
      if (elt.scrollLeft != left2)
        elt.scrollLeft = left2;
    }
  }
}
var scratchRange;
function textRange(node, from, to = from) {
  let range2 = scratchRange || (scratchRange = document.createRange());
  range2.setEnd(node, to);
  range2.setStart(node, from);
  return range2;
}
function dispatchKey(elt, name3, code, mods) {
  let options4 = { key: name3, code: name3, keyCode: code, which: code, cancelable: true };
  if (mods)
    ({ altKey: options4.altKey, ctrlKey: options4.ctrlKey, shiftKey: options4.shiftKey, metaKey: options4.metaKey } = mods);
  let down = new KeyboardEvent("keydown", options4);
  down.synthetic = true;
  elt.dispatchEvent(down);
  let up = new KeyboardEvent("keyup", options4);
  up.synthetic = true;
  elt.dispatchEvent(up);
  return down.defaultPrevented || up.defaultPrevented;
}
function getRoot(node) {
  while (node) {
    if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
      return node;
    node = node.assignedSlot || node.parentNode;
  }
  return null;
}
function clearAttributes(node) {
  while (node.attributes.length)
    node.removeAttributeNode(node.attributes[0]);
}
function atElementStart(doc2, selection2) {
  let node = selection2.focusNode, offset = selection2.focusOffset;
  if (!node || selection2.anchorNode != node || selection2.anchorOffset != offset)
    return false;
  offset = Math.min(offset, maxOffset(node));
  for (; ; ) {
    if (offset) {
      if (node.nodeType != 1)
        return false;
      let prev = node.childNodes[offset - 1];
      if (prev.contentEditable == "false")
        offset--;
      else {
        node = prev;
        offset = maxOffset(node);
      }
    } else if (node == doc2) {
      return true;
    } else {
      offset = domIndex(node);
      node = node.parentNode;
    }
  }
}
function isScrolledToBottom(elt) {
  return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
}
function textNodeBefore(startNode, startOffset) {
  for (let node = startNode, offset = startOffset; ; ) {
    if (node.nodeType == 3 && offset > 0) {
      return { node, offset };
    } else if (node.nodeType == 1 && offset > 0) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset - 1];
      offset = maxOffset(node);
    } else if (node.parentNode && !isBlockElement(node)) {
      offset = domIndex(node);
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
function textNodeAfter(startNode, startOffset) {
  for (let node = startNode, offset = startOffset; ; ) {
    if (node.nodeType == 3 && offset < node.nodeValue.length) {
      return { node, offset };
    } else if (node.nodeType == 1 && offset < node.childNodes.length) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset];
      offset = 0;
    } else if (node.parentNode && !isBlockElement(node)) {
      offset = domIndex(node) + 1;
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
var DOMPos = class _DOMPos {
  constructor(node, offset, precise = true) {
    this.node = node;
    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);
  }
};
var noChildren = [];
var ContentView = 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 pos = this.posAtStart;
    for (let child2 of this.children) {
      if (child2 == view)
        return pos;
      pos += child2.length + child2.breakAfter;
    }
    throw new RangeError("Invalid child in posBefore");
  }
  posAfter(view) {
    return this.posBefore(view) + view.length;
  }
  sync(view, track) {
    if (this.flags & 2) {
      let parent2 = this.dom;
      let prev = null, next2;
      for (let child2 of this.children) {
        if (child2.flags & 7) {
          if (!child2.dom && (next2 = prev ? prev.nextSibling : parent2.firstChild)) {
            let contentView = _ContentView.get(next2);
            if (!contentView || !contentView.parent && contentView.canReuseDOM(child2))
              child2.reuseDOM(next2);
          }
          child2.sync(view, track);
          child2.flags &= ~7;
        }
        next2 = prev ? prev.nextSibling : parent2.firstChild;
        if (track && !track.written && track.node == parent2 && next2 != child2.dom)
          track.written = true;
        if (child2.dom.parentNode == parent2) {
          while (next2 && next2 != child2.dom)
            next2 = rm$1(next2);
        } else {
          parent2.insertBefore(child2.dom, next2);
        }
        prev = child2.dom;
      }
      next2 = prev ? prev.nextSibling : parent2.firstChild;
      if (next2 && track && track.node == parent2)
        track.written = true;
      while (next2)
        next2 = rm$1(next2);
    } else if (this.flags & 1) {
      for (let child2 of this.children)
        if (child2.flags & 7) {
          child2.sync(view, track);
          child2.flags &= ~7;
        }
    }
  }
  reuseDOM(_dom) {
  }
  localPosFromDOM(node, offset) {
    let after;
    if (node == this.dom) {
      after = this.dom.childNodes[offset];
    } else {
      let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
      for (; ; ) {
        let parent2 = node.parentNode;
        if (parent2 == this.dom)
          break;
        if (bias == 0 && parent2.firstChild != parent2.lastChild) {
          if (node == parent2.firstChild)
            bias = -1;
          else
            bias = 1;
        }
        node = parent2;
      }
      if (bias < 0)
        after = node;
      else
        after = node.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, pos = 0; ; i2++) {
      let child2 = this.children[i2];
      if (child2.dom == after)
        return pos;
      pos += child2.length + child2.breakAfter;
    }
  }
  domBoundsAround(from, to, offset = 0) {
    let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
    for (let i2 = 0, pos = offset, prevEnd = offset; i2 < this.children.length; i2++) {
      let child2 = this.children[i2], end = pos + child2.length;
      if (pos < from && end > to)
        return child2.domBoundsAround(from, to, pos);
      if (end >= from && fromI == -1) {
        fromI = i2;
        fromStart = pos;
      }
      if (pos > to && child2.dom.parentNode == this.dom) {
        toI = i2;
        toEnd = prevEnd;
        break;
      }
      prevEnd = end;
      pos = end + child2.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 parent2 = this.parent; parent2; parent2 = parent2.parent) {
      if (childList)
        parent2.flags |= 2;
      if (parent2.flags & 1)
        return;
      parent2.flags |= 1;
      childList = false;
    }
  }
  setParent(parent2) {
    if (this.parent != parent2) {
      this.parent = parent2;
      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 parent2 = v.parent;
      if (!parent2)
        return v;
      v = parent2;
    }
  }
  replaceChildren(from, to, children2 = noChildren) {
    this.markDirty();
    for (let i2 = from; i2 < to; i2++) {
      let child2 = this.children[i2];
      if (child2.parent == this && children2.indexOf(child2) < 0)
        child2.destroy();
    }
    if (children2.length < 250)
      this.children.splice(from, to - from, ...children2);
    else
      this.children = [].concat(this.children.slice(0, from), children2, this.children.slice(to));
    for (let i2 = 0; i2 < children2.length; i2++)
      children2[i2].setParent(this);
  }
  ignoreMutation(_rec) {
    return false;
  }
  ignoreEvent(_event) {
    return false;
  }
  childCursor(pos = this.length) {
    return new ChildCursor(this.children, pos, this.children.length);
  }
  childPos(pos, bias = 1) {
    return this.childCursor().findPos(pos, bias);
  }
  toString() {
    let name3 = this.constructor.name.replace("View", "");
    return name3 + (this.children.length ? "(" + this.children.join() + ")" : this.length ? "[" + (name3 == "Text" ? this.text : this.length) + "]" : "") + (this.breakAfter ? "#" : "");
  }
  static get(node) {
    return node.cmView;
  }
  get isEditable() {
    return true;
  }
  get isWidget() {
    return false;
  }
  get isHidden() {
    return false;
  }
  merge(from, to, source3, 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 child2 of this.children)
      if (child2.parent == this)
        child2.destroy();
    this.parent = null;
  }
};
ContentView.prototype.breakAfter = 0;
function rm$1(dom) {
  let next2 = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next2;
}
var ChildCursor = class {
  constructor(children2, pos, i2) {
    this.children = children2;
    this.pos = pos;
    this.i = i2;
    this.off = 0;
  }
  findPos(pos, bias = 1) {
    for (; ; ) {
      if (pos > this.pos || pos == this.pos && (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
        this.off = pos - this.pos;
        return this;
      }
      let next2 = this.children[--this.i];
      this.pos -= next2.length + next2.breakAfter;
    }
  }
};
function replaceRange(parent2, fromI, fromOff, toI, toOff, insert2, breakAtStart, openStart, openEnd) {
  let { children: children2 } = parent2;
  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)
    parent2.replaceChildren(fromI, toI, insert2);
}
function mergeChildrenInto(parent2, from, to, insert2, openStart, openEnd) {
  let cur2 = parent2.childCursor();
  let { i: toI, off: toOff } = cur2.findPos(to, 1);
  let { i: fromI, off: fromOff } = cur2.findPos(from, -1);
  let dLen = from - to;
  for (let view of insert2)
    dLen += view.length;
  parent2.length += dLen;
  replaceRange(parent2, fromI, fromOff, toI, toOff, insert2, 0, openStart, openEnd);
}
var nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
var doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
var ie_edge = /* @__PURE__ */ /Edge\/(\d+)/.exec(nav.userAgent);
var ie_upto10 = /* @__PURE__ */ /MSIE \d/.test(nav.userAgent);
var ie_11up = /* @__PURE__ */ /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
var ie2 = !!(ie_upto10 || ie_11up || ie_edge);
var gecko = !ie2 && /* @__PURE__ */ /gecko\/(\d+)/i.test(nav.userAgent);
var chrome = !ie2 && /* @__PURE__ */ /Chrome\/(\d+)/.exec(nav.userAgent);
var webkit = "webkitFontSmoothing" in doc.documentElement.style;
var safari = !ie2 && /* @__PURE__ */ /Apple Computer/.test(nav.vendor);
var 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: ie2,
  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"
};
var MaxJoinLen = 256;
var TextView = 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, track) {
    if (!this.dom)
      this.createDOM();
    if (this.dom.nodeValue != this.text) {
      if (track && track.node == this.dom)
        track.written = true;
      this.dom.nodeValue = this.text;
    }
  }
  reuseDOM(dom) {
    if (dom.nodeType == 3)
      this.createDOM(dom);
  }
  merge(from, to, source3) {
    if (this.flags & 8 || source3 && (!(source3 instanceof _TextView) || this.length - (to - from) + source3.length > MaxJoinLen || source3.flags & 8))
      return false;
    this.text = this.text.slice(0, from) + (source3 ? source3.text : "") + this.text.slice(to);
    this.markDirty();
    return true;
  }
  split(from) {
    let result = new _TextView(this.text.slice(from));
    this.text = this.text.slice(0, from);
    this.markDirty();
    result.flags |= this.flags & 8;
    return result;
  }
  localPosFromDOM(node, offset) {
    return node == this.dom ? offset : offset ? this.text.length : 0;
  }
  domAtPos(pos) {
    return new DOMPos(this.dom, pos);
  }
  domBoundsAround(_from, _to, offset) {
    return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };
  }
  coordsAt(pos, side) {
    return textCoords(this.dom, pos, side);
  }
};
var MarkView = class _MarkView extends ContentView {
  constructor(mark, children2 = [], length = 0) {
    super();
    this.mark = mark;
    this.children = children2;
    this.length = length;
    for (let ch of children2)
      ch.setParent(this);
  }
  setAttrs(dom) {
    clearAttributes(dom);
    if (this.mark.class)
      dom.className = this.mark.class;
    if (this.mark.attrs)
      for (let name3 in this.mark.attrs)
        dom.setAttribute(name3, this.mark.attrs[name3]);
    return dom;
  }
  canReuseDOM(other) {
    return super.canReuseDOM(other) && !((this.flags | other.flags) & 8);
  }
  reuseDOM(node) {
    if (node.nodeName == this.mark.tagName.toUpperCase()) {
      this.setDOM(node);
      this.flags |= 4 | 2;
    }
  }
  sync(view, track) {
    if (!this.dom)
      this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));
    else if (this.flags & 4)
      this.setAttrs(this.dom);
    super.sync(view, track);
  }
  merge(from, to, source3, _hasStart, openStart, openEnd) {
    if (source3 && (!(source3 instanceof _MarkView && source3.mark.eq(this.mark)) || from && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    mergeChildrenInto(this, from, to, source3 ? source3.children.slice() : [], openStart - 1, openEnd - 1);
    this.markDirty();
    return true;
  }
  split(from) {
    let result = [], off = 0, detachFrom = -1, i2 = 0;
    for (let elt of this.children) {
      let end = off + elt.length;
      if (end > from)
        result.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, result, length);
  }
  domAtPos(pos) {
    return inlineDOMAtPos(this, pos);
  }
  coordsAt(pos, side) {
    return coordsInChildren(this, pos, side);
  }
};
function textCoords(text2, pos, side) {
  let length = text2.nodeValue.length;
  if (pos > length)
    pos = length;
  let from = pos, to = pos, flatten2 = 0;
  if (pos == 0 && side < 0 || pos == length && side >= 0) {
    if (!(browser.chrome || browser.gecko)) {
      if (pos) {
        from--;
        flatten2 = 1;
      } else if (to < length) {
        to++;
        flatten2 = -1;
      }
    }
  } else {
    if (side < 0)
      from--;
    else if (to < length)
      to++;
  }
  let rects = textRange(text2, from, to).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;
}
var WidgetView = 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 result = _WidgetView.create(this.widget, this.length - from, this.side);
    this.length -= from;
    return result;
  }
  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, to, source3, hasStart, openStart, openEnd) {
    if (source3 && (!(source3 instanceof _WidgetView) || !this.widget.compare(source3.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    this.length = from + (source3 ? source3.length : 0) + (this.length - to);
    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(event2) {
    return this.widget.ignoreEvent(event2);
  }
  get overrideDOMText() {
    if (this.length == 0)
      return Text2.empty;
    let top3 = this;
    while (top3.parent)
      top3 = top3.parent;
    let { view } = top3, text2 = view && view.state.doc, start2 = this.posAtStart;
    return text2 ? text2.slice(start2, start2 + this.length) : Text2.empty;
  }
  domAtPos(pos) {
    return (this.length ? pos == 0 : this.side > 0) ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
  }
  domBoundsAround() {
    return null;
  }
  coordsAt(pos, side) {
    let custom2 = this.widget.coordsAt(this.dom, pos, side);
    if (custom2)
      return custom2;
    let rects = this.dom.getClientRects(), rect = null;
    if (!rects.length)
      return null;
    let fromBack = this.side ? this.side < 0 : pos > 0;
    for (let i2 = fromBack ? rects.length - 1 : 0; ; i2 += fromBack ? -1 : 1) {
      rect = rects[i2];
      if (pos > 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);
  }
};
var WidgetBufferView = 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(pos) {
    return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom);
  }
  localPosFromDOM() {
    return 0;
  }
  domBoundsAround() {
    return null;
  }
  coordsAt(pos) {
    return this.dom.getBoundingClientRect();
  }
  get overrideDOMText() {
    return Text2.empty;
  }
  get isHidden() {
    return true;
  }
};
TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
function inlineDOMAtPos(parent2, pos) {
  let dom = parent2.dom, { children: children2 } = parent2, i2 = 0;
  for (let off = 0; i2 < children2.length; i2++) {
    let child2 = children2[i2], end = off + child2.length;
    if (end == off && child2.getSide() <= 0)
      continue;
    if (pos > off && pos < end && child2.dom.parentNode == dom)
      return child2.domAtPos(pos - off);
    if (pos <= off)
      break;
    off = end;
  }
  for (let j = i2; j > 0; j--) {
    let prev = children2[j - 1];
    if (prev.dom.parentNode == dom)
      return prev.domAtPos(prev.length);
  }
  for (let j = i2; j < children2.length; j++) {
    let next2 = children2[j];
    if (next2.dom.parentNode == dom)
      return next2.domAtPos(0);
  }
  return new DOMPos(dom, 0);
}
function joinInlineInto(parent2, view, open) {
  let last, { children: children2 } = parent2;
  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(parent2);
  }
  parent2.length += view.length;
}
function coordsInChildren(view, pos, side) {
  let before = null, beforePos = -1, after = null, afterPos = -1;
  function scan(view2, pos2) {
    for (let i2 = 0, off = 0; i2 < view2.children.length && off <= pos2; i2++) {
      let child2 = view2.children[i2], end = off + child2.length;
      if (end >= pos2) {
        if (child2.children.length) {
          scan(child2, pos2 - off);
        } else if ((!after || after.isHidden && side > 0) && (end > pos2 || off == end && child2.getSide() > 0)) {
          after = child2;
          afterPos = pos2 - off;
        } else if (off < pos2 || off == end && child2.getSide() < 0 && !child2.isHidden) {
          before = child2;
          beforePos = pos2 - off;
        }
      }
      off = end;
    }
  }
  scan(view, pos);
  let target = (side < 0 ? before : after) || before || after;
  if (target)
    return target.coordsAt(Math.max(0, target == 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(source3, target) {
  for (let name3 in source3) {
    if (name3 == "class" && target.class)
      target.class += " " + source3.class;
    else if (name3 == "style" && target.style)
      target.style += ";" + source3.style;
    else
      target[name3] = source3[name3];
  }
  return target;
}
var noAttrs = /* @__PURE__ */ Object.create(null);
function attrsEq(a, b, ignore) {
  if (a == b)
    return true;
  if (!a)
    a = noAttrs;
  if (!b)
    b = noAttrs;
  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 name3 in prev)
      if (!(attrs && name3 in attrs)) {
        changed = true;
        if (name3 == "style")
          dom.style.cssText = "";
        else
          dom.removeAttribute(name3);
      }
  }
  if (attrs) {
    for (let name3 in attrs)
      if (!(prev && prev[name3] == attrs[name3])) {
        changed = true;
        if (name3 == "style")
          dom.style.cssText = attrs[name3];
        else
          dom.setAttribute(name3, attrs[name3]);
      }
  }
  return changed;
}
function getAttrs(dom) {
  let attrs = /* @__PURE__ */ Object.create(null);
  for (let i2 = 0; i2 < dom.attributes.length; i2++) {
    let attr2 = dom.attributes[i2];
    attrs[attr2.name] = attr2.value;
  }
  return attrs;
}
var WidgetType = class {
  /**
  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(event2) {
    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, pos, 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 = {}));
var Decoration = class 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: start2, end } = getInclusive(spec, block2);
      startSide = (start2 ? 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, sort2 = false) {
    return RangeSet.of(of, sort2);
  }
  /**
  @internal
  */
  hasHeight() {
    return this.widget ? this.widget.estimatedHeight > -1 : false;
  }
};
Decoration.none = RangeSet.empty;
var MarkDecoration = class _MarkDecoration extends Decoration {
  constructor(spec) {
    let { start: start2, end } = getInclusive(spec);
    super(start2 ? -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, _b;
    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 || ((_b = other.attrs) === null || _b === void 0 ? void 0 : _b.class)) && attrsEq(this.attrs, other.attrs, "class");
  }
  range(from, to = from) {
    if (from >= to)
      throw new RangeError("Mark decorations may not be empty");
    return super.range(from, to);
  }
};
MarkDecoration.prototype.point = false;
var LineDecoration = 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, to = from) {
    if (to != from)
      throw new RangeError("Line decoration ranges must be zero-length");
    return super.range(from, to);
  }
};
LineDecoration.prototype.mapMode = MapMode.TrackBefore;
LineDecoration.prototype.point = true;
var PointDecoration = 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, to = from) {
    if (this.isReplace && (from > to || from == to && this.startSide > 0 && this.endSide <= 0))
      throw new RangeError("Invalid range for replacement decoration");
    if (!this.isReplace && to != from)
      throw new RangeError("Widget decorations can only have zero-length ranges");
    return super.range(from, to);
  }
};
PointDecoration.prototype.point = true;
function getInclusive(spec, block2 = false) {
  let { inclusiveStart: start2, inclusiveEnd: end } = spec;
  if (start2 == null)
    start2 = spec.inclusive;
  if (end == null)
    end = spec.inclusive;
  return { start: start2 !== null && start2 !== void 0 ? start2 : block2, end: end !== null && end !== void 0 ? end : block2 };
}
function widgetsEq(a, b) {
  return a == b || !!(a && b && a.compare(b));
}
function addRange(from, to, ranges, margin = 0) {
  let last = ranges.length - 1;
  if (last >= 0 && ranges[last] + margin >= from)
    ranges[last] = Math.max(ranges[last], to);
  else
    ranges.push(from, to);
}
var LineView = 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, to, source3, hasStart, openStart, openEnd) {
    if (source3) {
      if (!(source3 instanceof _LineView))
        return false;
      if (!this.dom)
        source3.transferDOM(this);
    }
    if (hasStart)
      this.setDeco(source3 ? source3.attrs : null);
    mergeChildrenInto(this, from, to, source3 ? source3.children.slice() : [], openStart, openEnd);
    return true;
  }
  split(at) {
    let end = new _LineView();
    end.breakAfter = this.breakAfter;
    if (this.length == 0)
      return end;
    let { i: i2, off } = this.childPos(at);
    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 j = i2; j < this.children.length; j++)
      end.append(this.children[j], 0);
    while (i2 > 0 && this.children[i2 - 1].length == 0)
      this.children[--i2].destroy();
    this.children.length = i2;
    this.markDirty();
    this.length = at;
    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(child2, openStart) {
    joinInlineInto(this, child2, 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(pos) {
    return inlineDOMAtPos(this, pos);
  }
  reuseDOM(node) {
    if (node.nodeName == "DIV") {
      this.setDOM(node);
      this.flags |= 4 | 2;
    }
  }
  sync(view, track) {
    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, track);
    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((ch) => ch 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 child2 of this.children) {
      if (!(child2 instanceof TextView) || /[^ -~]/.test(child2.text))
        return null;
      let rects = clientRectsFor(child2.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(pos, side) {
    let rect = coordsInChildren(this, pos, 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, pos) {
    for (let i2 = 0, off = 0; i2 < docView.children.length; i2++) {
      let block2 = docView.children[i2], end = off + block2.length;
      if (end >= pos) {
        if (block2 instanceof _LineView)
          return block2;
        if (end > pos)
          break;
      }
      off = end + block2.breakAfter;
    }
    return null;
  }
};
var BlockWidgetView = 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, to, source3, _takeDeco, openStart, openEnd) {
    if (source3 && (!(source3 instanceof _BlockWidgetView) || !this.widget.compare(source3.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    this.length = from + (source3 ? source3.length : 0) + (this.length - to);
    return true;
  }
  domAtPos(pos) {
    return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
  }
  split(at) {
    let len = this.length - at;
    this.length = at;
    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) : Text2.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(event2) {
    return this.widget.ignoreEvent(event2);
  }
  get isEditable() {
    return false;
  }
  get isWidget() {
    return true;
  }
  coordsAt(pos, side) {
    let custom2 = this.widget.coordsAt(this.dom, pos, side);
    if (custom2)
      return custom2;
    if (this.widget instanceof BlockGapWidget)
      return null;
    return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos == 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;
  }
};
var BlockGapWidget = class 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;
  }
};
var ContentBuilder = class _ContentBuilder {
  constructor(doc2, pos, end, disallowBlockEffectsFor) {
    this.doc = doc2;
    this.pos = pos;
    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 = pos;
  }
  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(active = this.bufferMarks) {
    if (this.pendingBuffer) {
      this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.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, active, openStart) {
    while (length > 0) {
      if (this.textOff == this.text.length) {
        let { value, 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 = value;
          this.textOff = 0;
        }
      }
      let take = Math.min(
        this.text.length - this.textOff,
        length,
        512
        /* T.Chunk */
      );
      this.flushBuffer(active.slice(active.length - openStart));
      this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
      this.atCursorPos = true;
      this.textOff += take;
      length -= take;
      openStart = 0;
    }
  }
  span(from, to, active, openStart) {
    this.buildText(to - from, active, openStart);
    this.pos = to;
    if (this.openStart < 0)
      this.openStart = openStart;
  }
  point(from, to, deco, active, openStart, index3) {
    if (this.disallowBlockEffectsFor[index3] && deco instanceof PointDecoration) {
      if (deco.block)
        throw new RangeError("Block decorations may not be specified via plugins");
      if (to > this.doc.lineAt(this.pos).to)
        throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
    }
    let len = to - 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 <= active.length && (from < to || deco.startSide > 0);
        let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);
        let line = this.getLine();
        if (this.pendingBuffer == 2 && !cursorBefore && !view.isEditable)
          this.pendingBuffer = 0;
        this.flushBuffer(active);
        if (cursorBefore) {
          line.append(wrapMarks(new WidgetBufferView(1), active), openStart);
          openStart = active.length + Math.max(0, openStart - active.length);
        }
        line.append(wrapMarks(view, active), openStart);
        this.atCursorPos = cursorAfter;
        this.pendingBuffer = !cursorAfter ? 0 : from < to || openStart > active.length ? 1 : 2;
        if (this.pendingBuffer)
          this.bufferMarks = active.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 = to;
    }
    if (this.openStart < 0)
      this.openStart = openStart;
  }
  static build(text2, from, to, decorations2, dynamicDecorationMap) {
    let builder = new _ContentBuilder(text2, from, to, dynamicDecorationMap);
    builder.openEnd = RangeSet.spans(decorations2, from, to, builder);
    if (builder.openStart < 0)
      builder.openStart = builder.openEnd;
    builder.finish(builder.openEnd);
    return builder;
  }
};
function wrapMarks(view, active) {
  for (let mark of active)
    view = new MarkView(mark, [view], view.length);
  return view;
}
var NullWidget = class 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 = {}));
var LTR = Direction.LTR;
var RTL = Direction.RTL;
function dec(str) {
  let result = [];
  for (let i2 = 0; i2 < str.length; i2++)
    result.push(1 << +str[i2]);
  return result;
}
var LowTypes = /* @__PURE__ */ dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
var ArabicTypes = /* @__PURE__ */ dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
var Brackets = /* @__PURE__ */ Object.create(null);
var BracketStack = [];
for (let p of ["()", "[]", "{}"]) {
  let l = /* @__PURE__ */ p.charCodeAt(0), r2 = /* @__PURE__ */ p.charCodeAt(1);
  Brackets[l] = r2;
  Brackets[r2] = -l;
}
function charType(ch) {
  return ch <= 247 ? LowTypes[ch] : 1424 <= ch && ch <= 1524 ? 2 : 1536 <= ch && ch <= 1785 ? ArabicTypes[ch - 1536] : 1774 <= ch && ch <= 2220 ? 4 : 8192 <= ch && ch <= 8204 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : 1;
}
var BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
var BidiSpan = class {
  /**
  The direction of this span.
  */
  get dir() {
    return this.level % 2 ? RTL : LTR;
  }
  /**
  @internal
  */
  constructor(from, to, level) {
    this.from = from;
    this.to = to;
    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, index3, level, assoc) {
    let maybe = -1;
    for (let i2 = 0; i2 < order.length; i2++) {
      let span = order[i2];
      if (span.from <= index3 && span.to >= index3) {
        if (span.level == level)
          return i2;
        if (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index3 : span.to > index3 : 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;
}
var types = [];
function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
  for (let iI = 0; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    let prevType = iI ? 256 : outerType;
    for (let i2 = from, prev = prevType, prevStrong = prevType; i2 < to; i2++) {
      let type = charType(line.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 < to; i2++) {
      let type = types[i2];
      if (type == 128) {
        if (i2 < to - 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 < to && types[end] == 64)
          end++;
        let replace2 = i2 && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
        for (let j = i2; j < end; j++)
          types[j] = replace2;
        i2 = end - 1;
      } else if (type == 8 && prevStrong == 1) {
        types[i2] = 1;
      }
      prev = type;
      if (type & 7)
        prevStrong = type;
    }
  }
}
function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
  let oppositeType = outerType == 1 ? 2 : 1;
  for (let iI = 0, sI = 0, context2 = 0; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i2 = from, ch, br, type; i2 < to; i2++) {
      if (br = Brackets[ch = line.charCodeAt(i2)]) {
        if (br < 0) {
          for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
            if (BracketStack[sJ + 1] == -br) {
              let flags2 = BracketStack[sJ + 2];
              let type2 = flags2 & 2 ? outerType : !(flags2 & 4) ? 0 : flags2 & 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++] = ch;
          BracketStack[sI++] = context2;
        }
      } else if ((type = types[i2]) == 2 || type == 1) {
        let embed = type == outerType;
        context2 = 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, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i2 = from; i2 < to; ) {
      let type = types[i2];
      if (type == 256) {
        let end = i2 + 1;
        for (; ; ) {
          if (end == to) {
            if (iI == isolates.length)
              break;
            end = isolates[iI++].to;
            to = 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 j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i2; ) {
          if (j == fromJ) {
            j = isolates[--jI].from;
            fromJ = jI ? isolates[jI - 1].to : rFrom;
          }
          types[--j] = replace2;
        }
        i2 = end;
      } else {
        prev = type;
        i2++;
      }
    }
  }
}
function emitSpans(line, from, to, level, baseLevel, isolates, order) {
  let ourType = level % 2 ? 2 : 1;
  if (level % 2 == baseLevel % 2) {
    for (let iCh = from, iI = 0; iCh < to; ) {
      let sameDir = true, isNum = false;
      if (iI == isolates.length || iCh < isolates[iI].from) {
        let next2 = types[iCh];
        if (next2 != ourType) {
          sameDir = false;
          isNum = next2 == 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 == to)
                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(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
            iCh = iso.to;
          }
          iScan = iso.to;
        } else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
          break;
        } else {
          iScan++;
        }
      }
      if (recurse)
        emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
      else if (iCh < iScan)
        order.push(new BidiSpan(iCh, iScan, localLevel));
      iCh = iScan;
    }
  } else {
    for (let iCh = to, iI = isolates.length; iCh > from; ) {
      let sameDir = true, isNum = false;
      if (!iI || iCh > isolates[iI - 1].to) {
        let next2 = types[iCh - 1];
        if (next2 != ourType) {
          sameDir = false;
          isNum = next2 == 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(line, 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(line, iScan, iCh, level + 1, baseLevel, recurse, order);
      else if (iScan < iCh)
        order.push(new BidiSpan(iScan, iCh, localLevel));
      iCh = iScan;
    }
  }
}
function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
  let outerType = level % 2 ? 2 : 1;
  computeCharTypes(line, from, to, isolates, outerType);
  processBracketPairs(line, from, to, isolates, outerType);
  processNeutrals(from, to, isolates, outerType);
  emitSpans(line, from, to, level, baseLevel, isolates, order);
}
function computeOrder(line, direction, isolates) {
  if (!line)
    return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
  if (direction == LTR && !isolates.length && !BidiRE.test(line))
    return trivialOrder(line.length);
  if (isolates.length)
    while (line.length > types.length)
      types[types.length] = 256;
  let order = [], level = direction == LTR ? 0 : 1;
  computeSectionOrder(line, level, level, isolates, 0, line.length, order);
  return order;
}
function trivialOrder(length) {
  return [new BidiSpan(0, length, 0)];
}
var movedOver = "";
function moveVisually(line, order, dir, start2, forward) {
  var _a2;
  let startIndex = start2.head - line.from;
  let spanI = BidiSpan.find(order, startIndex, (_a2 = start2.bidiLevel) !== null && _a2 !== void 0 ? _a2 : -1, start2.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 = findClusterBreak2(line.text, startIndex, span.forward(forward, dir));
  if (nextIndex < span.from || nextIndex > span.to)
    nextIndex = spanEnd;
  movedOver = line.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) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
  return EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);
}
function autoDirection(text2, from, to) {
  for (let i2 = from; i2 < to; i2++) {
    let type = charType(text2.charCodeAt(i2));
    if (type == 1)
      return LTR;
    if (type == 2 || type == 4)
      return RTL;
  }
  return LTR;
}
var clickAddsSelectionRange = /* @__PURE__ */ Facet.define();
var dragMovesSelection$1 = /* @__PURE__ */ Facet.define();
var mouseSelectionStyle = /* @__PURE__ */ Facet.define();
var exceptionSink = /* @__PURE__ */ Facet.define();
var updateListener = /* @__PURE__ */ Facet.define();
var inputHandler = /* @__PURE__ */ Facet.define();
var focusChangeEffect = /* @__PURE__ */ Facet.define();
var clipboardInputFilter = /* @__PURE__ */ Facet.define();
var clipboardOutputFilter = /* @__PURE__ */ Facet.define();
var perLineTextDirection = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
var nativeSelectionHidden = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
var scrollHandler = /* @__PURE__ */ Facet.define();
var ScrollTarget = class _ScrollTarget {
  constructor(range2, y2 = "nearest", x2 = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
    this.range = range2;
    this.y = y2;
    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(state2) {
    return this.range.to <= state2.doc.length ? this : new _ScrollTarget(EditorSelection.cursor(state2.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
  }
};
var scrollIntoView = /* @__PURE__ */ StateEffect.define({ map: (t4, ch) => t4.map(ch) });
var setEditContextFormatting = /* @__PURE__ */ StateEffect.define();
function logException(state2, exception, context2) {
  let handler = state2.facet(exceptionSink);
  if (handler.length)
    handler[0](exception);
  else if (window.onerror)
    window.onerror(String(exception), context2, void 0, void 0, exception);
  else if (context2)
    console.error(context2 + ":", exception);
  else
    console.error(exception);
}
var editable = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : true });
var nextPluginID = 0;
var viewPlugin = /* @__PURE__ */ Facet.define();
var ViewPlugin = class _ViewPlugin {
  constructor(id3, create, domEventHandlers, domEventObservers, buildExtensions) {
    this.id = id3;
    this.create = create;
    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(create, spec) {
    const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
    return new _ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, (plugin) => {
      let ext2 = [viewPlugin.of(plugin)];
      if (deco)
        ext2.push(decorations.of((view) => {
          let pluginInst = view.plugin(plugin);
          return pluginInst ? deco(pluginInst) : Decoration.none;
        }));
      if (provide)
        ext2.push(provide(plugin));
      return ext2;
    });
  }
  /**
  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);
  }
};
var PluginInstance = class {
  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 update3 = this.mustUpdate;
      this.mustUpdate = null;
      if (this.value.update) {
        try {
          this.value.update(update3);
        } catch (e) {
          logException(update3.state, e, "CodeMirror plugin crashed");
          if (this.value.destroy)
            try {
              this.value.destroy();
            } catch (_2) {
            }
          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;
  }
};
var editorAttributes = /* @__PURE__ */ Facet.define();
var contentAttributes = /* @__PURE__ */ Facet.define();
var decorations = /* @__PURE__ */ Facet.define();
var outerDecorations = /* @__PURE__ */ Facet.define();
var atomicRanges = /* @__PURE__ */ Facet.define();
var bidiIsolatedRanges = /* @__PURE__ */ Facet.define();
function getIsolatedRanges(view, line) {
  let isolates = view.state.facet(bidiIsolatedRanges);
  if (!isolates.length)
    return isolates;
  let sets = isolates.map((i2) => i2 instanceof Function ? i2(view) : i2);
  let result = [];
  RangeSet.spans(sets, line.from, line.to, {
    point() {
    },
    span(fromDoc, toDoc, active, open) {
      let from = fromDoc - line.from, to = toDoc - line.from;
      let level = result;
      for (let i2 = active.length - 1; i2 >= 0; i2--, open--) {
        let direction = active[i2].spec.bidiIsolate, update3;
        if (direction == null)
          direction = autoDirection(line.text, from, to);
        if (open > 0 && level.length && (update3 = level[level.length - 1]).to == from && update3.direction == direction) {
          update3.to = to;
          level = update3.inner;
        } else {
          let add3 = { from, to, direction, inner: [] };
          level.push(add3);
          level = add3.inner;
        }
      }
    }
  });
  return result;
}
var scrollMargins = /* @__PURE__ */ Facet.define();
function getScrollMargins(view) {
  let left2 = 0, right2 = 0, top3 = 0, bottom2 = 0;
  for (let source3 of view.state.facet(scrollMargins)) {
    let m2 = source3(view);
    if (m2) {
      if (m2.left != null)
        left2 = Math.max(left2, m2.left);
      if (m2.right != null)
        right2 = Math.max(right2, m2.right);
      if (m2.top != null)
        top3 = Math.max(top3, m2.top);
      if (m2.bottom != null)
        bottom2 = Math.max(bottom2, m2.bottom);
    }
  }
  return { left: left2, right: right2, top: top3, bottom: bottom2 };
}
var styleModule = /* @__PURE__ */ Facet.define();
var ChangedRange = 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(set4) {
    let i2 = set4.length, me = this;
    for (; i2 > 0; i2--) {
      let range2 = set4[i2 - 1];
      if (range2.fromA > me.toA)
        continue;
      if (range2.toA < me.fromA)
        break;
      me = me.join(range2);
      set4.splice(i2 - 1, 1);
    }
    set4.splice(i2, 0, me);
    return set4;
  }
  static extendWithRanges(diff, ranges) {
    if (ranges.length == 0)
      return diff;
    let result = [];
    for (let dI = 0, rI = 0, posA = 0, posB = 0; ; dI++) {
      let next2 = dI == diff.length ? null : diff[dI], off = posA - posB;
      let end = next2 ? next2.fromB : 1e9;
      while (rI < ranges.length && ranges[rI] < end) {
        let from = ranges[rI], to = ranges[rI + 1];
        let fromB = Math.max(posB, from), toB = Math.min(end, to);
        if (fromB <= toB)
          new _ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);
        if (to > end)
          break;
        else
          rI += 2;
      }
      if (!next2)
        return result;
      new _ChangedRange(next2.fromA, next2.toA, next2.fromB, next2.toB).addToSet(result);
      posA = next2.toA;
      posB = next2.toB;
    }
  }
};
var ViewUpdate = class _ViewUpdate {
  constructor(view, state2, transactions) {
    this.view = view;
    this.state = state2;
    this.transactions = transactions;
    this.flags = 0;
    this.startState = view.state;
    this.changes = ChangeSet.empty(this.startState.doc.length);
    for (let tr of transactions)
      this.changes = this.changes.compose(tr.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, state2, transactions) {
    return new _ViewUpdate(view, state2, 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((tr) => tr.selection);
  }
  /**
  @internal
  */
  get empty() {
    return this.flags == 0 && this.transactions.length == 0;
  }
};
var DocView = class 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(update3) {
    var _a2;
    let changedRanges = update3.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 = update3.changes.mapPos(this.minWidthFrom, 1);
        this.minWidthTo = update3.changes.mapPos(this.minWidthTo, 1);
      }
    }
    this.updateEditContextFormatting(update3);
    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(update3.changes, this.hasComposition) && !update3.selectionSet)
        readCompositionAt = update3.state.selection.main.head;
    }
    let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update3.changes, readCompositionAt) : null;
    this.domChanged = null;
    if (this.hasComposition) {
      this.markedForComposition.clear();
      let { from, to } = this.hasComposition;
      changedRanges = new ChangedRange(from, to, update3.changes.mapPos(from, -1), update3.changes.mapPos(to, 1)).addToSet(changedRanges.slice());
    }
    this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
    if ((browser.ie || browser.chrome) && !composition && update3 && update3.state.doc.lines != update3.startState.doc.lines)
      this.forceSelection = true;
    let prevDeco = this.decorations, deco = this.updateDeco();
    let decoDiff = findChangedDeco(prevDeco, deco, update3.changes);
    changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
    if (!(this.flags & 7) && changedRanges.length == 0) {
      return false;
    } else {
      this.updateInner(changedRanges, update3.startState.doc.length, composition);
      if (update3.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 track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : void 0;
      this.sync(this.view, track);
      this.flags &= ~7;
      if (track && (track.written || observer.selectionRange.focusNode != track.node))
        this.forceSelection = true;
      this.dom.style.height = "";
    });
    this.markedForComposition.forEach(
      (cView) => cView.flags &= ~8
      /* ViewFlag.Composition */
    );
    let gaps = [];
    if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) {
      for (let child2 of this.children)
        if (child2 instanceof BlockWidgetView && child2.widget instanceof BlockGapWidget)
          gaps.push(child2.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 next2 = i2 >= 0 ? ranges[i2] : null;
      if (!next2)
        break;
      let { fromA, toA, fromB, toB } = next2, 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(update3) {
    this.editContextFormatting = this.editContextFormatting.map(update3.changes);
    for (let tr of update3.transactions)
      for (let effect2 of tr.effects)
        if (effect2.is(setEditContextFormatting)) {
          this.editContextFormatting = effect2.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 line = new LineView();
    line.append(cur2, 0);
    return line;
  }
  fixCompositionDOM(composition) {
    let fix = (dom, cView2) => {
      cView2.flags |= 8 | (cView2.children.some(
        (c) => c.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 pos = this.childPos(composition.range.fromB, 1);
    let cView = this.children[pos.i];
    fix(composition.line, cView);
    for (let i2 = composition.marks.length - 1; i2 >= -1; i2--) {
      pos = cView.childPos(pos.off, 1);
      cView = cView.children[pos.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 head2 = 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 = head2 = 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(head2.node, head2.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(head2.node, head2.offset);
          } catch (_2) {
          }
        } else {
          let range2 = document.createRange();
          if (main.anchor > main.head)
            [anchor, head2] = [head2, anchor];
          range2.setEnd(head2.node, head2.offset);
          range2.setStart(anchor.node, anchor.offset);
          rawSel.removeAllRanges();
          rawSel.addRange(range2);
        }
        if (selectionNotFocus && this.view.root.activeElement == this.dom) {
          this.dom.blur();
          if (activeElt)
            activeElt.focus();
        }
      });
      this.view.observer.setSelectionRange(anchor, head2);
    }
    this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
    this.impreciseHead = head2.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 line = LineView.find(this, cursor.head);
    if (!line)
      return;
    let lineStart = line.posAtStart;
    if (cursor.head == lineStart || cursor.head == lineStart + line.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(pos) {
    let dom = this.dom, newPos;
    if (pos.node != dom)
      return pos;
    for (let i2 = pos.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 = pos.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) : pos;
  }
  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(node, offset) {
    let view = this.nearest(node);
    if (!view)
      throw new RangeError("Trying to find position for a DOM position outside of the document");
    return view.localPosFromDOM(node, offset) + view.posAtStart;
  }
  domAtPos(pos) {
    let { i: i2, off } = this.childCursor().findPos(pos, -1);
    for (; i2 < this.children.length - 1; ) {
      let child2 = this.children[i2];
      if (off < child2.length || child2 instanceof LineView)
        break;
      i2++;
      off = 0;
    }
    return this.children[i2].domAtPos(off);
  }
  coordsAt(pos, side) {
    let best = null, bestPos = 0;
    for (let off = this.length, i2 = this.children.length - 1; i2 >= 0; i2--) {
      let child2 = this.children[i2], end = off - child2.breakAfter, start2 = end - child2.length;
      if (end < pos)
        break;
      if (start2 <= pos && (start2 < pos || child2.covers(-1)) && (end > pos || child2.covers(1)) && (!best || child2 instanceof LineView && !(best instanceof LineView && side >= 0))) {
        best = child2;
        bestPos = start2;
      } else if (best && start2 == pos && end == pos && child2 instanceof BlockWidgetView && Math.abs(side) < 2) {
        if (child2.deco.startSide < 0)
          break;
        else if (i2)
          best = null;
      }
      off = start2;
    }
    return best ? best.coordsAt(pos - bestPos, side) : null;
  }
  coordsForChar(pos) {
    let { i: i2, off } = this.childPos(pos, 1), child2 = this.children[i2];
    if (!(child2 instanceof LineView))
      return null;
    while (child2.children.length) {
      let { i: i3, off: childOff } = child2.childPos(off, 1);
      for (; ; i3++) {
        if (i3 == child2.children.length)
          return null;
        if ((child2 = child2.children[i3]).length)
          break;
      }
      off = childOff;
    }
    if (!(child2 instanceof TextView))
      return null;
    let end = findClusterBreak2(child2.text, off);
    if (end == off)
      return null;
    let rects = textRange(child2.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 result = [], { from, to } = 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 pos = 0, i2 = 0; i2 < this.children.length; i2++) {
      let child2 = this.children[i2], end = pos + child2.length;
      if (end > to)
        break;
      if (pos >= from) {
        let childRect = child2.dom.getBoundingClientRect();
        result.push(childRect.height);
        if (isWider) {
          let last = child2.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 = pos;
              this.minWidthTo = end;
            }
          }
        }
      }
      pos = end + child2.breakAfter;
    }
    return result;
  }
  textDirectionAt(pos) {
    let { i: i2 } = this.childPos(pos, 1);
    return getComputedStyle(this.children[i2].dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
  }
  measureTextSize() {
    for (let child2 of this.children) {
      if (child2 instanceof LineView) {
        let measure = child2.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(pos = this.length) {
    let i2 = this.children.length;
    if (i2)
      pos -= this.children[--i2].length;
    return new ChildCursor(this.children, pos, i2);
  }
  computeBlockGapDeco() {
    let deco = [], vs = this.view.viewState;
    for (let pos = 0, i2 = 0; ; i2++) {
      let next2 = i2 == vs.viewports.length ? null : vs.viewports[i2];
      let end = next2 ? next2.from - 1 : this.length;
      if (end > pos) {
        let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
        deco.push(Decoration.replace({
          widget: new BlockGapWidget(height),
          block: true,
          inclusive: true,
          isBlockGap: true
        }).range(pos, end));
      }
      if (!next2)
        break;
      pos = next2.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(target) {
    if (target.isSnapshot) {
      let ref = this.view.viewState.lineBlockAt(target.range.head);
      this.view.scrollDOM.scrollTop = ref.top - target.yMargin;
      this.view.scrollDOM.scrollLeft = target.xMargin;
      return;
    }
    for (let handler of this.view.state.facet(scrollHandler)) {
      try {
        if (handler(this.view, target.range, target))
          return true;
      } catch (e) {
        logException(this.view.state, e, "scroll handler");
      }
    }
    let { range: range2 } = target;
    let rect = this.coordsAt(range2.head, range2.empty ? range2.assoc : range2.head > range2.anchor ? -1 : 1), other;
    if (!rect)
      return;
    if (!range2.empty && (other = this.coordsAt(range2.anchor, range2.anchor > range2.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, range2.head < range2.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
  }
};
function betweenUneditable(pos) {
  return pos.node.nodeType == 1 && pos.node.firstChild && (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.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 } = 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 range2 = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);
  let marks2 = [];
  for (let parent2 = textNode.parentNode; ; parent2 = parent2.parentNode) {
    let parentView = ContentView.get(parent2);
    if (parentView instanceof MarkView)
      marks2.push({ node: parent2, deco: parentView.mark });
    else if (parentView instanceof LineView || parent2.nodeName == "DIV" && parent2.parentNode == view.contentDOM)
      return { range: range2, text: textNode, marks: marks2, line: parent2 };
    else if (parent2 != view.contentDOM)
      marks2.push({ node: parent2, deco: new MarkDecoration({
        inclusive: true,
        attributes: getAttrs(parent2),
        tagName: parent2.tagName.toLowerCase()
      }) });
    else
      return null;
  }
}
function nextToUneditable(node, offset) {
  if (node.nodeType != 1)
    return 0;
  return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 : 0);
}
var DecorationComparator$1 = class DecorationComparator {
  constructor() {
    this.changes = [];
  }
  compareRange(from, to) {
    addRange(from, to, this.changes);
  }
  comparePoint(from, to) {
    addRange(from, to, this.changes);
  }
  boundChange(pos) {
    addRange(pos, pos, this.changes);
  }
};
function findChangedDeco(a, b, diff) {
  let comp = new DecorationComparator$1();
  RangeSet.compare(a, b, diff, comp);
  return comp.changes;
}
function inUneditable(node, inside2) {
  for (let cur2 = node; 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, to) => {
      if (from < composition.to && to > composition.from)
        touched = true;
    });
  return touched;
}
function groupAt(state2, pos, bias = 1) {
  let categorize = state2.charCategorizer(pos);
  let line = state2.doc.lineAt(pos), linePos = pos - line.from;
  if (line.length == 0)
    return EditorSelection.cursor(pos);
  if (linePos == 0)
    bias = 1;
  else if (linePos == line.length)
    bias = -1;
  let from = linePos, to = linePos;
  if (bias < 0)
    from = findClusterBreak2(line.text, linePos, false);
  else
    to = findClusterBreak2(line.text, linePos);
  let cat = categorize(line.text.slice(from, to));
  while (from > 0) {
    let prev = findClusterBreak2(line.text, from, false);
    if (categorize(line.text.slice(prev, from)) != cat)
      break;
    from = prev;
  }
  while (to < line.length) {
    let next2 = findClusterBreak2(line.text, to);
    if (categorize(line.text.slice(to, next2)) != cat)
      break;
    to = next2;
  }
  return EditorSelection.range(from + line.from, to + line.from);
}
function getdx(x2, rect) {
  return rect.left > x2 ? rect.left - x2 : Math.max(0, x2 - rect.right);
}
function getdy(y2, rect) {
  return rect.top > y2 ? rect.top - y2 : Math.max(0, y2 - rect.bottom);
}
function yOverlap(a, b) {
  return a.top < b.bottom - 1 && a.bottom > b.top + 1;
}
function upTop(rect, top3) {
  return top3 < rect.top ? { top: top3, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;
}
function upBot(rect, bottom2) {
  return bottom2 > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom: bottom2 } : rect;
}
function domPosAtCoords(parent2, x2, y2) {
  let closest, closestRect, closestX, closestY, closestOverlap = false;
  let above, below, aboveRect, belowRect;
  for (let child2 = parent2.firstChild; child2; child2 = child2.nextSibling) {
    let rects = clientRectsFor(child2);
    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(y2, rect);
      if (dx == 0 && dy == 0)
        return child2.nodeType == 3 ? domPosInText(child2, x2, y2) : domPosAtCoords(child2, x2, y2);
      if (!closest || closestY > dy || closestY == dy && closestX > dx) {
        closest = child2;
        closestRect = rect;
        closestX = dx;
        closestY = dy;
        let side = dy ? y2 < 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 (y2 > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
          above = child2;
          aboveRect = rect;
        } else if (y2 < rect.top && (!belowRect || belowRect.top > rect.top)) {
          below = child2;
          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 >= y2) {
    closest = above;
    closestRect = aboveRect;
  } else if (belowRect && belowRect.top <= y2) {
    closest = below;
    closestRect = belowRect;
  }
  if (!closest)
    return { node: parent2, offset: 0 };
  let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x2));
  if (closest.nodeType == 3)
    return domPosInText(closest, clipX, y2);
  if (closestOverlap && closest.contentEditable != "false")
    return domPosAtCoords(closest, clipX, y2);
  let offset = Array.prototype.indexOf.call(parent2.childNodes, closest) + (x2 >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);
  return { node: parent2, offset };
}
function domPosInText(node, x2, y2) {
  let len = node.nodeValue.length;
  let closestOffset = -1, closestDY = 1e9, generalSide = 0;
  for (let i2 = 0; i2 < len; i2++) {
    let rects = textRange(node, i2, i2 + 1).getClientRects();
    for (let j = 0; j < rects.length; j++) {
      let rect = rects[j];
      if (rect.top == rect.bottom)
        continue;
      if (!generalSide)
        generalSide = x2 - rect.left;
      let dy = (rect.top > y2 ? rect.top - y2 : y2 - rect.bottom) - 1;
      if (rect.left - 1 <= x2 && rect.right + 1 >= x2 && dy < closestDY) {
        let right2 = x2 >= (rect.left + rect.right) / 2, after = right2;
        if (browser.chrome || browser.gecko) {
          let rectBefore = textRange(node, i2).getBoundingClientRect();
          if (rectBefore.left == rect.right)
            after = !right2;
        }
        if (dy <= 0)
          return { node, offset: i2 + (after ? 1 : 0) };
        closestOffset = i2 + (after ? 1 : 0);
        closestDY = dy;
      }
    }
  }
  return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 };
}
function posAtCoords(view, coords, precise, bias = -1) {
  var _a2, _b;
  let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop;
  let block2, { docHeight } = view.viewState;
  let { x: x2, y: y2 } = coords, yOffset = y2 - 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;
    }
  }
  y2 = docTop + yOffset;
  let lineStart = block2.from;
  if (lineStart < view.viewport.from)
    return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content2, block2, x2, y2);
  if (lineStart > view.viewport.to)
    return view.viewport.to == view.state.doc.length ? view.state.doc.length : precise ? null : posAtCoordsImprecise(view, content2, block2, x2, y2);
  let doc2 = view.dom.ownerDocument;
  let root68 = view.root.elementFromPoint ? view.root : doc2;
  let element2 = root68.elementFromPoint(x2, y2);
  if (element2 && !view.contentDOM.contains(element2))
    element2 = null;
  if (!element2) {
    x2 = Math.max(content2.left + 1, Math.min(content2.right - 1, x2));
    element2 = root68.elementFromPoint(x2, y2);
    if (element2 && !view.contentDOM.contains(element2))
      element2 = null;
  }
  let node, offset = -1;
  if (element2 && ((_a2 = view.docView.nearest(element2)) === null || _a2 === void 0 ? void 0 : _a2.isEditable) != false) {
    if (doc2.caretPositionFromPoint) {
      let pos = doc2.caretPositionFromPoint(x2, y2);
      if (pos)
        ({ offsetNode: node, offset } = pos);
    } else if (doc2.caretRangeFromPoint) {
      let range2 = doc2.caretRangeFromPoint(x2, y2);
      if (range2) {
        ({ startContainer: node, startOffset: offset } = range2);
        if (!view.contentDOM.contains(node) || browser.safari && isSuspiciousSafariCaretResult(node, offset, x2) || browser.chrome && isSuspiciousChromeCaretResult(node, offset, x2))
          node = void 0;
      }
    }
    if (node)
      offset = Math.min(maxOffset(node), offset);
  }
  if (!node || !view.docView.dom.contains(node)) {
    let line = LineView.find(view.docView, lineStart);
    if (!line)
      return yOffset > block2.top + block2.height / 2 ? block2.to : block2.from;
    ({ node, offset } = domPosAtCoords(line.dom, x2, y2));
  }
  let nearest = view.docView.nearest(node);
  if (!nearest)
    return null;
  if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.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(node, offset) + nearest.posAtStart;
  }
}
function posAtCoordsImprecise(view, contentRect, block2, x2, y2) {
  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 line = Math.floor((y2 - block2.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
    into += line * view.viewState.heightOracle.lineLength;
  }
  let content2 = view.state.sliceDoc(block2.from, block2.to);
  return block2.from + findColumn(content2, into, view.state.tabSize);
}
function isSuspiciousSafariCaretResult(node, offset, x2) {
  let len;
  if (node.nodeType != 3 || offset != (len = node.nodeValue.length))
    return false;
  for (let next2 = node.nextSibling; next2; next2 = next2.nextSibling)
    if (next2.nodeType != 1 || next2.nodeName != "BR")
      return false;
  return textRange(node, len - 1, len).getBoundingClientRect().left > x2;
}
function isSuspiciousChromeCaretResult(node, offset, x2) {
  if (offset != 0)
    return false;
  for (let cur2 = node; ; ) {
    let parent2 = cur2.parentNode;
    if (!parent2 || parent2.nodeType != 1 || parent2.firstChild != cur2)
      return false;
    if (parent2.classList.contains("cm-line"))
      break;
    cur2 = parent2;
  }
  let rect = node.nodeType == 1 ? node.getBoundingClientRect() : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect();
  return x2 - rect.left > 5;
}
function blockAt(view, pos) {
  let line = view.lineBlockAt(pos);
  if (Array.isArray(line.type))
    for (let l of line.type) {
      if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text))
        return l;
    }
  return line;
}
function moveToLineBoundary(view, start2, forward, includeWrap) {
  let line = blockAt(view, start2.head);
  let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start2.assoc < 0 && start2.head > line.from ? start2.head - 1 : start2.head);
  if (coords) {
    let editorRect = view.dom.getBoundingClientRect();
    let direction = view.textDirectionAt(line.from);
    let pos = view.posAtCoords({
      x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
      y: (coords.top + coords.bottom) / 2
    });
    if (pos != null)
      return EditorSelection.cursor(pos, forward ? -1 : 1);
  }
  return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
}
function moveByChar(view, start2, forward, by) {
  let line = view.state.doc.lineAt(start2.head), spans = view.bidiSpans(line);
  let direction = view.textDirectionAt(line.from);
  for (let cur2 = start2, check = null; ; ) {
    let next2 = moveVisually(line, spans, direction, cur2, forward), char = movedOver;
    if (!next2) {
      if (line.number == (forward ? view.state.doc.lines : 1))
        return cur2;
      char = "\n";
      line = view.state.doc.line(line.number + (forward ? 1 : -1));
      spans = view.bidiSpans(line);
      next2 = view.visualLineSide(line, !forward);
    }
    if (!check) {
      if (!by)
        return next2;
      check = by(char);
    } else if (!check(char)) {
      return cur2;
    }
    cur2 = next2;
  }
}
function byGroup(view, pos, start2) {
  let categorize = view.state.charCategorizer(pos);
  let cat = categorize(start2);
  return (next2) => {
    let nextCat = categorize(next2);
    if (cat == CharCategory.Space)
      cat = nextCat;
    return cat == nextCat;
  };
}
function moveVertically(view, start2, forward, distance) {
  let startPos = start2.head, dir = forward ? 1 : -1;
  if (startPos == (forward ? view.state.doc.length : 0))
    return EditorSelection.cursor(startPos, start2.assoc);
  let goal = start2.goalColumn, startY;
  let rect = view.contentDOM.getBoundingClientRect();
  let startCoords = view.coordsAtPos(startPos, start2.assoc || -1), docTop = view.documentTop;
  if (startCoords) {
    if (goal == null)
      goal = startCoords.left - rect.left;
    startY = dir < 0 ? startCoords.top : startCoords.bottom;
  } else {
    let line = view.viewState.lineBlockAt(startPos);
    if (goal == null)
      goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
    startY = (dir < 0 ? line.top : line.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 pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
    if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {
      let charRect = view.docView.coordsForChar(pos);
      let assoc = !charRect || curY < charRect.top ? -1 : 1;
      return EditorSelection.cursor(pos, assoc, void 0, goal);
    }
  }
}
function skipAtomicRanges(atoms, pos, bias) {
  for (; ; ) {
    let moved = 0;
    for (let set4 of atoms) {
      set4.between(pos - 1, pos + 1, (from, to, value) => {
        if (pos > from && pos < to) {
          let side = moved || bias || (pos - from < to - pos ? -1 : 1);
          pos = side < 0 ? from : to;
          moved = side;
        }
      });
    }
    if (!moved)
      return pos;
  }
}
function skipAtoms(view, oldPos, pos) {
  let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map((f) => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
  return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
}
var LineBreakPlaceholder = "\uFFFF";
var DOMReader = class {
  constructor(points, state2) {
    this.points = points;
    this.text = "";
    this.lineSeparator = state2.facet(EditorState.lineSeparator);
  }
  append(text2) {
    this.text += text2;
  }
  lineBreak() {
    this.text += LineBreakPlaceholder;
  }
  readRange(start2, end) {
    if (!start2)
      return this;
    let parent2 = start2.parentNode;
    for (let cur2 = start2; ; ) {
      this.findPointBefore(parent2, cur2);
      let oldLen = this.text.length;
      this.readNode(cur2);
      let next2 = cur2.nextSibling;
      if (next2 == end)
        break;
      let view = ContentView.get(cur2), nextView = ContentView.get(next2);
      if (view && nextView ? view.breakAfter : (view ? view.breakAfter : isBlockElement(cur2)) || isBlockElement(next2) && (cur2.nodeName != "BR" || cur2.cmIgnore) && this.text.length > oldLen)
        this.lineBreak();
      cur2 = next2;
    }
    this.findPointBefore(parent2, end);
    return this;
  }
  readTextNode(node) {
    let text2 = node.nodeValue;
    for (let point2 of this.points)
      if (point2.node == node)
        point2.pos = this.text.length + Math.min(point2.offset, text2.length);
    for (let off = 0, re2 = this.lineSeparator ? null : /\r\n?|\n/g; ; ) {
      let nextBreak = -1, breakSize = 1, m2;
      if (this.lineSeparator) {
        nextBreak = text2.indexOf(this.lineSeparator, off);
        breakSize = this.lineSeparator.length;
      } else if (m2 = re2.exec(text2)) {
        nextBreak = m2.index;
        breakSize = m2[0].length;
      }
      this.append(text2.slice(off, nextBreak < 0 ? text2.length : nextBreak));
      if (nextBreak < 0)
        break;
      this.lineBreak();
      if (breakSize > 1) {
        for (let point2 of this.points)
          if (point2.node == node && point2.pos > this.text.length)
            point2.pos -= breakSize - 1;
      }
      off = nextBreak + breakSize;
    }
  }
  readNode(node) {
    if (node.cmIgnore)
      return;
    let view = ContentView.get(node);
    let fromView = view && view.overrideDOMText;
    if (fromView != null) {
      this.findPointInside(node, fromView.length);
      for (let i2 = fromView.iter(); !i2.next().done; ) {
        if (i2.lineBreak)
          this.lineBreak();
        else
          this.append(i2.value);
      }
    } else if (node.nodeType == 3) {
      this.readTextNode(node);
    } else if (node.nodeName == "BR") {
      if (node.nextSibling)
        this.lineBreak();
    } else if (node.nodeType == 1) {
      this.readRange(node.firstChild, null);
    }
  }
  findPointBefore(node, next2) {
    for (let point2 of this.points)
      if (point2.node == node && node.childNodes[point2.offset] == next2)
        point2.pos = this.text.length;
  }
  findPointInside(node, length) {
    for (let point2 of this.points)
      if (node.nodeType == 3 ? point2.node == node : node.contains(point2.node))
        point2.pos = this.text.length + (isAtEnd(node, point2.node, point2.offset) ? length : 0);
  }
};
function isAtEnd(parent2, node, offset) {
  for (; ; ) {
    if (!node || offset < maxOffset(node))
      return false;
    if (node == parent2)
      return true;
    offset = domIndex(node) + 1;
    node = node.parentNode;
  }
}
var DOMPoint = class {
  constructor(node, offset) {
    this.node = node;
    this.offset = offset;
    this.pos = -1;
  }
};
var DOMChange = class {
  constructor(view, start2, end, typeOver) {
    this.typeOver = typeOver;
    this.bounds = null;
    this.text = "";
    this.domChanged = start2 > -1;
    let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
    if (view.state.readOnly && start2 > -1) {
      this.newSel = null;
    } else if (start2 > -1 && (this.bounds = view.docView.domBoundsAround(start2, 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 head2 = 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 && head2 != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) {
        let from = Math.min(head2, anchor), to = Math.max(head2, anchor);
        let offFrom = vp.from - from, offTo = vp.to - to;
        if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
          head2 = 0;
          anchor = view.state.doc.length;
        }
      }
      this.newSel = EditorSelection.single(anchor, head2);
    }
  }
};
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 } = domChange.bounds;
    let preferredPos = sel.from, preferredSide = null;
    if (lastKey === 8 || browser.android && domChange.text.length < to - from) {
      preferredPos = sel.to;
      preferredSide = "end";
    }
    let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
    if (diff) {
      if (browser.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
        diff.toB--;
      change = {
        from: from + diff.from,
        to: from + diff.toA,
        insert: Text2.of(domChange.text.slice(diff.from, diff.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: Text2.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: Text2.of([" "]) };
  }
  if (change) {
    return applyDOMChangeInner(view, change, newSel, lastKey);
  } else if (newSel && !newSel.main.eq(sel)) {
    let scrollIntoView3 = false, userEvent = "select";
    if (view.inputState.lastSelectionTime > Date.now() - 50) {
      if (view.inputState.lastSelectionOrigin == "select")
        scrollIntoView3 = true;
      userEvent = view.inputState.lastSelectionOrigin;
    }
    view.dispatch({ selection: newSel, scrollIntoView: scrollIntoView3, 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 tr, 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) : "";
    tr = 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;
      tr = startState.changeByRange((range2) => {
        if (range2.from == sel.from && range2.to == sel.to)
          return { changes, range: mainSel || range2.map(changes) };
        let to = range2.to - offset, from = to - replaced.length;
        if (range2.to - range2.from != size || view.state.sliceDoc(from, to) != 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.
        range2.to >= compositionRange.from && range2.from <= compositionRange.to)
          return { range: range2 };
        let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range2.to - sel.to;
        return {
          changes: rangeChanges,
          range: !mainSel ? range2.map(rangeChanges) : EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
        };
      });
    } else {
      tr = {
        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(tr, { 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 move3 = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
    from -= move3;
    toB = from + (toB - toA);
    toA = from;
  } else if (toB < from) {
    let move3 = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
    from -= move3;
    toA = from + (toA - toB);
    toB = from;
  }
  return { from, toA, toB };
}
function selectionPoints(view) {
  let result = [];
  if (view.root.activeElement != view.contentDOM)
    return result;
  let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
  if (anchorNode) {
    result.push(new DOMPoint(anchorNode, anchorOffset));
    if (focusNode != anchorNode || focusOffset != anchorOffset)
      result.push(new DOMPoint(focusNode, focusOffset));
  }
  return result;
}
function selectionFromPoints(points, base2) {
  if (points.length == 0)
    return null;
  let anchor = points[0].pos, head2 = points.length == 2 ? points[1].pos : anchor;
  return anchor > -1 && head2 > -1 ? EditorSelection.single(anchor + base2, head2 + base2) : null;
}
var InputState = class {
  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(event2) {
    if (!eventBelongsToEditor(this.view, event2) || this.ignoreDuringComposition(event2))
      return;
    if (event2.type == "keydown" && this.keydown(event2))
      return;
    if (this.view.updateState != 0)
      Promise.resolve().then(() => this.runHandlers(event2.type, event2));
    else
      this.runHandlers(event2.type, event2);
  }
  runHandlers(type, event2) {
    let handlers2 = this.handlers[type];
    if (handlers2) {
      for (let observer of handlers2.observers)
        observer(this.view, event2);
      for (let handler of handlers2.handlers) {
        if (event2.defaultPrevented)
          break;
        if (handler(this.view, event2)) {
          event2.preventDefault();
          break;
        }
      }
    }
  }
  ensureHandlers(plugins) {
    let handlers2 = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
    for (let type in handlers2)
      if (type != "scroll") {
        let passive2 = !handlers2[type].handlers.length;
        let exists = prev[type];
        if (exists && passive2 != !exists.handlers.length) {
          dom.removeEventListener(type, this.handleEvent);
          exists = null;
        }
        if (!exists)
          dom.addEventListener(type, this.handleEvent, { passive: passive2 });
      }
    for (let type in prev)
      if (type != "scroll" && !handlers2[type])
        dom.removeEventListener(type, this.handleEvent);
    this.handlers = handlers2;
  }
  keydown(event2) {
    this.lastKeyCode = event2.keyCode;
    this.lastKeyTime = Date.now();
    if (event2.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode))
      return true;
    if (this.tabFocusMode > 0 && event2.keyCode != 27 && modifierCodes.indexOf(event2.keyCode) < 0)
      this.tabFocusMode = -1;
    if (browser.android && browser.chrome && !event2.synthetic && (event2.keyCode == 13 || event2.keyCode == 8)) {
      this.view.observer.delayAndroidKey(event2.key, event2.keyCode);
      return true;
    }
    let pending2;
    if (browser.ios && !event2.synthetic && !event2.altKey && !event2.metaKey && ((pending2 = PendingKeys.find((key2) => key2.keyCode == event2.keyCode)) && !event2.ctrlKey || EmacsyPendingKeys.indexOf(event2.key) > -1 && event2.ctrlKey && !event2.shiftKey)) {
      this.pendingIOSKey = pending2 || event2;
      setTimeout(() => this.flushIOSKey(), 250);
      return true;
    }
    if (event2.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(event2) {
    if (!/^key/.test(event2.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(update3) {
    this.view.observer.update(update3);
    if (this.mouseSelection)
      this.mouseSelection.update(update3);
    if (this.draggedContent && update3.docChanged)
      this.draggedContent = this.draggedContent.map(update3.changes);
    if (update3.transactions.length)
      this.lastKeyCode = this.lastSelectionTime = 0;
  }
  destroy() {
    if (this.mouseSelection)
      this.mouseSelection.destroy();
  }
};
function bindHandler(plugin, handler) {
  return (view, event2) => {
    try {
      return handler.call(plugin, event2, view);
    } catch (e) {
      logException(view.state, e);
    }
  };
}
function computeHandlers(plugins) {
  let result = /* @__PURE__ */ Object.create(null);
  function record2(type) {
    return result[type] || (result[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)
          record2(type).handlers.push(bindHandler(plugin.value, f));
      }
    if (spec && spec.domEventObservers)
      for (let type in spec.domEventObservers) {
        let f = spec.domEventObservers[type];
        if (f)
          record2(type).observers.push(bindHandler(plugin.value, f));
      }
  }
  for (let type in handlers)
    record2(type).handlers.push(handlers[type]);
  for (let type in observers)
    record2(type).observers.push(observers[type]);
  return result;
}
var 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" }
];
var EmacsyPendingKeys = "dthko";
var modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
var 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));
}
var MouseSelection = class {
  constructor(view, startEvent, style, mustSelect) {
    this.view = view;
    this.startEvent = startEvent;
    this.style = style;
    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(event2) {
    if (this.dragging === false)
      this.select(event2);
  }
  move(event2) {
    if (event2.buttons == 0)
      return this.destroy();
    if (this.dragging || this.dragging == null && dist(this.startEvent, event2) < 10)
      return;
    this.select(this.lastEvent = event2);
    let sx = 0, sy = 0;
    let left2 = 0, top3 = 0, right2 = this.view.win.innerWidth, bottom2 = this.view.win.innerHeight;
    if (this.scrollParents.x)
      ({ left: left2, right: right2 } = this.scrollParents.x.getBoundingClientRect());
    if (this.scrollParents.y)
      ({ top: top3, bottom: bottom2 } = this.scrollParents.y.getBoundingClientRect());
    let margins = getScrollMargins(this.view);
    if (event2.clientX - margins.left <= left2 + dragScrollMargin)
      sx = -dragScrollSpeed(left2 - event2.clientX);
    else if (event2.clientX + margins.right >= right2 - dragScrollMargin)
      sx = dragScrollSpeed(event2.clientX - right2);
    if (event2.clientY - margins.top <= top3 + dragScrollMargin)
      sy = -dragScrollSpeed(top3 - event2.clientY);
    else if (event2.clientY + margins.bottom >= bottom2 - dragScrollMargin)
      sy = dragScrollSpeed(event2.clientY - bottom2);
    this.setScrollSpeed(sx, sy);
  }
  up(event2) {
    if (this.dragging == null)
      this.select(this.lastEvent);
    if (!this.dragging)
      event2.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: y2 } = this.scrollSpeed;
    if (x2 && this.scrollParents.x) {
      this.scrollParents.x.scrollLeft += x2;
      x2 = 0;
    }
    if (y2 && this.scrollParents.y) {
      this.scrollParents.y.scrollTop += y2;
      y2 = 0;
    }
    if (x2 || y2)
      this.view.win.scrollBy(x2, y2);
    if (this.dragging === false)
      this.select(this.lastEvent);
  }
  skipAtoms(sel) {
    let ranges = null;
    for (let i2 = 0; i2 < sel.ranges.length; i2++) {
      let range2 = sel.ranges[i2], updated = null;
      if (range2.empty) {
        let pos = skipAtomicRanges(this.atoms, range2.from, 0);
        if (pos != range2.from)
          updated = EditorSelection.cursor(pos, -1);
      } else {
        let from = skipAtomicRanges(this.atoms, range2.from, -1);
        let to = skipAtomicRanges(this.atoms, range2.to, 1);
        if (from != range2.from || to != range2.to)
          updated = EditorSelection.range(range2.from == range2.anchor ? from : to, range2.from == range2.head ? from : to);
      }
      if (updated) {
        if (!ranges)
          ranges = sel.ranges.slice();
        ranges[i2] = updated;
      }
    }
    return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
  }
  select(event2) {
    let { view } = this, selection2 = this.skipAtoms(this.style.get(event2, this.extend, this.multiple));
    if (this.mustSelect || !selection2.eq(view.state.selection, this.dragging === false))
      this.view.dispatch({
        selection: selection2,
        userEvent: "select.pointer"
      });
    this.mustSelect = false;
  }
  update(update3) {
    if (update3.transactions.some((tr) => tr.isUserEvent("input.type")))
      this.destroy();
    else if (this.style.update(update3))
      setTimeout(() => this.select(this.lastEvent), 20);
  }
};
function addsSelectionRange(view, event2) {
  let facet = view.state.facet(clickAddsSelectionRange);
  return facet.length ? facet[0](event2) : browser.mac ? event2.metaKey : event2.ctrlKey;
}
function dragMovesSelection(view, event2) {
  let facet = view.state.facet(dragMovesSelection$1);
  return facet.length ? facet[0](event2) : browser.mac ? !event2.altKey : !event2.ctrlKey;
}
function isInPrimarySelection(view, event2) {
  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 <= event2.clientX && rect.right >= event2.clientX && rect.top <= event2.clientY && rect.bottom >= event2.clientY)
      return true;
  }
  return false;
}
function eventBelongsToEditor(view, event2) {
  if (!event2.bubbles)
    return true;
  if (event2.defaultPrevented)
    return false;
  for (let node = event2.target, cView; node != view.contentDOM; node = node.parentNode)
    if (!node || node.nodeType == 11 || (cView = ContentView.get(node)) && cView.ignoreEvent(event2))
      return false;
  return true;
}
var handlers = /* @__PURE__ */ Object.create(null);
var observers = /* @__PURE__ */ Object.create(null);
var brokenClipboardAPI = browser.ie && browser.ie_version < 15 || browser.ios && browser.webkit_version < 604;
function capturePaste(view) {
  let parent2 = view.dom.parentNode;
  if (!parent2)
    return;
  let target = parent2.appendChild(document.createElement("textarea"));
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.focus();
  setTimeout(() => {
    view.focus();
    target.remove();
    doPaste(view, target.value);
  }, 50);
}
function textFilter(state2, facet, text2) {
  for (let filter2 of state2.facet(facet))
    text2 = filter2(text2, state2);
  return text2;
}
function doPaste(view, input) {
  input = textFilter(view.state, clipboardInputFilter, input);
  let { state: state2 } = view, changes, i2 = 1, text2 = state2.toText(input);
  let byLine = text2.lines == state2.selection.ranges.length;
  let linewise = lastLinewiseCopy != null && state2.selection.ranges.every((r2) => r2.empty) && lastLinewiseCopy == text2.toString();
  if (linewise) {
    let lastLine = -1;
    changes = state2.changeByRange((range2) => {
      let line = state2.doc.lineAt(range2.from);
      if (line.from == lastLine)
        return { range: range2 };
      lastLine = line.from;
      let insert2 = state2.toText((byLine ? text2.line(i2++).text : input) + state2.lineBreak);
      return {
        changes: { from: line.from, insert: insert2 },
        range: EditorSelection.cursor(range2.from + insert2.length)
      };
    });
  } else if (byLine) {
    changes = state2.changeByRange((range2) => {
      let line = text2.line(i2++);
      return {
        changes: { from: range2.from, to: range2.to, insert: line.text },
        range: EditorSelection.cursor(range2.from + line.length)
      };
    });
  } else {
    changes = state2.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, event2) => {
  view.inputState.setSelectionOrigin("select");
  if (event2.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, event2) => {
  view.observer.flush();
  if (view.inputState.lastTouchTime > Date.now() - 2e3)
    return false;
  let style = null;
  for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
    style = makeStyle(view, event2);
    if (style)
      break;
  }
  if (!style && event2.button == 0)
    style = basicMouseSelection(view, event2);
  if (style) {
    let mustFocus = !view.hasFocus;
    view.inputState.startMouseSelection(new MouseSelection(view, event2, style, mustFocus));
    if (mustFocus)
      view.observer.ignore(() => {
        focusPreventScroll(view.contentDOM);
        let active = view.root.activeElement;
        if (active && !active.contains(view.contentDOM))
          active.blur();
      });
    let mouseSel = view.inputState.mouseSelection;
    if (mouseSel) {
      mouseSel.start(event2);
      return mouseSel.dragging === false;
    }
  }
  return false;
};
function rangeForClick(view, pos, bias, type) {
  if (type == 1) {
    return EditorSelection.cursor(pos, bias);
  } else if (type == 2) {
    return groupAt(view.state, pos, bias);
  } else {
    let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
    let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
    if (to < view.state.doc.length && to == line.to)
      to++;
    return EditorSelection.range(from, to);
  }
}
var inside = (x2, y2, rect) => y2 >= rect.top && y2 <= rect.bottom && x2 >= rect.left && x2 <= rect.right;
function findPositionSide(view, pos, x2, y2) {
  let line = LineView.find(view.docView, pos);
  if (!line)
    return 1;
  let off = pos - line.posAtStart;
  if (off == 0)
    return 1;
  if (off == line.length)
    return -1;
  let before = line.coordsAt(off, -1);
  if (before && inside(x2, y2, before))
    return -1;
  let after = line.coordsAt(off, 1);
  if (after && inside(x2, y2, after))
    return 1;
  return before && before.bottom >= y2 ? -1 : 1;
}
function queryPos(view, event2) {
  let pos = view.posAtCoords({ x: event2.clientX, y: event2.clientY }, false);
  return { pos, bias: findPositionSide(view, pos, event2.clientX, event2.clientY) };
}
var BadMouseDetail = browser.ie && browser.ie_version <= 11;
var lastMouseDown = null;
var lastMouseDownCount = 0;
var lastMouseDownTime = 0;
function getClickType(event2) {
  if (!BadMouseDetail)
    return event2.detail;
  let last = lastMouseDown, lastTime = lastMouseDownTime;
  lastMouseDown = event2;
  lastMouseDownTime = Date.now();
  return lastMouseDownCount = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event2.clientX) < 2 && Math.abs(last.clientY - event2.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1;
}
function basicMouseSelection(view, event2) {
  let start2 = queryPos(view, event2), type = getClickType(event2);
  let startSel = view.state.selection;
  return {
    update(update3) {
      if (update3.docChanged) {
        start2.pos = update3.changes.mapPos(start2.pos);
        startSel = startSel.map(update3.changes);
      }
    },
    get(event3, extend2, multiple) {
      let cur2 = queryPos(view, event3), removed;
      let range2 = rangeForClick(view, cur2.pos, cur2.bias, type);
      if (start2.pos != cur2.pos && !extend2) {
        let startRange = rangeForClick(view, start2.pos, start2.bias, type);
        let from = Math.min(startRange.from, range2.from), to = Math.max(startRange.to, range2.to);
        range2 = from < range2.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
      }
      if (extend2)
        return startSel.replaceRange(startSel.main.extend(range2.from, range2.to));
      else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur2.pos)))
        return removed;
      else if (multiple)
        return startSel.addRange(range2);
      else
        return EditorSelection.create([range2]);
    }
  };
}
function removeRangeAround(sel, pos) {
  for (let i2 = 0; i2 < sel.ranges.length; i2++) {
    let { from, to } = sel.ranges[i2];
    if (from <= pos && to >= pos)
      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, event2) => {
  let { selection: { main: range2 } } = view.state;
  if (event2.target.draggable) {
    let cView = view.docView.nearest(event2.target);
    if (cView && cView.isWidget) {
      let from = cView.posAtStart, to = from + cView.length;
      if (from >= range2.to || to <= range2.from)
        range2 = EditorSelection.range(from, to);
    }
  }
  let { inputState } = view;
  if (inputState.mouseSelection)
    inputState.mouseSelection.dragging = true;
  inputState.draggedContent = range2;
  if (event2.dataTransfer) {
    event2.dataTransfer.setData("Text", textFilter(view.state, clipboardOutputFilter, view.state.sliceDoc(range2.from, range2.to)));
    event2.dataTransfer.effectAllowed = "copyMove";
  }
  return false;
};
handlers.dragend = (view) => {
  view.inputState.draggedContent = null;
  return false;
};
function dropText(view, event2, text2, direct) {
  text2 = textFilter(view.state, clipboardInputFilter, text2);
  if (!text2)
    return;
  let dropPos = view.posAtCoords({ x: event2.clientX, y: event2.clientY }, false);
  let { draggedContent } = view.inputState;
  let del = direct && draggedContent && dragMovesSelection(view, event2) ? { 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, event2) => {
  if (!event2.dataTransfer)
    return false;
  if (view.state.readOnly)
    return true;
  let files2 = event2.dataTransfer.files;
  if (files2 && files2.length) {
    let text2 = Array(files2.length), read = 0;
    let finishFile = () => {
      if (++read == files2.length)
        dropText(view, event2, text2.filter((s) => s != null).join(view.state.lineBreak), false);
    };
    for (let i2 = 0; i2 < files2.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(files2[i2]);
    }
    return true;
  } else {
    let text2 = event2.dataTransfer.getData("Text");
    if (text2) {
      dropText(view, event2, text2, true);
      return true;
    }
  }
  return false;
};
handlers.paste = (view, event2) => {
  if (view.state.readOnly)
    return true;
  view.observer.flush();
  let data = brokenClipboardAPI ? null : event2.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 parent2 = view.dom.parentNode;
  if (!parent2)
    return;
  let target = parent2.appendChild(document.createElement("textarea"));
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.value = text2;
  target.focus();
  target.selectionEnd = text2.length;
  target.selectionStart = 0;
  setTimeout(() => {
    target.remove();
    view.focus();
  }, 50);
}
function copiedRange(state2) {
  let content2 = [], ranges = [], linewise = false;
  for (let range2 of state2.selection.ranges)
    if (!range2.empty) {
      content2.push(state2.sliceDoc(range2.from, range2.to));
      ranges.push(range2);
    }
  if (!content2.length) {
    let upto = -1;
    for (let { from } of state2.selection.ranges) {
      let line = state2.doc.lineAt(from);
      if (line.number > upto) {
        content2.push(line.text);
        ranges.push({ from: line.from, to: Math.min(state2.doc.length, line.to + 1) });
      }
      upto = line.number;
    }
    linewise = true;
  }
  return { text: textFilter(state2, clipboardOutputFilter, content2.join(state2.lineBreak)), ranges, linewise };
}
var lastLinewiseCopy = null;
handlers.copy = handlers.cut = (view, event2) => {
  let { text: text2, ranges, linewise } = copiedRange(view.state);
  if (!text2 && !linewise)
    return false;
  lastLinewiseCopy = linewise ? text2 : null;
  if (event2.type == "cut" && !view.state.readOnly)
    view.dispatch({
      changes: ranges,
      scrollIntoView: true,
      userEvent: "delete.cut"
    });
  let data = brokenClipboardAPI ? null : event2.clipboardData;
  if (data) {
    data.clearData();
    data.setData("text/plain", text2);
    return true;
  } else {
    captureCopy(view, text2);
    return false;
  }
};
var isFocusChange = /* @__PURE__ */ Annotation.define();
function focusChangeTransaction(state2, focus) {
  let effects = [];
  for (let getEffect of state2.facet(focusChangeEffect)) {
    let effect2 = getEffect(state2, focus);
    if (effect2)
      effects.push(effect2);
  }
  return effects ? state2.update({ effects, annotations: isFocusChange.of(true) }) : null;
}
function updateForFocusChange(view) {
  setTimeout(() => {
    let focus = view.hasFocus;
    if (focus != view.inputState.notifiedFocused) {
      let tr = focusChangeTransaction(view.state, focus);
      if (tr)
        view.dispatch(tr);
      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, event2) => {
  var _a2, _b;
  if (event2.inputType == "insertReplacementText" && view.observer.editContext) {
    let text2 = (_a2 = event2.dataTransfer) === null || _a2 === void 0 ? void 0 : _a2.getData("text/plain"), ranges = event2.getTargetRanges();
    if (text2 && ranges.length) {
      let r2 = ranges[0];
      let from = view.posAtDOM(r2.startContainer, r2.startOffset), to = view.posAtDOM(r2.endContainer, r2.endOffset);
      applyDOMChangeInner(view, { from, to, insert: view.state.toText(text2) }, null);
      return true;
    }
  }
  let pending2;
  if (browser.chrome && browser.android && (pending2 = PendingKeys.find((key2) => key2.inputType == event2.inputType))) {
    view.observer.delayAndroidKey(pending2.key, pending2.keyCode);
    if (pending2.key == "Backspace" || pending2.key == "Delete") {
      let startViewHeight = ((_b = window.visualViewport) === null || _b === void 0 ? void 0 : _b.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 && event2.inputType == "deleteContentForward") {
    view.observer.flushSoon();
  }
  if (browser.safari && event2.inputType == "insertText" && view.inputState.composing >= 0) {
    setTimeout(() => observers.compositionend(view, event2), 20);
  }
  return false;
};
var appliedFirefoxHack = /* @__PURE__ */ new Set();
function firefoxCopyCutHack(doc2) {
  if (!appliedFirefoxHack.has(doc2)) {
    appliedFirefoxHack.add(doc2);
    doc2.addEventListener("copy", () => {
    });
    doc2.addEventListener("cut", () => {
    });
  }
}
var wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
var heightChangeFlag = false;
function clearHeightChangeFlag() {
  heightChangeFlag = false;
}
var HeightOracle = class {
  constructor(lineWrapping) {
    this.lineWrapping = lineWrapping;
    this.doc = Text2.empty;
    this.heightSamples = {};
    this.lineHeight = 14;
    this.charWidth = 7;
    this.textHeight = 14;
    this.lineLength = 30;
  }
  heightForGap(from, to) {
    let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
    if (this.lineWrapping)
      lines += Math.max(0, Math.ceil((to - 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;
  }
};
var MeasuredHeights = class {
  constructor(from, heights) {
    this.from = from;
    this.heights = heights;
    this.index = 0;
  }
  get more() {
    return this.index < this.heights.length;
  }
};
var BlockInfo = class _BlockInfo {
  /**
  @internal
  */
  constructor(from, length, top3, height, _content) {
    this.from = from;
    this.length = length;
    this.top = top3;
    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(QueryType3) {
  QueryType3[QueryType3["ByPos"] = 0] = "ByPos";
  QueryType3[QueryType3["ByHeight"] = 1] = "ByHeight";
  QueryType3[QueryType3["ByPosNoHeight"] = 2] = "ByPosNoHeight";
  return QueryType3;
}(QueryType || (QueryType = {}));
var Epsilon = 1e-3;
var HeightMap = class _HeightMap {
  constructor(length, height, flags2 = 2) {
    this.length = length;
    this.height = height;
    this.flags = flags2;
  }
  get outdated() {
    return (this.flags & 2) > 0;
  }
  set outdated(value) {
    this.flags = (value ? 2 : 0) | this.flags & ~2;
  }
  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, result) {
    result.push(this);
  }
  decomposeRight(_from, result) {
    result.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 start2 = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
      let end = start2.to >= toA ? start2 : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);
      toB += end.to - toA;
      toA = end.to;
      while (i2 > 0 && start2.from <= changes[i2 - 1].toA) {
        fromA = changes[i2 - 1].fromA;
        fromB = changes[i2 - 1].fromB;
        i2--;
        if (fromA < start2.from)
          start2 = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);
      }
      fromB += start2.from - fromA;
      fromA = start2.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, j = nodes.length, before = 0, after = 0;
    for (; ; ) {
      if (i2 == j) {
        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);
          j += 1 + split.break;
          before -= split.size;
        } else if (after > before * 2) {
          let split = nodes[j];
          if (split.break)
            nodes.splice(j, 1, split.left, null, split.right);
          else
            nodes.splice(j, 1, split.left, split.right);
          j += 2 + split.break;
          after -= split.size;
        } else {
          break;
        }
      } else if (before < after) {
        let next2 = nodes[i2++];
        if (next2)
          before += next2.size;
      } else {
        let next2 = nodes[--j];
        if (next2)
          after += next2.size;
      }
    }
    let brk = 0;
    if (nodes[i2 - 1] == null) {
      brk = 1;
      i2--;
    } else if (nodes[i2] == null) {
      brk = 1;
      j++;
    }
    return new HeightMapBranch(_HeightMap.of(nodes.slice(0, i2)), brk, _HeightMap.of(nodes.slice(j)));
  }
};
function replace(old, val) {
  if (old == val)
    return old;
  if (old.constructor != val.constructor)
    heightChangeFlag = true;
  return val;
}
HeightMap.prototype.size = 1;
var HeightMapBlock = class extends HeightMap {
  constructor(length, height, deco) {
    super(length, height);
    this.deco = deco;
  }
  blockAt(_height, _oracle, top3, offset) {
    return new BlockInfo(offset, this.length, top3, this.height, this.deco || 0);
  }
  lineAt(_value, _type, oracle, top3, offset) {
    return this.blockAt(0, oracle, top3, offset);
  }
  forEachLine(from, to, oracle, top3, offset, f) {
    if (from <= offset + this.length && to >= offset)
      f(this.blockAt(0, oracle, top3, 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})`;
  }
};
var HeightMapText = class _HeightMapText extends HeightMapBlock {
  constructor(length, height) {
    super(length, height, null);
    this.collapsed = 0;
    this.widgetHeight = 0;
    this.breaks = 0;
  }
  blockAt(_height, _oracle, top3, offset) {
    return new BlockInfo(offset, this.length, top3, this.height, this.breaks);
  }
  replace(_from, _to, nodes) {
    let node = nodes[0];
    if (nodes.length == 1 && (node instanceof _HeightMapText || node instanceof HeightMapGap && node.flags & 4) && Math.abs(this.length - node.length) < 10) {
      if (node instanceof HeightMapGap)
        node = new _HeightMapText(node.length, this.height);
      else
        node.height = this.height;
      if (!this.outdated)
        node.outdated = false;
      return node;
    } 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 : ""})`;
  }
};
var HeightMapGap = 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, top3, 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 - top3) / this.height)) * this.length));
      let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
      let lineTop = Math.max(top3, height - lineHeight / 2);
      return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
    } else {
      let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top3) / perLine)));
      let { from, length } = oracle.doc.line(firstLine + line);
      return new BlockInfo(from, length, top3 + perLine * line, perLine, 0);
    }
  }
  lineAt(value, type, oracle, top3, offset) {
    if (type == QueryType.ByHeight)
      return this.blockAt(value, oracle, top3, offset);
    if (type == QueryType.ByPosNoHeight) {
      let { from, to } = oracle.doc.lineAt(value);
      return new BlockInfo(from, to - from, 0, 0, 0);
    }
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;
    let linesAbove = line.number - firstLine;
    let lineTop = top3 + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
    return new BlockInfo(line.from, line.length, Math.max(top3, Math.min(lineTop, top3 + this.height - lineHeight)), lineHeight, 0);
  }
  forEachLine(from, to, oracle, top3, offset, f) {
    from = Math.max(from, offset);
    to = Math.min(to, offset + this.length);
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    for (let pos = from, lineTop = top3; pos <= to; ) {
      let line = oracle.doc.lineAt(pos);
      if (pos == from) {
        let linesAbove = line.number - firstLine;
        lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
      }
      let lineHeight = perLine + perChar * line.length;
      f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
      lineTop += lineHeight;
      pos = line.to + 1;
    }
  }
  replace(from, to, nodes) {
    let after = this.length - to;
    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 first = nodes[0];
      if (first instanceof _HeightMapGap)
        nodes[0] = new _HeightMapGap(from + first.length);
      else
        nodes.unshift(new _HeightMapGap(from - 1), null);
    }
    return HeightMap.of(nodes);
  }
  decomposeLeft(to, result) {
    result.push(new _HeightMapGap(to - 1), null);
  }
  decomposeRight(from, result) {
    result.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 = [], pos = Math.max(offset, measured.from), singleHeight = -1;
      if (measured.from > offset)
        nodes.push(new _HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
      while (pos <= end && measured.more) {
        let len = oracle.doc.lineAt(pos).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 line = new HeightMapText(len, height);
        line.outdated = false;
        nodes.push(line);
        pos += len + 1;
      }
      if (pos <= end)
        nodes.push(null, new _HeightMapGap(end - pos).updateHeight(oracle, pos));
      let result = HeightMap.of(nodes);
      if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
        heightChangeFlag = true;
      return replace(this, result);
    } else if (force || this.outdated) {
      this.setHeight(oracle.heightForGap(offset, offset + this.length));
      this.outdated = false;
    }
    return this;
  }
  toString() {
    return `gap(${this.length})`;
  }
};
var HeightMapBranch = class extends HeightMap {
  constructor(left2, brk, right2) {
    super(left2.length + brk + right2.length, left2.height + right2.height, brk | (left2.outdated || right2.outdated ? 2 : 0));
    this.left = left2;
    this.right = right2;
    this.size = left2.size + right2.size;
  }
  get break() {
    return this.flags & 1;
  }
  blockAt(height, oracle, top3, offset) {
    let mid = top3 + this.left.height;
    return height < mid ? this.left.blockAt(height, oracle, top3, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
  }
  lineAt(value, type, oracle, top3, offset) {
    let rightTop = top3 + this.left.height, rightOffset = offset + this.left.length + this.break;
    let left2 = type == QueryType.ByHeight ? value < rightTop : value < rightOffset;
    let base2 = left2 ? this.left.lineAt(value, type, oracle, top3, offset) : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
    if (this.break || (left2 ? base2.to < rightOffset : base2.from > rightOffset))
      return base2;
    let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;
    if (left2)
      return base2.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
    else
      return this.left.lineAt(rightOffset, subQuery, oracle, top3, offset).join(base2);
  }
  forEachLine(from, to, oracle, top3, offset, f) {
    let rightTop = top3 + this.left.height, rightOffset = offset + this.left.length + this.break;
    if (this.break) {
      if (from < rightOffset)
        this.left.forEachLine(from, to, oracle, top3, offset, f);
      if (to >= rightOffset)
        this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
    } else {
      let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top3, offset);
      if (from < mid.from)
        this.left.forEachLine(from, mid.from - 1, oracle, top3, offset, f);
      if (mid.to >= from && mid.from <= to)
        f(mid);
      if (to > mid.to)
        this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
    }
  }
  replace(from, to, nodes) {
    let rightStart = this.left.length + this.break;
    if (to < rightStart)
      return this.balanced(this.left.replace(from, to, nodes), this.right);
    if (from > this.left.length)
      return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
    let result = [];
    if (from > 0)
      this.decomposeLeft(from, result);
    let left2 = result.length;
    for (let node of nodes)
      result.push(node);
    if (from > 0)
      mergeGaps(result, left2 - 1);
    if (to < this.length) {
      let right2 = result.length;
      this.decomposeRight(to, result);
      mergeGaps(result, right2);
    }
    return HeightMap.of(result);
  }
  decomposeLeft(to, result) {
    let left2 = this.left.length;
    if (to <= left2)
      return this.left.decomposeLeft(to, result);
    result.push(this.left);
    if (this.break) {
      left2++;
      if (to >= left2)
        result.push(null);
    }
    if (to > left2)
      this.right.decomposeLeft(to - left2, result);
  }
  decomposeRight(from, result) {
    let left2 = this.left.length, right2 = left2 + this.break;
    if (from >= right2)
      return this.right.decomposeRight(from - right2, result);
    if (from < left2)
      this.left.decomposeRight(from, result);
    if (this.break && from < right2)
      result.push(null);
    result.push(this.right);
  }
  balanced(left2, right2) {
    if (left2.size > 2 * right2.size || right2.size > 2 * left2.size)
      return HeightMap.of(this.break ? [left2, null, right2] : [left2, right2]);
    this.left = replace(this.left, left2);
    this.right = replace(this.right, right2);
    this.setHeight(left2.height + right2.height);
    this.outdated = left2.outdated || right2.outdated;
    this.size = left2.size + right2.size;
    this.length = left2.length + this.break + right2.length;
    return this;
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    let { left: left2, right: right2 } = this, rightStart = offset + left2.length + this.break, rebalance = null;
    if (measured && measured.from <= offset + left2.length && measured.more)
      rebalance = left2 = left2.updateHeight(oracle, offset, force, measured);
    else
      left2.updateHeight(oracle, offset, force);
    if (measured && measured.from <= rightStart + right2.length && measured.more)
      rebalance = right2 = right2.updateHeight(oracle, rightStart, force, measured);
    else
      right2.updateHeight(oracle, rightStart, force);
    if (rebalance)
      return this.balanced(left2, right2);
    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));
}
var relevantWidgetHeight = 5;
var NodeBuilder = class _NodeBuilder {
  constructor(pos, oracle) {
    this.pos = pos;
    this.oracle = oracle;
    this.nodes = [];
    this.lineStart = -1;
    this.lineEnd = -1;
    this.covering = null;
    this.writtenTo = pos;
  }
  get isCovered() {
    return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
  }
  span(_from, to) {
    if (this.lineStart > -1) {
      let end = Math.min(to, 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 (to > end) {
        this.nodes.push(null);
        this.writtenTo++;
        this.lineStart = -1;
      }
    }
    this.pos = to;
  }
  point(from, to, deco) {
    if (from < to || 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 = to - from;
      if (deco.block) {
        this.addBlock(new HeightMapBlock(len, height, deco));
      } else if (len || breaks || height >= relevantWidgetHeight) {
        this.addLineDeco(height, breaks, len);
      }
    } else if (to > from) {
      this.span(from, to);
    }
    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 } = this.oracle.doc.lineAt(this.pos);
    this.lineStart = from;
    this.lineEnd = to;
    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, to) {
    let gap = new HeightMapGap(to - from);
    if (this.oracle.doc.lineAt(from).to == to)
      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 line = new HeightMapText(0, -1);
    this.nodes.push(line);
    return line;
  }
  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 line = this.ensureLine();
    line.length += length;
    line.collapsed += length;
    line.widgetHeight = Math.max(line.widgetHeight, height);
    line.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 pos = from;
    for (let node of this.nodes) {
      if (node instanceof HeightMapText)
        node.updateHeight(this.oracle, pos);
      pos += node ? node.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, to) {
    let builder = new _NodeBuilder(from, oracle);
    RangeSet.spans(decorations2, from, to, builder, 0);
    return builder.finish(from);
  }
};
function heightRelevantDecoChanges(a, b, diff) {
  let comp = new DecorationComparator2();
  RangeSet.compare(a, b, diff, comp, 0);
  return comp.changes;
}
var DecorationComparator2 = class {
  constructor() {
    this.changes = [];
  }
  compareRange() {
  }
  comparePoint(from, to, a, b) {
    if (from < to || a && a.heightRelevant || b && b.heightRelevant)
      addRange(from, to, this.changes, 5);
  }
};
function visiblePixelRange(dom, paddingTop) {
  let rect = dom.getBoundingClientRect();
  let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
  let left2 = Math.max(0, rect.left), right2 = Math.min(win.innerWidth, rect.right);
  let top3 = Math.max(0, rect.top), bottom2 = Math.min(win.innerHeight, rect.bottom);
  for (let parent2 = dom.parentNode; parent2 && parent2 != doc2.body; ) {
    if (parent2.nodeType == 1) {
      let elt = parent2;
      let style = window.getComputedStyle(elt);
      if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style.overflow != "visible") {
        let parentRect = elt.getBoundingClientRect();
        left2 = Math.max(left2, parentRect.left);
        right2 = Math.min(right2, parentRect.right);
        top3 = Math.max(top3, parentRect.top);
        bottom2 = Math.min(parent2 == dom.parentNode ? win.innerHeight : bottom2, parentRect.bottom);
      }
      parent2 = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
    } else if (parent2.nodeType == 11) {
      parent2 = parent2.host;
    } else {
      break;
    }
  }
  return {
    left: left2 - rect.left,
    right: Math.max(left2, right2) - rect.left,
    top: top3 - (rect.top + paddingTop),
    bottom: Math.max(top3, bottom2) - (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)
  };
}
var LineGap = class {
  constructor(from, to, size, displaySize) {
    this.from = from;
    this.to = to;
    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);
  }
};
var LineGapWidget = class 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;
  }
};
var ViewState = class {
  constructor(state2) {
    this.state = state2;
    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 = state2.facet(contentAttributes).some((v) => typeof v != "function" && v.class == "cm-lineWrapping");
    this.heightOracle = new HeightOracle(guessWrapping);
    this.stateDeco = state2.facet(decorations).filter((d) => typeof d != "function");
    this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text2.empty, this.heightOracle.setDoc(state2.doc), [new ChangedRange(0, 0, 0, state2.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 pos = i2 ? main.head : main.anchor;
      if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {
        let { from, to } = this.lineBlockAt(pos);
        viewports.push(new Viewport(from, to));
      }
    }
    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(update3, scrollTarget = null) {
    this.state = update3.state;
    let prevDeco = this.stateDeco;
    this.stateDeco = this.state.facet(decorations).filter((d) => typeof d != "function");
    let contentChanges = update3.changedRanges;
    let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update3 ? update3.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, update3.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
    if (this.heightMap.height != prevHeight || heightChangeFlag)
      update3.flags |= 2;
    if (scrollAnchor) {
      this.scrollAnchorPos = update3.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, update3.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;
    update3.flags |= this.updateForViewport();
    if (viewportChange || !update3.changes.empty || update3.flags & 2)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update3.changes)));
    update3.flags |= this.computeVisibleRanges(update3.changes);
    if (scrollTarget)
      this.scrollTarget = scrollTarget;
    if (!this.mustEnforceCursorAssoc && update3.selectionSet && update3.view.lineWrapping && update3.state.selection.main.empty && update3.state.selection.main.assoc && !update3.state.facet(nativeSelectionHidden))
      this.mustEnforceCursorAssoc = true;
  }
  measure(view) {
    let dom = view.contentDOM, style = window.getComputedStyle(dom);
    let oracle = this.heightOracle;
    let whiteSpace = style.whiteSpace;
    this.defaultTextDirection = style.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 result = 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;
        result |= 16;
        refresh = measureContent = true;
      }
    }
    let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
    let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
    if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
      this.paddingTop = paddingTop;
      this.paddingBottom = paddingBottom;
      result |= 16 | 2;
    }
    if (this.editorWidth != view.scrollDOM.clientWidth) {
      if (oracle.lineWrapping)
        measureContent = true;
      this.editorWidth = view.scrollDOM.clientWidth;
      result |= 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;
      result |= 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;
          result |= 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, Text2.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)
        result |= 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 (result & 2)
        result |= this.updateScaler();
      this.viewport = this.getViewport(bias, this.scrollTarget);
      result |= this.updateForViewport();
    }
    if (result & 2 || viewportChange)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
    result |= this.computeVisibleRanges();
    if (this.mustEnforceCursorAssoc) {
      this.mustEnforceCursorAssoc = false;
      view.docView.enforceCursorAssoc();
    }
    return result;
  }
  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: head2 } = scrollTarget.range;
      if (head2 < viewport.from || head2 > viewport.to) {
        let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
        let block2 = map2.lineAt(head2, 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" && head2 < 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), to = changes.mapPos(viewport.to, 1);
    return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, 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 }, bias = 0) {
    if (!this.inView)
      return true;
    let { top: top3 } = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);
    let { bottom: bottom2 } = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);
    let { visibleTop, visibleBottom } = this;
    return (from == 0 || top3 <= visibleTop - Math.max(10, Math.min(
      -bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (to == this.state.doc.length || bottom2 >= visibleBottom + Math.max(10, Math.min(
      bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (top3 > visibleTop - 2 * 1e3 && bottom2 < 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, to, line, structure) => {
      if (to - from < halfMargin)
        return;
      let sel = this.state.selection.main, avoid = [sel.from];
      if (!sel.empty)
        avoid.push(sel.to);
      for (let pos of avoid) {
        if (pos > from && pos < to) {
          addGap(from, pos - 10, line, structure);
          addGap(pos + 10, to, line, structure);
          return;
        }
      }
      let gap = find(current, (gap2) => gap2.from >= line.from && gap2.to <= line.to && Math.abs(gap2.from - from) < halfMargin && Math.abs(gap2.to - to) < halfMargin && !avoid.some((pos) => gap2.from < pos && gap2.to > pos));
      if (!gap) {
        if (to < line.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some((r2) => r2.from <= to && r2.to >= to)) {
          let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
          if (lineStart > from)
            to = lineStart;
        }
        let size = this.gapSize(line, from, to, structure);
        let displaySize = wrapping || size < 2e6 ? size : 2e6;
        gap = new LineGap(from, to, size, displaySize);
      }
      gaps.push(gap);
    };
    let checkLine = (line) => {
      if (line.length < doubleMargin || line.type != BlockType.Text)
        return;
      let structure = lineStructure(line.from, line.to, this.stateDeco);
      if (structure.total < doubleMargin)
        return;
      let target = this.scrollTarget ? this.scrollTarget.range.head : null;
      let viewFrom, viewTo;
      if (wrapping) {
        let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight;
        let top3, bot;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
          top3 = targetFrac - spaceFrac;
          bot = targetFrac + spaceFrac;
        } else {
          top3 = (this.visibleTop - line.top - marginHeight) / line.height;
          bot = (this.visibleBottom - line.top + marginHeight) / line.height;
        }
        viewFrom = findPosition(structure, top3);
        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 >= line.from && old.from < line.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 left2, right2;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth;
          left2 = targetFrac - spaceFrac;
          right2 = targetFrac + spaceFrac;
        } else {
          left2 = (pxLeft - marginWidth) / totalWidth;
          right2 = (pxRight + marginWidth) / totalWidth;
        }
        viewFrom = findPosition(structure, left2);
        viewTo = findPosition(structure, right2);
      }
      if (viewFrom > line.from)
        addGap(line.from, viewFrom, line, structure);
      if (viewTo < line.to)
        addGap(viewTo, line.to, line, structure);
    };
    for (let line of this.viewportLines) {
      if (Array.isArray(line.type))
        line.type.forEach(checkLine);
      else
        checkLine(line);
    }
    return gaps;
  }
  gapSize(line, from, to, structure) {
    let fraction = findFraction(structure, to) - findFraction(structure, from);
    if (this.heightOracle.lineWrapping) {
      return line.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, to) {
        ranges.push({ from, to });
      },
      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(pos) {
    return pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find((b) => b.from <= pos && b.to >= pos) || scaleBlock(this.heightMap.lineAt(pos, 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;
  }
};
var Viewport = class {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
};
function lineStructure(from, to, stateDeco) {
  let ranges = [], pos = from, total = 0;
  RangeSet.spans(stateDeco, from, to, {
    span() {
    },
    point(from2, to2) {
      if (from2 > pos) {
        ranges.push({ from: pos, to: from2 });
        total += from2 - pos;
      }
      pos = to2;
    }
  }, 20);
  if (pos < to) {
    ranges.push({ from: pos, to });
    total += to - pos;
  }
  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 } = ranges[i2], size = to - from;
    if (dist2 <= size)
      return from + dist2;
    dist2 -= size;
  }
}
function findFraction(structure, pos) {
  let counted = 0;
  for (let { from, to } of structure.ranges) {
    if (pos <= to) {
      counted += pos - from;
      break;
    }
    counted += to - from;
  }
  return counted / structure.total;
}
function find(array3, f) {
  for (let val of array3)
    if (f(val))
      return val;
  return void 0;
}
var IdScaler = {
  toDOM(n) {
    return n;
  },
  fromDOM(n) {
    return n;
  },
  scale: 1,
  eq(other) {
    return other == this;
  }
};
var BigScaler = class _BigScaler {
  constructor(oracle, heightMap, viewports) {
    let vpHeight = 0, base2 = 0, domBase = 0;
    this.viewports = viewports.map(({ from, to }) => {
      let top3 = heightMap.lineAt(from, QueryType.ByPos, oracle, 0, 0).top;
      let bottom2 = heightMap.lineAt(to, QueryType.ByPos, oracle, 0, 0).bottom;
      vpHeight += bottom2 - top3;
      return { from, to, top: top3, bottom: bottom2, 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);
}
var theme = /* @__PURE__ */ Facet.define({ combine: (strs) => strs.join(" ") });
var darkTheme = /* @__PURE__ */ Facet.define({ combine: (values) => values.indexOf(true) > -1 });
var baseThemeID = /* @__PURE__ */ StyleModule.newName();
var baseLightID = /* @__PURE__ */ StyleModule.newName();
var baseDarkID = /* @__PURE__ */ StyleModule.newName();
var lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
function buildTheme(main, spec, scopes) {
  return new StyleModule(spec, {
    finish(sel) {
      return /&/.test(sel) ? sel.replace(/&\w*/, (m2) => {
        if (m2 == "&")
          return main;
        if (!scopes || !scopes[m2])
          throw new RangeError(`Unsupported selector: ${m2}`);
        return scopes[m2];
      }) : main + " " + sel;
    }
  });
}
var baseTheme$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);
var observeOptions = {
  childList: true,
  characterData: true,
  subtree: true,
  attributes: true,
  characterDataOldValue: true
};
var useCharData = browser.ie && browser.ie_version <= 11;
var DOMObserver = class {
  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((m2) => m2.type == "childList" && m2.removedNodes.length || m2.type == "characterData" && m2.oldValue.length > m2.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 = (event2) => {
        this.queue.push({
          target: event2.target,
          type: "characterData",
          oldValue: event2.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(event2) {
    if ((event2.type == "change" || !event2.type) && !event2.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(event2) {
    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 context2 = sel.anchorNode && view.docView.nearest(sel.anchorNode);
    if (context2 && context2.ignoreEvent(event2)) {
      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 selection2 = getSelection(view.root);
    if (!selection2)
      return false;
    let range2 = browser.safari && view.root.nodeType == 11 && view.root.activeElement == this.dom && safariSelectionRangeHack(this.view, selection2) || selection2;
    if (!range2 || this.selectionRange.eq(range2))
      return false;
    let local = hasSelection(this.dom, range2);
    if (local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart(this.dom, range2)) {
      this.view.inputState.lastFocusTime = 0;
      view.docView.updateSelection();
      return false;
    }
    this.selectionRange.setRange(range2);
    if (local)
      this.selectionChanged = true;
    return true;
  }
  setSelectionRange(anchor, head2) {
    this.selectionRange.set(anchor.node, anchor.offset, head2.node, head2.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, to = -1, typeOver = false;
    for (let record2 of records) {
      let range2 = this.readMutation(record2);
      if (!range2)
        continue;
      if (range2.typeOver)
        typeOver = true;
      if (from == -1) {
        ({ from, to } = range2);
      } else {
        from = Math.min(range2.from, from);
        to = Math.max(range2.to, to);
      }
    }
    return { from, to, typeOver };
  }
  readChange() {
    let { from, to, 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, to, 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(update3) {
    if (this.editContext) {
      this.editContext.update(update3);
      if (update3.startState.facet(editable) != update3.state.facet(editable))
        update3.view.contentDOM.editContext = update3.state.facet(editable) ? this.editContext.editContext : null;
    }
  }
  destroy() {
    var _a2, _b, _c;
    this.stop();
    (_a2 = this.intersection) === null || _a2 === void 0 ? void 0 : _a2.disconnect();
    (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.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 parent2 = dom.parentNode;
    dom = parent2 != cView.dom ? parent2 : dir > 0 ? dom.nextSibling : dom.previousSibling;
  }
  return null;
}
function buildSelectionRangeFromRange(view, range2) {
  let anchorNode = range2.startContainer, anchorOffset = range2.startOffset;
  let focusNode = range2.endContainer, focusOffset = range2.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, selection2) {
  if (selection2.getComposedRanges) {
    let range2 = selection2.getComposedRanges(view.root)[0];
    if (range2)
      return buildSelectionRangeFromRange(view, range2);
  }
  let found = null;
  function read(event2) {
    event2.preventDefault();
    event2.stopImmediatePropagation();
    found = event2.getTargetRanges()[0];
  }
  view.contentDOM.addEventListener("beforeinput", read, true);
  view.dom.ownerDocument.execCommand("indent");
  view.contentDOM.removeEventListener("beforeinput", read, true);
  return found ? buildSelectionRangeFromRange(view, found) : null;
}
var EditContextManager = class {
  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 context2 = 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: head2 } = main;
      let from = this.toEditorPos(e.updateRangeStart), to = this.toEditorPos(e.updateRangeEnd);
      if (view.inputState.composing >= 0 && !this.composing)
        this.composing = { contextBase: e.updateRangeStart, editorBase: from, drifted: false };
      let change = { from, to, insert: Text2.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 == head2 - 1 && /^\. ?$/.test(e.text) && view.contentDOM.getAttribute("autocorrect") == "off")
        change = { from, to, insert: Text2.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);
      }
      context2.updateCharacterBounds(e.rangeStart, rects);
    };
    this.handlers.textformatupdate = (e) => {
      let deco = [];
      for (let format3 of e.getTextFormats()) {
        let lineStyle = format3.underlineStyle, thickness = format3.underlineThickness;
        if (lineStyle != "None" && thickness != "None") {
          let from = this.toEditorPos(format3.rangeStart), to = this.toEditorPos(format3.rangeEnd);
          if (from < to) {
            let style = `text-decoration: underline ${lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${thickness == "Thin" ? 1 : 2}px`;
            deco.push(Decoration.mark({ attributes: { style } }).range(from, to));
          }
        }
      }
      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 event2 in this.handlers)
      context2.addEventListener(event2, this.handlers[event2]);
    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(update3) {
    let off = 0, abort2 = false, pending2 = this.pendingContextChange;
    update3.changes.iterChanges((fromA, toA, _fromB, _toB, insert2) => {
      if (abort2)
        return;
      let dLen = insert2.length - (toA - fromA);
      if (pending2 && toA >= pending2.to) {
        if (pending2.from == fromA && pending2.to == toA && pending2.insert.eq(insert2)) {
          pending2 = this.pendingContextChange = null;
          off += dLen;
          this.to += dLen;
          return;
        } else {
          pending2 = null;
          this.revertPending(update3.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) {
          abort2 = true;
          return;
        }
        this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert2.toString());
        this.to += dLen;
      }
      off += dLen;
    });
    if (pending2 && !abort2)
      this.revertPending(update3.state);
    return !abort2;
  }
  update(update3) {
    let reverted = this.pendingContextChange, startSel = update3.startState.selection.main;
    if (this.composing && (this.composing.drifted || !update3.changes.touchesRange(startSel.from, startSel.to) && update3.transactions.some((tr) => !tr.isUserEvent("input.type") && tr.changes.touchesRange(this.from, this.to)))) {
      this.composing.drifted = true;
      this.composing.editorBase = update3.changes.mapPos(this.composing.editorBase);
    } else if (!this.applyEdits(update3) || !this.rangeIsValid(update3.state)) {
      this.pendingContextChange = null;
      this.reset(update3.state);
    } else if (update3.docChanged || update3.selectionSet || reverted) {
      this.setSelection(update3.state);
    }
    if (update3.geometryChanged || update3.docChanged || update3.selectionSet)
      update3.view.requestMeasure(this.measureReq);
  }
  resetRange(state2) {
    let { head: head2 } = state2.selection.main;
    this.from = Math.max(
      0,
      head2 - 1e4
      /* CxVp.Margin */
    );
    this.to = Math.min(
      state2.doc.length,
      head2 + 1e4
      /* CxVp.Margin */
    );
  }
  reset(state2) {
    this.resetRange(state2);
    this.editContext.updateText(0, this.editContext.text.length, state2.doc.sliceString(this.from, this.to));
    this.setSelection(state2);
  }
  revertPending(state2) {
    let pending2 = this.pendingContextChange;
    this.pendingContextChange = null;
    this.editContext.updateText(this.toContextPos(pending2.from), this.toContextPos(pending2.from + pending2.insert.length), state2.doc.sliceString(pending2.from, pending2.to));
  }
  setSelection(state2) {
    let { main } = state2.selection;
    let start2 = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor)));
    let end = this.toContextPos(main.head);
    if (this.editContext.selectionStart != start2 || this.editContext.selectionEnd != end)
      this.editContext.updateSelection(start2, end);
  }
  rangeIsValid(state2) {
    let { head: head2 } = state2.selection.main;
    return !(this.from > 0 && head2 - this.from < 500 || this.to < state2.doc.length && this.to - head2 < 500 || this.to - this.from > 1e4 * 3);
  }
  toEditorPos(contextPos, clipLen = this.to - this.from) {
    contextPos = Math.min(contextPos, clipLen);
    let c = this.composing;
    return c && c.drifted ? c.editorBase + (contextPos - c.contextBase) : contextPos + this.from;
  }
  toContextPos(editorPos) {
    let c = this.composing;
    return c && c.drifted ? c.contextBase + (editorPos - c.editorBase) : editorPos - this.from;
  }
  destroy() {
    for (let event2 in this.handlers)
      this.editContext.removeEventListener(event2, this.handlers[event2]);
  }
};
var EditorView = 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((tr) => dispatch(tr, 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))
      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(...input) {
    let trs = input.length == 1 && input[0] instanceof Transaction2 ? input : input.length == 1 && Array.isArray(input[0]) ? input[0] : [this.state.update(...input)];
    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, update3;
    let state2 = this.state;
    for (let tr of transactions) {
      if (tr.startState != state2)
        throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
      state2 = tr.state;
    }
    if (this.destroyed) {
      this.viewState.state = state2;
      return;
    }
    let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
    if (transactions.some((tr) => tr.annotation(isFocusChange))) {
      this.inputState.notifiedFocused = focus;
      focusFlag = 1;
    } else if (focus != this.inputState.notifiedFocused) {
      this.inputState.notifiedFocused = focus;
      dispatchFocus = focusChangeTransaction(state2, 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(state2.doc) || !this.state.selection.eq(state2.selection))
        domChange = null;
    } else {
      this.observer.clear();
    }
    if (state2.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))
      return this.setState(state2);
    update3 = ViewUpdate.create(this, state2, transactions);
    update3.flags |= focusFlag;
    let scrollTarget = this.viewState.scrollTarget;
    try {
      this.updateState = 2;
      for (let tr of transactions) {
        if (scrollTarget)
          scrollTarget = scrollTarget.map(tr.changes);
        if (tr.scrollIntoView) {
          let { main } = tr.state.selection;
          scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
        }
        for (let e of tr.effects)
          if (e.is(scrollIntoView))
            scrollTarget = e.value.clip(this.state);
      }
      this.viewState.update(update3, scrollTarget);
      this.bidiCache = CachedOrder.update(this.bidiCache, update3.changes);
      if (!update3.empty) {
        this.updatePlugins(update3);
        this.inputState.update(update3);
      }
      redrawn = this.docView.update(update3);
      if (this.state.facet(styleModule) != this.styleModules)
        this.mountStyles();
      attrsChanged = this.updateAttrs();
      this.showAnnouncements(transactions);
      this.docView.updateSelection(redrawn, transactions.some((tr) => tr.isUserEvent("select.pointer")));
    } finally {
      this.updateState = 0;
    }
    if (update3.startState.facet(theme) != update3.state.facet(theme))
      this.viewState.mustMeasureContent = true;
    if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
      this.requestMeasure();
    if (redrawn)
      this.docViewUpdate();
    if (!update3.empty)
      for (let listener of this.state.facet(updateListener)) {
        try {
          listener(update3);
        } 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(update3) {
    let prevSpecs = update3.startState.facet(viewPlugin), specs = update3.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 = update3;
          newPlugins.push(plugin);
        }
      }
      for (let plugin of this.plugins)
        if (plugin.mustUpdate != update3)
          plugin.destroy(this);
      this.plugins = newPlugins;
      this.pluginMap.clear();
    } else {
      for (let p of this.plugins)
        p.mustUpdate = update3;
    }
    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((m2) => {
          try {
            return m2.read(this);
          } catch (e) {
            logException(this.state, e);
            return BadMeasure;
          }
        });
        let update3 = ViewUpdate.create(this, this.state, []), redrawn = false;
        update3.flags |= changed;
        if (!updated)
          updated = update3;
        else
          updated.flags |= changed;
        this.updateState = 2;
        if (!update3.empty) {
          this.updatePlugins(update3);
          this.inputState.update(update3);
          this.updateAttrs();
          redrawn = this.docView.update(update3);
          if (redrawn)
            this.docViewUpdate();
        }
        for (let i3 = 0; i3 < measuring.length; i3++)
          if (measured[i3] != BadMeasure) {
            try {
              let m2 = measuring[i3];
              if (m2.write)
                m2.write(measured[i3], this);
            } catch (e) {
              logException(this.state, e);
            }
          }
        if (redrawn)
          this.docView.updateSelection(true);
        if (!update3.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 diff = newAnchorHeight - scrollAnchorHeight;
              if (diff > 1 || diff < -1) {
                scrollTop = scrollTop + diff;
                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 first = true;
    for (let tr of trs)
      for (let effect2 of tr.effects)
        if (effect2.is(_EditorView.announce)) {
          if (first)
            this.announceDOM.textContent = "";
          first = false;
          let div = this.announceDOM.appendChild(document.createElement("div"));
          div.textContent = effect2.value;
        }
  }
  mountStyles() {
    this.styleModules = this.state.facet(styleModule);
    let nonce = this.state.facet(_EditorView.cspNonce);
    StyleModule.mount(this.root, this.styleModules.concat(baseTheme$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(pos) {
    return this.viewState.lineBlockAt(pos);
  }
  /**
  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(start2, forward, by) {
    return skipAtoms(this, start2, moveByChar(this, start2, 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(start2, forward) {
    return skipAtoms(this, start2, moveByChar(this, start2, forward, (initial) => byGroup(this, start2.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(line, end) {
    let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from);
    let span = order[end ? order.length - 1 : 0];
    return EditorSelection.cursor(span.side(end, dir) + line.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(start2, forward, includeWrap = true) {
    return moveToLineBoundary(this, start2, 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(start2, forward, distance) {
    return skipAtoms(this, start2, moveVertically(this, start2, 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(pos) {
    return this.docView.domAtPos(pos);
  }
  /**
  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(node, offset = 0) {
    return this.docView.posFromDOM(node, 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(pos, side = 1) {
    this.readMeasured();
    let rect = this.docView.coordsAt(pos, side);
    if (!rect || rect.left == rect.right)
      return rect;
    let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
    let span = order[BidiSpan.find(order, pos - line.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(pos) {
    this.readMeasured();
    return this.docView.coordsForChar(pos);
  }
  /**
  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(pos) {
    let perLine = this.state.facet(perLineTextDirection);
    if (!perLine || pos < this.viewport.from || pos > this.viewport.to)
      return this.textDirection;
    this.readMeasured();
    return this.docView.textDirectionAt(pos);
  }
  /**
  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(line) {
    if (line.length > MaxBidiLine)
      return trivialOrder(line.length);
    let dir = this.textDirectionAt(line.from), isolates;
    for (let entry of this.bidiCache) {
      if (entry.from == line.from && entry.dir == dir && (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line))))
        return entry.order;
    }
    if (!isolates)
      isolates = getIsolatedRanges(this, line);
    let order = computeOrder(line.text, dir, isolates);
    this.bidiCache.push(new CachedOrder(line.from, line.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(root68) {
    if (this._root != root68) {
      this._root = root68;
      this.observer.setWindow((root68.nodeType == 9 ? root68 : root68.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(pos, options4 = {}) {
    return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options4.y, options4.x, options4.yMargin, options4.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.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(to) {
    if (to == null)
      this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1;
    else if (typeof to == "boolean")
      this.inputState.tabFocusMode = to ? 0 : -1;
    else if (this.inputState.tabFocusMode != 0)
      this.inputState.tabFocusMode = Date.now() + to;
  }
  /**
  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, options4) {
    let prefix = StyleModule.newName();
    let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
    if (options4 && options4.dark)
      result.push(darkTheme.of(true));
    return result;
  }
  /**
  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();
var MaxBidiLine = 4096;
var BadMeasure = {};
var CachedOrder = class _CachedOrder {
  constructor(from, to, dir, isolates, fresh, order) {
    this.from = from;
    this.to = to;
    this.dir = dir;
    this.isolates = isolates;
    this.fresh = fresh;
    this.order = order;
  }
  static update(cache, changes) {
    if (changes.empty && !cache.some((c) => c.fresh))
      return cache;
    let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
    for (let i2 = Math.max(0, cache.length - 10); i2 < cache.length; i2++) {
      let entry = cache[i2];
      if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
        result.push(new _CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
    }
    return result;
  }
};
function attrsFromFacet(view, facet, base2) {
  for (let sources = view.state.facet(facet), i2 = sources.length - 1; i2 >= 0; i2--) {
    let source3 = sources[i2], value = typeof source3 == "function" ? source3(view) : source3;
    if (value)
      combineAttrs(value, base2);
  }
  return base2;
}
var currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
function normalizeKeyName(name3, platform) {
  const parts2 = name3.split(/-(?!$)/);
  let result = parts2[parts2.length - 1];
  if (result == "Space")
    result = " ";
  let alt, ctrl, shift2, meta2;
  for (let i2 = 0; i2 < parts2.length - 1; ++i2) {
    const mod = parts2[i2];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta2 = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift2 = true;
    else if (/^mod$/i.test(mod)) {
      if (platform == "mac")
        meta2 = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta2)
    result = "Meta-" + result;
  if (shift2)
    result = "Shift-" + result;
  return result;
}
function modifiers(name3, event2, shift2) {
  if (event2.altKey)
    name3 = "Alt-" + name3;
  if (event2.ctrlKey)
    name3 = "Ctrl-" + name3;
  if (event2.metaKey)
    name3 = "Meta-" + name3;
  if (shift2 !== false && event2.shiftKey)
    name3 = "Shift-" + name3;
  return name3;
}
var handleKeyEvents = /* @__PURE__ */ Prec.default(/* @__PURE__ */ EditorView.domEventHandlers({
  keydown(event2, view) {
    return runHandlers(getKeymap(view.state), event2, view, "editor");
  }
}));
var keymap = /* @__PURE__ */ Facet.define({ enables: handleKeyEvents });
var Keymaps = /* @__PURE__ */ new WeakMap();
function getKeymap(state2) {
  let bindings = state2.facet(keymap);
  let map2 = Keymaps.get(bindings);
  if (!map2)
    Keymaps.set(bindings, map2 = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
  return map2;
}
function runScopeHandlers(view, event2, scope) {
  return runHandlers(getKeymap(view.state), event2, view, scope);
}
var storedPrefix = null;
var PrefixTimeout = 4e3;
function buildKeymap(bindings, platform = currentPlatform) {
  let bound = /* @__PURE__ */ Object.create(null);
  let isPrefix = /* @__PURE__ */ Object.create(null);
  let checkPrefix = (name3, is2) => {
    let current = isPrefix[name3];
    if (current == null)
      isPrefix[name3] = is2;
    else if (current != is2)
      throw new Error("Key binding " + name3 + " is used both as a regular binding and as a multi-stroke prefix");
  };
  let add3 = (scope, key2, command2, preventDefault2, stopPropagation2) => {
    var _a2, _b;
    let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
    let parts2 = key2.split(/ (?!$)/).map((k) => normalizeKeyName(k, platform));
    for (let i2 = 1; i2 < parts2.length; i2++) {
      let prefix = parts2.slice(0, i2).join(" ");
      checkPrefix(prefix, true);
      if (!scopeObj[prefix])
        scopeObj[prefix] = {
          preventDefault: true,
          stopPropagation: false,
          run: [(view) => {
            let ourObj = storedPrefix = { view, prefix, scope };
            setTimeout(() => {
              if (storedPrefix == ourObj)
                storedPrefix = null;
            }, PrefixTimeout);
            return true;
          }]
        };
    }
    let full = parts2.join(" ");
    checkPrefix(full, false);
    let binding = scopeObj[full] || (scopeObj[full] = {
      preventDefault: false,
      stopPropagation: false,
      run: ((_b = (_a2 = scopeObj._any) === null || _a2 === void 0 ? void 0 : _a2.run) === null || _b === void 0 ? void 0 : _b.slice()) || []
    });
    if (command2)
      binding.run.push(command2);
    if (preventDefault2)
      binding.preventDefault = true;
    if (stopPropagation2)
      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 name3 = b[platform] || b.key;
    if (!name3)
      continue;
    for (let scope of scopes) {
      add3(scope, name3, b.run, b.preventDefault, b.stopPropagation);
      if (b.shift)
        add3(scope, "Shift-" + name3, b.shift, b.preventDefault, b.stopPropagation);
    }
  }
  return bound;
}
var currentKeyEvent = null;
function runHandlers(map2, event2, view, scope) {
  currentKeyEvent = event2;
  let name3 = keyName(event2);
  let charCode = codePointAt2(name3, 0), isChar = codePointSize2(charCode) == name3.length && name3 != " ";
  let prefix = "", handled = false, prevented = false, stopPropagation2 = false;
  if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
    prefix = storedPrefix.prefix + " ";
    if (modifierCodes.indexOf(event2.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)
              stopPropagation2 = true;
            return true;
          }
        }
      if (binding.preventDefault) {
        if (binding.stopPropagation)
          stopPropagation2 = true;
        prevented = true;
      }
    }
    return false;
  };
  let scopeObj = map2[scope], baseName, shiftName;
  if (scopeObj) {
    if (runFor(scopeObj[prefix + modifiers(name3, event2, !isChar)])) {
      handled = true;
    } else if (isChar && (event2.altKey || event2.metaKey || event2.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
    !(browser.windows && event2.ctrlKey && event2.altKey) && (baseName = base[event2.keyCode]) && baseName != name3) {
      if (runFor(scopeObj[prefix + modifiers(baseName, event2, true)])) {
        handled = true;
      } else if (event2.shiftKey && (shiftName = shift[event2.keyCode]) != name3 && shiftName != baseName && runFor(scopeObj[prefix + modifiers(shiftName, event2, false)])) {
        handled = true;
      }
    } else if (isChar && event2.shiftKey && runFor(scopeObj[prefix + modifiers(name3, event2, true)])) {
      handled = true;
    }
    if (!handled && runFor(scopeObj._any))
      handled = true;
  }
  if (prevented)
    handled = true;
  if (handled && stopPropagation2)
    event2.stopPropagation();
  currentKeyEvent = null;
  return handled;
}
var RectangleMarker = class _RectangleMarker {
  /**
  Create a marker with the given class and dimensions. If `width`
  is null, the DOM element will get no width style.
  */
  constructor(className, left2, top3, width, height) {
    this.className = className;
    this.left = left2;
    this.top = top3;
    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, className, range2) {
    if (range2.empty) {
      let pos = view.coordsAtPos(range2.head, range2.assoc || 1);
      if (!pos)
        return [];
      let base2 = getBase(view);
      return [new _RectangleMarker(className, pos.left - base2.left, pos.top - base2.top, null, pos.bottom - pos.top)];
    } else {
      return rectanglesForRange(view, className, range2);
    }
  }
};
function getBase(view) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let left2 = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
  return { left: left2 - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
}
function wrappedLine(view, pos, side, inside2) {
  let coords = view.coordsAtPos(pos, side * 2);
  if (!coords)
    return inside2;
  let editorRect = view.dom.getBoundingClientRect();
  let y2 = (coords.top + coords.bottom) / 2;
  let left2 = view.posAtCoords({ x: editorRect.left + 1, y: y2 });
  let right2 = view.posAtCoords({ x: editorRect.right - 1, y: y2 });
  if (left2 == null || right2 == null)
    return inside2;
  return { from: Math.max(inside2.from, Math.min(left2, right2)), to: Math.min(inside2.to, Math.max(left2, right2)) };
}
function rectanglesForRange(view, className, range2) {
  if (range2.to <= view.viewport.from || range2.from >= view.viewport.to)
    return [];
  let from = Math.max(range2.from, view.viewport.from), to = Math.min(range2.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, to);
  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, to, -1, visualEnd);
  if (visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) {
    return pieces(drawForLine(range2.from, range2.to, visualStart));
  } else {
    let top3 = visualStart ? drawForLine(range2.from, null, visualStart) : drawForWidget(startBlock, false);
    let bottom2 = visualEnd ? drawForLine(null, range2.to, visualEnd) : drawForWidget(endBlock, true);
    let between = [];
    if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) || startBlock.widgetLineBreaks > 1 && top3.bottom + view.defaultLineHeight / 2 < bottom2.top)
      between.push(piece(leftSide, top3.bottom, rightSide, bottom2.top));
    else if (top3.bottom < bottom2.top && view.elementAtHeight((top3.bottom + bottom2.top) / 2).type == BlockType.Text)
      top3.bottom = bottom2.top = (top3.bottom + bottom2.top) / 2;
    return pieces(top3).concat(between).concat(pieces(bottom2));
  }
  function piece(left2, top3, right2, bottom2) {
    return new RectangleMarker(className, left2 - base2.left, top3 - base2.top, right2 - left2, bottom2 - top3);
  }
  function pieces({ top: top3, bottom: bottom2, horizontal }) {
    let pieces2 = [];
    for (let i2 = 0; i2 < horizontal.length; i2 += 2)
      pieces2.push(piece(horizontal[i2], top3, horizontal[i2 + 1], bottom2));
    return pieces2;
  }
  function drawForLine(from2, to2, line) {
    let top3 = 1e9, bottom2 = -1e9, horizontal = [];
    function addSpan(from3, fromOpen, to3, toOpen, dir) {
      let fromCoords = view.coordsAtPos(from3, from3 == line.to ? -2 : 2);
      let toCoords = view.coordsAtPos(to3, to3 == line.from ? 2 : -2);
      if (!fromCoords || !toCoords)
        return;
      top3 = Math.min(fromCoords.top, toCoords.top, top3);
      bottom2 = Math.max(fromCoords.bottom, toCoords.bottom, bottom2);
      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 start2 = from2 !== null && from2 !== void 0 ? from2 : line.from, end = to2 !== null && to2 !== void 0 ? to2 : line.to;
    for (let r2 of view.visibleRanges)
      if (r2.to > start2 && r2.from < end) {
        for (let pos = Math.max(r2.from, start2), endPos = Math.min(r2.to, end); ; ) {
          let docLine = view.state.doc.lineAt(pos);
          for (let span of view.bidiSpans(docLine)) {
            let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
            if (spanFrom >= endPos)
              break;
            if (spanTo > pos)
              addSpan(Math.max(spanFrom, pos), from2 == null && spanFrom <= start2, Math.min(spanTo, endPos), to2 == null && spanTo >= end, span.dir);
          }
          pos = docLine.to + 1;
          if (pos >= endPos)
            break;
        }
      }
    if (horizontal.length == 0)
      addSpan(start2, from2 == null, end, to2 == null, view.textDirection);
    return { top: top3, bottom: bottom2, horizontal };
  }
  function drawForWidget(block2, top3) {
    let y2 = contentRect.top + (top3 ? block2.top : block2.bottom);
    return { top: y2, bottom: y2, horizontal: [] };
  }
}
function sameMarker(a, b) {
  return a.constructor == b.constructor && a.eq(b);
}
var LayerView = class {
  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(update3) {
    if (update3.startState.facet(layerOrder) != update3.state.facet(layerOrder))
      this.setOrder(update3.state);
    if (this.layer.update(update3, this.dom) || update3.geometryChanged) {
      this.scale();
      update3.view.requestMeasure(this.measureReq);
    }
  }
  docViewUpdate(view) {
    if (this.layer.updateOnDocViewUpdate !== false)
      view.requestMeasure(this.measureReq);
  }
  setOrder(state2) {
    let pos = 0, order = state2.facet(layerOrder);
    while (pos < order.length && order[pos] != this.layer)
      pos++;
    this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
  }
  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 next2 = old.nextSibling;
        old.remove();
        old = next2;
      }
      this.drawn = markers;
    }
  }
  destroy() {
    if (this.layer.destroy)
      this.layer.destroy(this.dom, this.view);
    this.dom.remove();
  }
};
var layerOrder = /* @__PURE__ */ Facet.define();
function layer(config2) {
  return [
    ViewPlugin.define((v) => new LayerView(v, config2)),
    layerOrder.of(config2)
  ];
}
var CanHidePrimary = !(browser.ios && browser.webkit && browser.webkit_version < 534);
var 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(update3) {
  return update3.startState.facet(selectionConfig) != update3.state.facet(selectionConfig);
}
var cursorLayer = /* @__PURE__ */ layer({
  above: true,
  markers(view) {
    let { state: state2 } = view, conf = state2.facet(selectionConfig);
    let cursors = [];
    for (let r2 of state2.selection.ranges) {
      let prim = r2 == state2.selection.main;
      if (r2.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
        let className = 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, className, cursor))
          cursors.push(piece);
      }
    }
    return cursors;
  },
  update(update3, dom) {
    if (update3.transactions.some((tr) => tr.selection))
      dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
    let confChange = configChanged(update3);
    if (confChange)
      setBlinkRate(update3.state, dom);
    return update3.docChanged || update3.selectionSet || confChange;
  },
  mount(dom, view) {
    setBlinkRate(view.state, dom);
  },
  class: "cm-cursorLayer"
});
function setBlinkRate(state2, dom) {
  dom.style.animationDuration = state2.facet(selectionConfig).cursorBlinkRate + "ms";
}
var 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(update3, dom) {
    return update3.docChanged || update3.selectionSet || update3.viewportChanged || configChanged(update3);
  },
  class: "cm-selectionLayer"
});
var 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";
var hideNativeSelection = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.theme(themeSpec));
function iterMatches(doc2, re2, from, to, f) {
  re2.lastIndex = 0;
  for (let cursor = doc2.iterRange(from, to), pos = from, m2; !cursor.next().done; pos += cursor.value.length) {
    if (!cursor.lineBreak)
      while (m2 = re2.exec(cursor.value))
        f(pos + m2.index, m2);
  }
}
function matchRanges(view, maxLength) {
  let visible = view.visibleRanges;
  if (visible.length == 1 && visible[0].from == view.viewport.from && visible[0].to == view.viewport.to)
    return visible;
  let result = [];
  for (let { from, to } of visible) {
    from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
    to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
    if (result.length && result[result.length - 1].to >= from)
      result[result.length - 1].to = to;
    else
      result.push({ from, to });
  }
  return result;
}
var MatchDecorator = class {
  /**
  Create a decorator.
  */
  constructor(config2) {
    const { regexp, decoration, decorate, boundary: boundary2, 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, add3) => decorate(add3, from, from + match[0].length, match, view);
    } else if (typeof decoration == "function") {
      this.addMatch = (match, view, from, add3) => {
        let deco = decoration(match, view, from);
        if (deco)
          add3(from, from + match[0].length, deco);
      };
    } else if (decoration) {
      this.addMatch = (match, _view, from, add3) => add3(from, from + match[0].length, decoration);
    } else {
      throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
    }
    this.boundary = boundary2;
    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(), add3 = build.add.bind(build);
    for (let { from, to } of matchRanges(view, this.maxLength))
      iterMatches(view.state.doc, this.regexp, from, to, (from2, m2) => this.addMatch(m2, view, from2, add3));
    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(update3, deco) {
    let changeFrom = 1e9, changeTo = -1;
    if (update3.docChanged)
      update3.changes.iterChanges((_f, _t, from, to) => {
        if (to >= update3.view.viewport.from && from <= update3.view.viewport.to) {
          changeFrom = Math.min(from, changeFrom);
          changeTo = Math.max(to, changeTo);
        }
      });
    if (update3.viewportMoved || changeTo - changeFrom > 1e3)
      return this.createDeco(update3.view);
    if (changeTo > -1)
      return this.updateRange(update3.view, deco.map(update3.changes), changeFrom, changeTo);
    return deco;
  }
  updateRange(view, deco, updateFrom, updateTo) {
    for (let r2 of view.visibleRanges) {
      let from = Math.max(r2.from, updateFrom), to = Math.min(r2.to, updateTo);
      if (to > from) {
        let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
        let start2 = 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])) {
              start2 = from;
              break;
            }
          for (; to < toLine.to; to++)
            if (this.boundary.test(toLine.text[to - toLine.from])) {
              end = to;
              break;
            }
        }
        let ranges = [], m2;
        let add3 = (from2, to2, deco2) => ranges.push(deco2.range(from2, to2));
        if (fromLine == toLine) {
          this.regexp.lastIndex = start2 - fromLine.from;
          while ((m2 = this.regexp.exec(fromLine.text)) && m2.index < end - fromLine.from)
            this.addMatch(m2, view, m2.index + fromLine.from, add3);
        } else {
          iterMatches(view.state.doc, this.regexp, start2, end, (from2, m3) => this.addMatch(m3, view, from2, add3));
        }
        deco = deco.update({ filterFrom: start2, filterTo: end, filter: (from2, to2) => from2 < start2 || to2 > end, add: ranges });
      }
    }
    return deco;
  }
};
var UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
var Specials = /* @__PURE__ */ new RegExp("[\0-\b\n-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]", UnicodeRegexpSupport);
var 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"
};
var _supportsTabSize = null;
function supportsTabSize() {
  var _a2;
  if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
    let styles = document.body.style;
    _supportsTabSize = ((_a2 = styles.tabSize) !== null && _a2 !== void 0 ? _a2 : styles.MozTabSize) != null;
  }
  return _supportsTabSize || false;
}
var 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()];
}
var _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: (m2, view, pos) => {
          let { doc: doc2 } = view.state;
          let code = codePointAt2(m2[0], 0);
          if (code == 9) {
            let line = doc2.lineAt(pos);
            let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);
            return Decoration.replace({
              widget: new TabWidget((size - col % size) * this.view.defaultCharacterWidth / this.view.scaleX)
            });
          }
          return this.decorationCache[code] || (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
        },
        boundary: conf.replaceTabs ? void 0 : /[^]/
      });
    }
    update(update3) {
      let conf = update3.state.facet(specialCharConfig);
      if (update3.startState.facet(specialCharConfig) != conf) {
        this.decorator = this.makeDecorator(conf);
        this.decorations = this.decorator.createDeco(update3.view);
      } else {
        this.decorations = this.decorator.updateDeco(update3, this.decorations);
      }
    }
  }, {
    decorations: (v) => v.decorations
  }));
}
var DefaultPlaceholder = "\u2022";
function placeholder$1(code) {
  if (code >= 32)
    return DefaultPlaceholder;
  if (code == 10)
    return "\u2424";
  return String.fromCharCode(9216 + code);
}
var SpecialCharWidget = class extends WidgetType {
  constructor(options4, code) {
    super();
    this.options = options4;
    this.code = code;
  }
  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 custom2 = this.options.render && this.options.render(this.code, desc, ph);
    if (custom2)
      return custom2;
    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;
  }
};
var TabWidget = class 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;
  }
};
function highlightActiveLine() {
  return activeLineHighlighter;
}
var lineDeco = /* @__PURE__ */ Decoration.line({ class: "cm-activeLine" });
var activeLineHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = this.getDeco(view);
  }
  update(update3) {
    if (update3.docChanged || update3.selectionSet)
      this.decorations = this.getDeco(update3.view);
  }
  getDeco(view) {
    let lastLineStart = -1, deco = [];
    for (let r2 of view.state.selection.ranges) {
      let line = view.lineBlockAt(r2.head);
      if (line.from > lastLineStart) {
        deco.push(lineDeco.range(line.from));
        lastLineStart = line.from;
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v) => v.decorations
});
var Placeholder = class extends WidgetType {
  constructor(content2) {
    super();
    this.content = content2;
  }
  toDOM(view) {
    let wrap = document.createElement("span");
    wrap.className = "cm-placeholder";
    wrap.style.pointerEvents = "none";
    wrap.appendChild(typeof this.content == "string" ? document.createTextNode(this.content) : typeof this.content == "function" ? this.content(view) : this.content.cloneNode(true));
    if (typeof this.content == "string")
      wrap.setAttribute("aria-label", "placeholder " + this.content);
    else
      wrap.setAttribute("aria-hidden", "true");
    return wrap;
  }
  coordsAt(dom) {
    let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];
    if (!rects.length)
      return null;
    let style = window.getComputedStyle(dom.parentNode);
    let rect = flattenRect(rects[0], style.direction != "rtl");
    let lineHeight = parseInt(style.lineHeight);
    if (rect.bottom - rect.top > lineHeight * 1.5)
      return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight };
    return rect;
  }
  ignoreEvent() {
    return false;
  }
};
function placeholder(content2) {
  return ViewPlugin.fromClass(class {
    constructor(view) {
      this.view = view;
      this.placeholder = content2 ? Decoration.set([Decoration.widget({ widget: new Placeholder(content2), side: 1 }).range(0)]) : Decoration.none;
    }
    get decorations() {
      return this.view.state.doc.length ? Decoration.none : this.placeholder;
    }
  }, { decorations: (v) => v.decorations });
}
var MaxOff = 2e3;
function rectangleFor(state2, a, b) {
  let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);
  let ranges = [];
  if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {
    let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);
    for (let i2 = startLine; i2 <= endLine; i2++) {
      let line = state2.doc.line(i2);
      if (line.length <= endOff)
        ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
    }
  } else {
    let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);
    for (let i2 = startLine; i2 <= endLine; i2++) {
      let line = state2.doc.line(i2);
      let start2 = findColumn(line.text, startCol, state2.tabSize, true);
      if (start2 < 0) {
        ranges.push(EditorSelection.cursor(line.to));
      } else {
        let end = findColumn(line.text, endCol, state2.tabSize);
        ranges.push(EditorSelection.range(line.from + start2, line.from + end));
      }
    }
  }
  return ranges;
}
function absoluteColumn(view, x2) {
  let ref = view.coordsAtPos(view.viewport.from);
  return ref ? Math.round(Math.abs((ref.left - x2) / view.defaultCharacterWidth)) : -1;
}
function getPos(view, event2) {
  let offset = view.posAtCoords({ x: event2.clientX, y: event2.clientY }, false);
  let line = view.state.doc.lineAt(offset), off = offset - line.from;
  let col = off > MaxOff ? -1 : off == line.length ? absoluteColumn(view, event2.clientX) : countColumn(line.text, view.state.tabSize, offset - line.from);
  return { line: line.number, col, off };
}
function rectangleSelectionStyle(view, event2) {
  let start2 = getPos(view, event2), startSel = view.state.selection;
  if (!start2)
    return null;
  return {
    update(update3) {
      if (update3.docChanged) {
        let newStart = update3.changes.mapPos(update3.startState.doc.line(start2.line).from);
        let newLine = update3.state.doc.lineAt(newStart);
        start2 = { line: newLine.number, col: start2.col, off: Math.min(start2.off, newLine.length) };
        startSel = startSel.map(update3.changes);
      }
    },
    get(event3, _extend, multiple) {
      let cur2 = getPos(view, event3);
      if (!cur2)
        return startSel;
      let ranges = rectangleFor(view.state, start2, cur2);
      if (!ranges.length)
        return startSel;
      if (multiple)
        return EditorSelection.create(ranges.concat(startSel.ranges));
      else
        return EditorSelection.create(ranges);
    }
  };
}
function rectangularSelection(options4) {
  let filter2 = (options4 === null || options4 === void 0 ? void 0 : options4.eventFilter) || ((e) => e.altKey && e.button == 0);
  return EditorView.mouseSelectionStyle.of((view, event2) => filter2(event2) ? rectangleSelectionStyle(view, event2) : null);
}
var Outside = "-10000px";
var TooltipViewManager = class {
  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((t4) => t4);
    let prev = null;
    this.tooltipViews = this.tooltips.map((t4) => prev = createTooltipView(t4, prev));
  }
  update(update3, above) {
    var _a2;
    let input = update3.state.facet(this.facet);
    let tooltips = input.filter((x2) => x2);
    if (input === this.input) {
      for (let t4 of this.tooltipViews)
        if (t4.update)
          t4.update(update3);
      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(update3);
      }
    }
    for (let t4 of this.tooltipViews)
      if (tooltipViews.indexOf(t4) < 0) {
        this.removeTooltipView(t4);
        (_a2 = t4.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(t4);
      }
    if (above) {
      newAbove.forEach((val, i2) => above[i2] = val);
      above.length = newAbove.length;
    }
    this.input = input;
    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 };
}
var tooltipConfig = /* @__PURE__ */ Facet.define({
  combine: (values) => {
    var _a2, _b, _c;
    return {
      position: browser.ios ? "absolute" : ((_a2 = values.find((conf) => conf.position)) === null || _a2 === void 0 ? void 0 : _a2.position) || "fixed",
      parent: ((_b = values.find((conf) => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
      tooltipSpace: ((_c = values.find((conf) => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace
    };
  }
});
var knownHeight = /* @__PURE__ */ new WeakMap();
var 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, (t4, p) => this.createTooltip(t4, p), (t4) => {
      if (this.resizeObserver)
        this.resizeObserver.unobserve(t4.dom);
      t4.dom.remove();
    });
    this.above = this.manager.tooltips.map((t4) => !!t4.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 tooltip2 of this.manager.tooltipViews)
        this.intersectionObserver.observe(tooltip2.dom);
    }
  }
  measureSoon() {
    if (this.measureTimeout < 0)
      this.measureTimeout = setTimeout(() => {
        this.measureTimeout = -1;
        this.maybeMeasure();
      }, 50);
  }
  update(update3) {
    if (update3.transactions.length)
      this.lastTransaction = Date.now();
    let updated = this.manager.update(update3, this.above);
    if (updated)
      this.observeIntersection();
    let shouldMeasure = updated || update3.geometryChanged;
    let newConfig = update3.state.facet(tooltipConfig);
    if (newConfig.position != this.position && !this.madeAbsolute) {
      this.position = newConfig.position;
      for (let t4 of this.manager.tooltipViews)
        t4.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 t4 of this.manager.tooltipViews)
        this.container.appendChild(t4.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(tooltip2, prev) {
    let tooltipView = tooltip2.create(this.view);
    let before = prev ? prev.dom : null;
    tooltipView.dom.classList.add("cm-tooltip");
    if (tooltip2.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, _b, _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();
    (_b = this.resizeObserver) === null || _b === void 0 ? void 0 : _b.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 visible = this.view.scrollDOM.getBoundingClientRect(), margins = getScrollMargins(this.view);
    return {
      visible: {
        left: visible.left + margins.left,
        top: visible.top + margins.top,
        right: visible.right - margins.right,
        bottom: visible.bottom - margins.bottom
      },
      parent: this.parent ? this.container.getBoundingClientRect() : this.view.dom.getBoundingClientRect(),
      pos: this.manager.tooltips.map((t4, i2) => {
        let tv = this.manager.tooltipViews[i2];
        return tv.getCoords ? tv.getCoords(t4.pos) : this.view.coordsAtPos(t4.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 t4 of this.manager.tooltipViews)
        t4.dom.style.position = "absolute";
    }
    let { visible, space, scaleX, scaleY } = measured;
    let others = [];
    for (let i2 = 0; i2 < this.manager.tooltips.length; i2++) {
      let tooltip2 = this.manager.tooltips[i2], tView = this.manager.tooltipViews[i2], { dom } = tView;
      let pos = measured.pos[i2], size = measured.size[i2];
      if (!pos || tooltip2.clip !== false && (pos.bottom <= Math.max(visible.top, space.top) || pos.top >= Math.min(visible.bottom, space.bottom) || pos.right < Math.max(visible.left, space.left) - 0.1 || pos.left > Math.min(visible.right, space.right) + 0.1)) {
        dom.style.top = Outside;
        continue;
      }
      let arrow = tooltip2.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 left2 = size.width > space.right - space.left ? ltr ? space.left : space.right - size.width : ltr ? Math.max(space.left, Math.min(pos.left - (arrow ? 14 : 0) + offset.x, space.right - width)) : Math.min(Math.max(space.left, pos.left - width + (arrow ? 14 : 0) - offset.x), space.right - width);
      let above = this.above[i2];
      if (!tooltip2.strictSide && (above ? pos.top - height - arrowHeight - offset.y < space.top : pos.bottom + height + arrowHeight + offset.y > space.bottom) && above == space.bottom - pos.bottom > pos.top - space.top)
        above = this.above[i2] = !above;
      let spaceVert = (above ? pos.top - space.top : space.bottom - pos.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 top3 = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
      let right2 = left2 + width;
      if (tView.overlap !== true) {
        for (let r2 of others)
          if (r2.left < right2 && r2.right > left2 && r2.top < top3 + height && r2.bottom > top3)
            top3 = above ? r2.top - height - 2 - arrowHeight : r2.bottom + arrowHeight + 2;
      }
      if (this.position == "absolute") {
        dom.style.top = (top3 - measured.parent.top) / scaleY + "px";
        setLeftStyle(dom, (left2 - measured.parent.left) / scaleX);
      } else {
        dom.style.top = top3 / scaleY + "px";
        setLeftStyle(dom, left2 / scaleX);
      }
      if (arrow) {
        let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left2 + 14 - 7);
        arrow.style.left = arrowLeft / scaleX + "px";
      }
      if (tView.overlap !== true)
        others.push({ left: left2, top: top3, right: right2, bottom: top3 + 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, value) {
  let current = parseInt(elt.style.left, 10);
  if (isNaN(current) || Math.abs(value - current) > 1)
    elt.style.left = value + "px";
}
var baseTheme = /* @__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"
    }
  }
});
var noOffset = { x: 0, y: 0 };
var showTooltip = /* @__PURE__ */ Facet.define({
  enables: [tooltipPlugin, baseTheme]
});
var showHoverTooltip = /* @__PURE__ */ Facet.define({
  combine: (inputs) => inputs.reduce((a, i2) => a.concat(i2), [])
});
var HoverTooltipHost = 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, (t4, p) => this.createHostedView(t4, p), (t4) => t4.dom.remove());
  }
  createHostedView(tooltip2, prev) {
    let hostedView = tooltip2.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(update3) {
    this.manager.update(update3);
  }
  destroy() {
    var _a2;
    for (let t4 of this.manager.tooltipViews)
      (_a2 = t4.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(t4);
  }
  passProp(name3) {
    let value = void 0;
    for (let view of this.manager.tooltipViews) {
      let given = view[name3];
      if (given !== void 0) {
        if (value === void 0)
          value = given;
        else if (value !== given)
          return void 0;
      }
    }
    return value;
  }
  get offset() {
    return this.passProp("offset");
  }
  get getCoords() {
    return this.passProp("getCoords");
  }
  get overlap() {
    return this.passProp("overlap");
  }
  get resize() {
    return this.passProp("resize");
  }
};
var showHoverTooltipHost = /* @__PURE__ */ showTooltip.compute([showHoverTooltip], (state2) => {
  let tooltips = state2.facet(showHoverTooltip);
  if (tooltips.length === 0)
    return null;
  return {
    pos: Math.min(...tooltips.map((t4) => t4.pos)),
    end: Math.max(...tooltips.map((t4) => {
      var _a2;
      return (_a2 = t4.end) !== null && _a2 !== void 0 ? _a2 : t4.pos;
    })),
    create: HoverTooltipHost.create,
    above: tooltips[0].above,
    arrow: tooltips.some((t4) => t4.arrow)
  };
});
var HoverPlugin = class {
  constructor(view, source3, field, setHover, hoverTime) {
    this.view = view;
    this.source = source3;
    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 pos, side = 1;
    if (desc instanceof WidgetView) {
      pos = desc.posAtStart;
    } else {
      pos = view.posAtCoords(lastMove);
      if (pos == null)
        return;
      let posCoords = view.coordsAtPos(pos);
      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(pos)).find((s) => s.from <= pos && s.to >= pos);
      let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
      side = lastMove.x < posCoords.left ? -rtl : rtl;
    }
    let open = this.source(view, pos, side);
    if (open === null || open === void 0 ? void 0 : open.then) {
      let pending2 = this.pending = { pos };
      open.then((result) => {
        if (this.pending == pending2) {
          this.pending = null;
          if (result && !(Array.isArray(result) && !result.length))
            view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) });
        }
      }, (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 index3 = plugin ? plugin.manager.tooltips.findIndex((t4) => t4.create == HoverTooltipHost.create) : -1;
    return index3 > -1 ? plugin.manager.tooltipViews[index3] : null;
  }
  mousemove(event2) {
    var _a2, _b;
    this.lastMove = { x: event2.clientX, y: event2.clientY, target: event2.target, time: Date.now() };
    if (this.hoverTimeout < 0)
      this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
    let { active, tooltip: tooltip2 } = this;
    if (active.length && tooltip2 && !isInTooltip(tooltip2.dom, event2) || this.pending) {
      let { pos } = active[0] || this.pending, end = (_b = (_a2 = active[0]) === null || _a2 === void 0 ? void 0 : _a2.end) !== null && _b !== void 0 ? _b : pos;
      if (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange(this.view, pos, end, event2.clientX, event2.clientY)) {
        this.view.dispatch({ effects: this.setHover.of([]) });
        this.pending = null;
      }
    }
  }
  mouseleave(event2) {
    clearTimeout(this.hoverTimeout);
    this.hoverTimeout = -1;
    let { active } = this;
    if (active.length) {
      let { tooltip: tooltip2 } = this;
      let inTooltip = tooltip2 && tooltip2.dom.contains(event2.relatedTarget);
      if (!inTooltip)
        this.view.dispatch({ effects: this.setHover.of([]) });
      else
        this.watchTooltipLeave(tooltip2.dom);
    }
  }
  watchTooltipLeave(tooltip2) {
    let watch = (event2) => {
      tooltip2.removeEventListener("mouseleave", watch);
      if (this.active.length && !this.view.dom.contains(event2.relatedTarget))
        this.view.dispatch({ effects: this.setHover.of([]) });
    };
    tooltip2.addEventListener("mouseleave", watch);
  }
  destroy() {
    clearTimeout(this.hoverTimeout);
    this.view.dom.removeEventListener("mouseleave", this.mouseleave);
    this.view.dom.removeEventListener("mousemove", this.mousemove);
  }
};
var tooltipMargin = 4;
function isInTooltip(tooltip2, event2) {
  let { left: left2, right: right2, top: top3, bottom: bottom2 } = tooltip2.getBoundingClientRect(), arrow;
  if (arrow = tooltip2.querySelector(".cm-tooltip-arrow")) {
    let arrowRect = arrow.getBoundingClientRect();
    top3 = Math.min(arrowRect.top, top3);
    bottom2 = Math.max(arrowRect.bottom, bottom2);
  }
  return event2.clientX >= left2 - tooltipMargin && event2.clientX <= right2 + tooltipMargin && event2.clientY >= top3 - tooltipMargin && event2.clientY <= bottom2 + tooltipMargin;
}
function isOverRange(view, from, to, x2, y2, margin) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
  if (rect.left > x2 || rect.right < x2 || rect.top > y2 || Math.min(rect.bottom, docBottom) < y2)
    return false;
  let pos = view.posAtCoords({ x: x2, y: y2 }, false);
  return pos >= from && pos <= to;
}
function hoverTooltip(source3, options4 = {}) {
  let setHover = StateEffect.define();
  let hoverState = StateField.define({
    create() {
      return [];
    },
    update(value, tr) {
      if (value.length) {
        if (options4.hideOnChange && (tr.docChanged || tr.selection))
          value = [];
        else if (options4.hideOn)
          value = value.filter((v) => !options4.hideOn(tr, v));
        if (tr.docChanged) {
          let mapped = [];
          for (let tooltip2 of value) {
            let newPos = tr.changes.mapPos(tooltip2.pos, -1, MapMode.TrackDel);
            if (newPos != null) {
              let copy2 = Object.assign(/* @__PURE__ */ Object.create(null), tooltip2);
              copy2.pos = newPos;
              if (copy2.end != null)
                copy2.end = tr.changes.mapPos(copy2.end);
              mapped.push(copy2);
            }
          }
          value = mapped;
        }
      }
      for (let effect2 of tr.effects) {
        if (effect2.is(setHover))
          value = effect2.value;
        if (effect2.is(closeHoverTooltipEffect))
          value = [];
      }
      return value;
    },
    provide: (f) => showHoverTooltip.from(f)
  });
  return {
    active: hoverState,
    extension: [
      hoverState,
      ViewPlugin.define((view) => new HoverPlugin(
        view,
        source3,
        hoverState,
        setHover,
        options4.hoverTime || 300
        /* Hover.Time */
      )),
      showHoverTooltipHost
    ]
  };
}
function getTooltip(view, tooltip2) {
  let plugin = view.plugin(tooltipPlugin);
  if (!plugin)
    return null;
  let found = plugin.manager.tooltips.indexOf(tooltip2);
  return found < 0 ? null : plugin.manager.tooltipViews[found];
}
var closeHoverTooltipEffect = /* @__PURE__ */ StateEffect.define();
var panelConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    let topContainer, bottomContainer;
    for (let c of configs) {
      topContainer = topContainer || c.topContainer;
      bottomContainer = bottomContainer || c.bottomContainer;
    }
    return { topContainer, bottomContainer };
  }
});
function getPanel(view, panel) {
  let plugin = view.plugin(panelPlugin);
  let index3 = plugin ? plugin.specs.indexOf(panel) : -1;
  return index3 > -1 ? plugin.panels[index3] : null;
}
var 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(update3) {
    let conf = update3.state.facet(panelConfig);
    if (this.top.container != conf.topContainer) {
      this.top.sync([]);
      this.top = new PanelGroup(update3.view, true, conf.topContainer);
    }
    if (this.bottom.container != conf.bottomContainer) {
      this.bottom.sync([]);
      this.bottom = new PanelGroup(update3.view, false, conf.bottomContainer);
    }
    this.top.syncClasses();
    this.bottom.syncClasses();
    let input = update3.state.facet(showPanel);
    if (input != this.input) {
      let specs = input.filter((x2) => x2);
      let panels = [], top3 = [], bottom2 = [], mount2 = [];
      for (let spec of specs) {
        let known = this.specs.indexOf(spec), panel;
        if (known < 0) {
          panel = spec(update3.view);
          mount2.push(panel);
        } else {
          panel = this.panels[known];
          if (panel.update)
            panel.update(update3);
        }
        panels.push(panel);
        (panel.top ? top3 : bottom2).push(panel);
      }
      this.specs = specs;
      this.panels = panels;
      this.top.sync(top3);
      this.bottom.sync(bottom2);
      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(update3);
    }
  }
  destroy() {
    this.top.sync([]);
    this.bottom.sync([]);
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value = view.plugin(plugin);
    return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };
  })
});
var PanelGroup = class {
  constructor(view, top3, container) {
    this.view = view;
    this.top = top3;
    this.container = container;
    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 parent2 = this.container || this.view.dom;
      parent2.insertBefore(this.dom, this.top ? parent2.firstChild : null);
    }
    let curDOM = this.dom.firstChild;
    for (let panel of this.panels) {
      if (panel.dom.parentNode == this.dom) {
        while (curDOM != panel.dom)
          curDOM = rm(curDOM);
        curDOM = curDOM.nextSibling;
      } else {
        this.dom.insertBefore(panel.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(node) {
  let next2 = node.nextSibling;
  node.remove();
  return next2;
}
var showPanel = /* @__PURE__ */ Facet.define({
  enables: panelPlugin
});
var GutterMarker = class 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;
var gutterLineClass = /* @__PURE__ */ Facet.define();
var gutterWidgetClass = /* @__PURE__ */ Facet.define();
var defaults = {
  class: "",
  renderEmptyElements: false,
  elementStyle: "",
  markers: () => RangeSet.empty,
  lineMarker: () => null,
  widgetMarker: () => null,
  lineMarkerChange: null,
  initialSpacer: null,
  updateSpacer: null,
  domEventHandlers: {}
};
var activeGutters = /* @__PURE__ */ Facet.define();
function gutter(config2) {
  return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults), config2))];
}
var unfixGutters = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
function gutters(config2) {
  let result = [
    gutterView
  ];
  if (config2 && config2.fixed === false)
    result.push(unfixGutters.of(true));
  return result;
}
var gutterView = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.prevViewport = view.viewport;
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutters";
    this.dom.setAttribute("aria-hidden", "true");
    this.dom.style.minHeight = this.view.contentHeight / this.view.scaleY + "px";
    this.gutters = view.state.facet(activeGutters).map((conf) => new SingleGutterView(view, conf));
    for (let gutter2 of this.gutters)
      this.dom.appendChild(gutter2.dom);
    this.fixed = !view.state.facet(unfixGutters);
    if (this.fixed) {
      this.dom.style.position = "sticky";
    }
    this.syncGutters(false);
    view.scrollDOM.insertBefore(this.dom, view.contentDOM);
  }
  update(update3) {
    if (this.updateGutters(update3)) {
      let vpA = this.prevViewport, vpB = update3.view.viewport;
      let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
      this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);
    }
    if (update3.geometryChanged) {
      this.dom.style.minHeight = this.view.contentHeight / this.view.scaleY + "px";
    }
    if (this.view.state.facet(unfixGutters) != !this.fixed) {
      this.fixed = !this.fixed;
      this.dom.style.position = this.fixed ? "sticky" : "";
    }
    this.prevViewport = update3.view.viewport;
  }
  syncGutters(detach) {
    let after = this.dom.nextSibling;
    if (detach)
      this.dom.remove();
    let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
    let classSet = [];
    let contexts = this.gutters.map((gutter2) => new UpdateContext(gutter2, this.view.viewport, -this.view.documentPadding.top));
    for (let line of this.view.viewportLineBlocks) {
      if (classSet.length)
        classSet = [];
      if (Array.isArray(line.type)) {
        let first = true;
        for (let b of line.type) {
          if (b.type == BlockType.Text && first) {
            advanceCursor(lineClasses, classSet, b.from);
            for (let cx of contexts)
              cx.line(this.view, b, classSet);
            first = false;
          } else if (b.widget) {
            for (let cx of contexts)
              cx.widget(this.view, b);
          }
        }
      } else if (line.type == BlockType.Text) {
        advanceCursor(lineClasses, classSet, line.from);
        for (let cx of contexts)
          cx.line(this.view, line, classSet);
      } else if (line.widget) {
        for (let cx of contexts)
          cx.widget(this.view, line);
      }
    }
    for (let cx of contexts)
      cx.finish();
    if (detach)
      this.view.scrollDOM.insertBefore(this.dom, after);
  }
  updateGutters(update3) {
    let prev = update3.startState.facet(activeGutters), cur2 = update3.state.facet(activeGutters);
    let change = update3.docChanged || update3.heightChanged || update3.viewportChanged || !RangeSet.eq(update3.startState.facet(gutterLineClass), update3.state.facet(gutterLineClass), update3.view.viewport.from, update3.view.viewport.to);
    if (prev == cur2) {
      for (let gutter2 of this.gutters)
        if (gutter2.update(update3))
          change = true;
    } else {
      change = true;
      let gutters2 = [];
      for (let conf of cur2) {
        let known = prev.indexOf(conf);
        if (known < 0) {
          gutters2.push(new SingleGutterView(this.view, conf));
        } else {
          this.gutters[known].update(update3);
          gutters2.push(this.gutters[known]);
        }
      }
      for (let g of this.gutters) {
        g.dom.remove();
        if (gutters2.indexOf(g) < 0)
          g.destroy();
      }
      for (let g of gutters2)
        this.dom.appendChild(g.dom);
      this.gutters = gutters2;
    }
    return change;
  }
  destroy() {
    for (let view of this.gutters)
      view.destroy();
    this.dom.remove();
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value = view.plugin(plugin);
    if (!value || value.gutters.length == 0 || !value.fixed)
      return null;
    return view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth * view.scaleX } : { right: value.dom.offsetWidth * view.scaleX };
  })
});
function asArray2(val) {
  return Array.isArray(val) ? val : [val];
}
function advanceCursor(cursor, collect2, pos) {
  while (cursor.value && cursor.from <= pos) {
    if (cursor.from == pos)
      collect2.push(cursor.value);
    cursor.next();
  }
}
var UpdateContext = class {
  constructor(gutter2, viewport, height) {
    this.gutter = gutter2;
    this.height = height;
    this.i = 0;
    this.cursor = RangeSet.iter(gutter2.markers, viewport.from);
  }
  addElement(view, block2, markers) {
    let { gutter: gutter2 } = this, above = (block2.top - this.height) / view.scaleY, height = block2.height / view.scaleY;
    if (this.i == gutter2.elements.length) {
      let newElt = new GutterElement(view, height, above, markers);
      gutter2.elements.push(newElt);
      gutter2.dom.appendChild(newElt.dom);
    } else {
      gutter2.elements[this.i].update(view, height, above, markers);
    }
    this.height = block2.bottom;
    this.i++;
  }
  line(view, line, extraMarkers) {
    let localMarkers = [];
    advanceCursor(this.cursor, localMarkers, line.from);
    if (extraMarkers.length)
      localMarkers = localMarkers.concat(extraMarkers);
    let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
    if (forLine)
      localMarkers.unshift(forLine);
    let gutter2 = this.gutter;
    if (localMarkers.length == 0 && !gutter2.config.renderEmptyElements)
      return;
    this.addElement(view, line, localMarkers);
  }
  widget(view, block2) {
    let marker = this.gutter.config.widgetMarker(view, block2.widget, block2), markers = marker ? [marker] : null;
    for (let cls of view.state.facet(gutterWidgetClass)) {
      let marker2 = cls(view, block2.widget, block2);
      if (marker2)
        (markers || (markers = [])).push(marker2);
    }
    if (markers)
      this.addElement(view, block2, markers);
  }
  finish() {
    let gutter2 = this.gutter;
    while (gutter2.elements.length > this.i) {
      let last = gutter2.elements.pop();
      gutter2.dom.removeChild(last.dom);
      last.destroy();
    }
  }
};
var SingleGutterView = class {
  constructor(view, config2) {
    this.view = view;
    this.config = config2;
    this.elements = [];
    this.spacer = null;
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
    for (let prop2 in config2.domEventHandlers) {
      this.dom.addEventListener(prop2, (event2) => {
        let target = event2.target, y2;
        if (target != this.dom && this.dom.contains(target)) {
          while (target.parentNode != this.dom)
            target = target.parentNode;
          let rect = target.getBoundingClientRect();
          y2 = (rect.top + rect.bottom) / 2;
        } else {
          y2 = event2.clientY;
        }
        let line = view.lineBlockAtHeight(y2 - view.documentTop);
        if (config2.domEventHandlers[prop2](view, line, event2))
          event2.preventDefault();
      });
    }
    this.markers = asArray2(config2.markers(view));
    if (config2.initialSpacer) {
      this.spacer = new GutterElement(view, 0, 0, [config2.initialSpacer(view)]);
      this.dom.appendChild(this.spacer.dom);
      this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
    }
  }
  update(update3) {
    let prevMarkers = this.markers;
    this.markers = asArray2(this.config.markers(update3.view));
    if (this.spacer && this.config.updateSpacer) {
      let updated = this.config.updateSpacer(this.spacer.markers[0], update3);
      if (updated != this.spacer.markers[0])
        this.spacer.update(update3.view, 0, 0, [updated]);
    }
    let vp = update3.view.viewport;
    return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || (this.config.lineMarkerChange ? this.config.lineMarkerChange(update3) : false);
  }
  destroy() {
    for (let elt of this.elements)
      elt.destroy();
  }
};
var GutterElement = class {
  constructor(view, height, above, markers) {
    this.height = -1;
    this.above = 0;
    this.markers = [];
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutterElement";
    this.update(view, height, above, markers);
  }
  update(view, height, above, markers) {
    if (this.height != height) {
      this.height = height;
      this.dom.style.height = height + "px";
    }
    if (this.above != above)
      this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
    if (!sameMarkers(this.markers, markers))
      this.setMarkers(view, markers);
  }
  setMarkers(view, markers) {
    let cls = "cm-gutterElement", domPos = this.dom.firstChild;
    for (let iNew = 0, iOld = 0; ; ) {
      let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;
      if (marker) {
        let c = marker.elementClass;
        if (c)
          cls += " " + c;
        for (let i2 = iOld; i2 < this.markers.length; i2++)
          if (this.markers[i2].compare(marker)) {
            skipTo = i2;
            matched = true;
            break;
          }
      } else {
        skipTo = this.markers.length;
      }
      while (iOld < skipTo) {
        let next2 = this.markers[iOld++];
        if (next2.toDOM) {
          next2.destroy(domPos);
          let after = domPos.nextSibling;
          domPos.remove();
          domPos = after;
        }
      }
      if (!marker)
        break;
      if (marker.toDOM) {
        if (matched)
          domPos = domPos.nextSibling;
        else
          this.dom.insertBefore(marker.toDOM(view), domPos);
      }
      if (matched)
        iOld++;
    }
    this.dom.className = cls;
    this.markers = markers;
  }
  destroy() {
    this.setMarkers(null, []);
  }
};
function sameMarkers(a, b) {
  if (a.length != b.length)
    return false;
  for (let i2 = 0; i2 < a.length; i2++)
    if (!a[i2].compare(b[i2]))
      return false;
  return true;
}
var lineNumberMarkers = /* @__PURE__ */ Facet.define();
var lineNumberWidgetMarker = /* @__PURE__ */ Facet.define();
var lineNumberConfig = /* @__PURE__ */ Facet.define({
  combine(values) {
    return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
      domEventHandlers(a, b) {
        let result = Object.assign({}, a);
        for (let event2 in b) {
          let exists = result[event2], add3 = b[event2];
          result[event2] = exists ? (view, line, event3) => exists(view, line, event3) || add3(view, line, event3) : add3;
        }
        return result;
      }
    });
  }
});
var NumberMarker = class extends GutterMarker {
  constructor(number7) {
    super();
    this.number = number7;
  }
  eq(other) {
    return this.number == other.number;
  }
  toDOM() {
    return document.createTextNode(this.number);
  }
};
function formatNumber(view, number7) {
  return view.state.facet(lineNumberConfig).formatNumber(number7, view.state);
}
var lineNumberGutter = /* @__PURE__ */ activeGutters.compute([lineNumberConfig], (state2) => ({
  class: "cm-lineNumbers",
  renderEmptyElements: false,
  markers(view) {
    return view.state.facet(lineNumberMarkers);
  },
  lineMarker(view, line, others) {
    if (others.some((m2) => m2.toDOM))
      return null;
    return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
  },
  widgetMarker: (view, widget, block2) => {
    for (let m2 of view.state.facet(lineNumberWidgetMarker)) {
      let result = m2(view, widget, block2);
      if (result)
        return result;
    }
    return null;
  },
  lineMarkerChange: (update3) => update3.startState.facet(lineNumberConfig) != update3.state.facet(lineNumberConfig),
  initialSpacer(view) {
    return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
  },
  updateSpacer(spacer, update3) {
    let max3 = formatNumber(update3.view, maxLineNumber(update3.view.state.doc.lines));
    return max3 == spacer.number ? spacer : new NumberMarker(max3);
  },
  domEventHandlers: state2.facet(lineNumberConfig).domEventHandlers
}));
function lineNumbers(config2 = {}) {
  return [
    lineNumberConfig.of(config2),
    gutters(),
    lineNumberGutter
  ];
}
function maxLineNumber(lines) {
  let last = 9;
  while (last < lines)
    last = last * 10 + 9;
  return last;
}
function matcher(decorator) {
  return ViewPlugin.define((view) => ({
    decorations: decorator.createDeco(view),
    update(u) {
      this.decorations = decorator.updateDeco(u, this.decorations);
    }
  }), {
    decorations: (v) => v.decorations
  });
}
var trailingHighlighter = /* @__PURE__ */ matcher(/* @__PURE__ */ new MatchDecorator({
  regexp: /\s+$/g,
  decoration: /* @__PURE__ */ Decoration.mark({ class: "cm-trailingSpace" }),
  boundary: /\S/
}));
function highlightTrailingWhitespace() {
  return trailingHighlighter;
}

// node_modules/@lezer/common/dist/index.js
var DefaultBufferLength = 1024;
var nextPropID = 0;
var Range2 = class {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
};
var NodeProp = class {
  /**
  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 result = match(type);
      return result === void 0 ? null : [this, result];
    };
  }
};
NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.isolate = new NodeProp({ deserialize: (value) => {
  if (value && value != "rtl" && value != "ltr" && value != "auto")
    throw new RangeError("Invalid value for isolate: " + value);
  return value || "auto";
} });
NodeProp.contextHash = new NodeProp({ perNode: true });
NodeProp.lookAhead = new NodeProp({ perNode: true });
NodeProp.mounted = new NodeProp({ perNode: true });
var MountedTree = class {
  constructor(tree, overlay, parser) {
    this.tree = tree;
    this.overlay = overlay;
    this.parser = parser;
  }
  /**
  @internal
  */
  static get(tree) {
    return tree && tree.props && tree.props[NodeProp.mounted.id];
  }
};
var noProps = /* @__PURE__ */ Object.create(null);
var NodeType = class _NodeType {
  /**
  @internal
  */
  constructor(name3, props2, id3, flags2 = 0) {
    this.name = name3;
    this.props = props2;
    this.id = id3;
    this.flags = flags2;
  }
  /**
  Define a node type.
  */
  static define(spec) {
    let props2 = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
    let flags2 = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
    let type = new _NodeType(spec.name || "", props2, spec.id, flags2);
    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");
          props2[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(prop2) {
    return this.props[prop2.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(name3) {
    if (typeof name3 == "string") {
      if (this.name == name3)
        return true;
      let group2 = this.prop(NodeProp.group);
      return group2 ? group2.indexOf(name3) > -1 : false;
    }
    return this.id == name3;
  }
  /**
  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 prop2 in map2)
      for (let name3 of prop2.split(" "))
        direct[name3] = map2[prop2];
    return (node) => {
      for (let groups2 = node.prop(NodeProp.group), i2 = -1; i2 < (groups2 ? groups2.length : 0); i2++) {
        let found = direct[i2 < 0 ? node.name : groups2[i2]];
        if (found)
          return found;
      }
    };
  }
};
NodeType.none = new NodeType(
  "",
  /* @__PURE__ */ Object.create(null),
  0,
  8
  /* NodeFlag.Anonymous */
);
var NodeSet = 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(...props2) {
    let newTypes = [];
    for (let type of this.types) {
      let newProps = null;
      for (let source3 of props2) {
        let add3 = source3(type);
        if (add3) {
          if (!newProps)
            newProps = Object.assign({}, type.props);
          newProps[add3[0].id] = add3[1];
        }
      }
      newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
    }
    return new _NodeSet(newTypes);
  }
};
var CachedNode = /* @__PURE__ */ new WeakMap();
var 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 = {}));
var Tree = class _Tree2 {
  /**
  Construct a new tree. See also [`Tree.build`](#common.Tree^build).
  */
  constructor(type, children2, positions, length, props2) {
    this.type = type;
    this.children = children2;
    this.positions = positions;
    this.length = length;
    this.props = null;
    if (props2 && props2.length) {
      this.props = /* @__PURE__ */ Object.create(null);
      for (let [prop2, value] of props2)
        this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value;
    }
  }
  /**
  @internal
  */
  toString() {
    let mounted = MountedTree.get(this);
    if (mounted && !mounted.overlay)
      return mounted.tree.toString();
    let children2 = "";
    for (let ch of this.children) {
      let str = ch.toString();
      if (str) {
        if (children2)
          children2 += ",";
        children2 += str;
      }
    }
    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(pos, side = 0, mode = 0) {
    let scope = CachedNode.get(this) || this.topNode;
    let cursor = new TreeCursor(scope);
    cursor.moveTo(pos, 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(pos, side = 0) {
    let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
    CachedNode.set(this, node);
    return node;
  }
  /**
  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(pos, side = 0) {
    let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
    CachedInnerNode.set(this, node);
    return node;
  }
  /**
  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(pos, side = 0) {
    return stackIterator(this, pos, 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 = this.length } = spec;
    let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
    for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
      let entered = false;
      if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
        if (c.firstChild())
          continue;
        entered = true;
      }
      for (; ; ) {
        if (entered && leave && (anon || !c.type.isAnonymous))
          leave(c);
        if (c.nextSibling())
          break;
        if (!c.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(prop2) {
    return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.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 result = [];
    if (this.props)
      for (let id3 in this.props)
        result.push([+id3, this.props[id3]]);
    return result;
  }
  /**
  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 _Tree2(this.type, children2, positions, length, this.propValues), config2.makeTree || ((children2, positions, length) => new _Tree2(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);
var FlatBufferCursor = class _FlatBufferCursor {
  constructor(buffer, index3) {
    this.buffer = buffer;
    this.index = index3;
  }
  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);
  }
};
var TreeBuffer = class _TreeBuffer {
  /**
  Create a tree buffer.
  */
  constructor(buffer, length, set4) {
    this.buffer = buffer;
    this.length = length;
    this.set = set4;
  }
  /**
  @internal
  */
  get type() {
    return NodeType.none;
  }
  /**
  @internal
  */
  toString() {
    let result = [];
    for (let index3 = 0; index3 < this.buffer.length; ) {
      result.push(this.childString(index3));
      index3 = this.buffer[index3 + 3];
    }
    return result.join(",");
  }
  /**
  @internal
  */
  childString(index3) {
    let id3 = this.buffer[index3], endIndex = this.buffer[index3 + 3];
    let type = this.set.types[id3], result = type.name;
    if (/\W/.test(result) && !type.isError)
      result = JSON.stringify(result);
    index3 += 4;
    if (endIndex == index3)
      return result;
    let children2 = [];
    while (index3 < endIndex) {
      children2.push(this.childString(index3));
      index3 = this.buffer[index3 + 3];
    }
    return result + "(" + children2.join(",") + ")";
  }
  /**
  @internal
  */
  findChild(startIndex, endIndex, dir, pos, side) {
    let { buffer } = this, pick = -1;
    for (let i2 = startIndex; i2 != endIndex; i2 = buffer[i2 + 3]) {
      if (checkSide(side, pos, buffer[i2 + 1], buffer[i2 + 2])) {
        pick = i2;
        if (dir > 0)
          break;
      }
    }
    return pick;
  }
  /**
  @internal
  */
  slice(startI, endI, from) {
    let b = this.buffer;
    let copy2 = new Uint16Array(endI - startI), len = 0;
    for (let i2 = startI, j = 0; i2 < endI; ) {
      copy2[j++] = b[i2++];
      copy2[j++] = b[i2++] - from;
      let to = copy2[j++] = b[i2++] - from;
      copy2[j++] = b[i2++] - startI;
      len = Math.max(len, to);
    }
    return new _TreeBuffer(copy2, len, this.set);
  }
};
function checkSide(side, pos, from, to) {
  switch (side) {
    case -2:
      return from < pos;
    case -1:
      return to >= pos && from < pos;
    case 0:
      return from < pos && to > pos;
    case 1:
      return from <= pos && to > pos;
    case 2:
      return to > pos;
    case 4:
      return true;
  }
}
function resolveNode(node, pos, side, overlays) {
  var _a2;
  while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
    let parent2 = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
    if (!parent2)
      return node;
    node = parent2;
  }
  let mode = overlays ? 0 : IterMode.IgnoreOverlays;
  if (overlays)
    for (let scan = node, parent2 = scan.parent; parent2; scan = parent2, parent2 = scan.parent) {
      if (scan instanceof TreeNode && scan.index < 0 && ((_a2 = parent2.enter(pos, side, mode)) === null || _a2 === void 0 ? void 0 : _a2.from) != scan.from)
        node = parent2;
    }
  for (; ; ) {
    let inner = node.enter(pos, side, mode);
    if (!inner)
      return node;
    node = inner;
  }
}
var BaseNode = class {
  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(pos, side = 0) {
    return resolveNode(this, pos, side, false);
  }
  resolveInner(pos, side = 0) {
    return resolveNode(this, pos, side, true);
  }
  matchContext(context2) {
    return matchNodeContext(this.parent, context2);
  }
  enterUnfinishedNodesBefore(pos) {
    let scan = this.childBefore(pos), node = this;
    while (scan) {
      let last = scan.lastChild;
      if (!last || last.to != scan.to)
        break;
      if (last.type.isError && last.from == last.to) {
        node = scan;
        scan = last.prevSibling;
      } else {
        scan = last;
      }
    }
    return node;
  }
  get node() {
    return this;
  }
  get next() {
    return this.parent;
  }
};
var TreeNode = class _TreeNode extends BaseNode {
  constructor(_tree, from, index3, _parent) {
    super();
    this._tree = _tree;
    this.from = from;
    this.index = index3;
    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, pos, side, mode = 0) {
    for (let parent2 = this; ; ) {
      for (let { children: children2, positions } = parent2._tree, e = dir > 0 ? children2.length : -1; i2 != e; i2 += dir) {
        let next2 = children2[i2], start2 = positions[i2] + parent2.from;
        if (!checkSide(side, pos, start2, start2 + next2.length))
          continue;
        if (next2 instanceof TreeBuffer) {
          if (mode & IterMode.ExcludeBuffers)
            continue;
          let index3 = next2.findChild(0, next2.buffer.length, dir, pos - start2, side);
          if (index3 > -1)
            return new BufferNode(new BufferContext(parent2, next2, i2, start2), null, index3);
        } else if (mode & IterMode.IncludeAnonymous || (!next2.type.isAnonymous || hasChild(next2))) {
          let mounted;
          if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next2)) && !mounted.overlay)
            return new _TreeNode(mounted.tree, start2, i2, parent2);
          let inner = new _TreeNode(next2, start2, i2, parent2);
          return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next2.children.length - 1 : 0, dir, pos, side);
        }
      }
      if (mode & IterMode.IncludeAnonymous || !parent2.type.isAnonymous)
        return null;
      if (parent2.index >= 0)
        i2 = parent2.index + dir;
      else
        i2 = dir < 0 ? -1 : parent2._parent._tree.children.length;
      parent2 = parent2._parent;
      if (!parent2)
        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(pos) {
    return this.nextChild(
      0,
      1,
      pos,
      2
      /* Side.After */
    );
  }
  childBefore(pos) {
    return this.nextChild(
      this._tree.children.length - 1,
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  enter(pos, side, mode = 0) {
    let mounted;
    if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
      let rPos = pos - this.from;
      for (let { from, to } of mounted.overlay) {
        if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos))
          return new _TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
      }
    }
    return this.nextChild(0, 1, pos, 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(node, type, before, after) {
  let cur2 = node.cursor(), result = [];
  if (!cur2.firstChild())
    return result;
  if (before != null)
    for (let found = false; !found; ) {
      found = cur2.type.is(before);
      if (!cur2.nextSibling())
        return result;
    }
  for (; ; ) {
    if (after != null && cur2.type.is(after))
      return result;
    if (cur2.type.is(type))
      result.push(cur2.node);
    if (!cur2.nextSibling())
      return after == null ? result : [];
  }
}
function matchNodeContext(node, context2, i2 = context2.length - 1) {
  for (let p = node; i2 >= 0; p = p.parent) {
    if (!p)
      return false;
    if (!p.type.isAnonymous) {
      if (context2[i2] && context2[i2] != p.name)
        return false;
      i2--;
    }
  }
  return true;
}
var BufferContext = class {
  constructor(parent2, buffer, index3, start2) {
    this.parent = parent2;
    this.buffer = buffer;
    this.index = index3;
    this.start = start2;
  }
};
var BufferNode = 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(context2, _parent, index3) {
    super();
    this.context = context2;
    this._parent = _parent;
    this.index = index3;
    this.type = context2.buffer.set.types[context2.buffer.buffer[index3]];
  }
  child(dir, pos, side) {
    let { buffer } = this.context;
    let index3 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
    return index3 < 0 ? null : new _BufferNode(this.context, this, index3);
  }
  get firstChild() {
    return this.child(
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  get lastChild() {
    return this.child(
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  childAfter(pos) {
    return this.child(
      1,
      pos,
      2
      /* Side.After */
    );
  }
  childBefore(pos) {
    return this.child(
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  enter(pos, side, mode = 0) {
    if (mode & IterMode.ExcludeBuffers)
      return null;
    let { buffer } = this.context;
    let index3 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
    return index3 < 0 ? null : new _BufferNode(this.context, this, index3);
  }
  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 } = this.context;
    let after = buffer.buffer[this.index + 3];
    if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
      return new _BufferNode(this.context, this._parent, after);
    return this.externalSibling(1);
  }
  get prevSibling() {
    let { buffer } = 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, buffer.findChild(
      parentStart,
      this.index,
      -1,
      0,
      4
      /* Side.DontCare */
    ));
  }
  get tree() {
    return null;
  }
  toTree() {
    let children2 = [], positions = [];
    let { buffer } = this.context;
    let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
    if (endI > startI) {
      let from = buffer.buffer[this.index + 1];
      children2.push(buffer.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 node = heads[i2];
    if (node.from > picked.from || node.to < picked.to) {
      picked = node;
      pick = i2;
    }
  }
  let next2 = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
  let newHeads = heads.slice();
  if (next2)
    newHeads[pick] = next2;
  else
    newHeads.splice(pick, 1);
  return new StackIterator(newHeads, picked);
}
var StackIterator = class {
  constructor(heads, node) {
    this.heads = heads;
    this.node = node;
  }
  get next() {
    return iterStack(this.heads);
  }
};
function stackIterator(tree, pos, side) {
  let inner = tree.resolveInner(pos, side), layers = null;
  for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
    if (scan.index < 0) {
      let parent2 = scan.parent;
      (layers || (layers = [inner])).push(parent2.resolve(pos, side));
      scan = parent2;
    } else {
      let mount2 = MountedTree.get(scan.tree);
      if (mount2 && mount2.overlay && mount2.overlay[0].from <= pos && mount2.overlay[mount2.overlay.length - 1].to >= pos) {
        let root68 = new TreeNode(mount2.tree, mount2.overlay[0].from + scan.from, -1, scan);
        (layers || (layers = [inner])).push(resolveNode(root68, pos, side, false));
      }
    }
  }
  return layers ? iterStack(layers) : inner;
}
var TreeCursor = class {
  /**
  Shorthand for `.type.name`.
  */
  get name() {
    return this.type.name;
  }
  /**
  @internal
  */
  constructor(node, mode = 0) {
    this.mode = mode;
    this.buffer = null;
    this.stack = [];
    this.index = 0;
    this.bufferNode = null;
    if (node instanceof TreeNode) {
      this.yieldNode(node);
    } else {
      this._tree = node.context.parent;
      this.buffer = node.context;
      for (let n = node._parent; n; n = n._parent)
        this.stack.unshift(n.index);
      this.bufferNode = node;
      this.yieldBuf(node.index);
    }
  }
  yieldNode(node) {
    if (!node)
      return false;
    this._tree = node;
    this.type = node.type;
    this.from = node.from;
    this.to = node.to;
    return true;
  }
  yieldBuf(index3, type) {
    this.index = index3;
    let { start: start2, buffer } = this.buffer;
    this.type = type || buffer.set.types[buffer.buffer[index3]];
    this.from = start2 + buffer.buffer[index3 + 1];
    this.to = start2 + buffer.buffer[index3 + 2];
    return true;
  }
  /**
  @internal
  */
  yield(node) {
    if (!node)
      return false;
    if (node instanceof TreeNode) {
      this.buffer = null;
      return this.yieldNode(node);
    }
    this.buffer = node.context;
    return this.yieldBuf(node.index, node.type);
  }
  /**
  @internal
  */
  toString() {
    return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
  }
  /**
  @internal
  */
  enterChild(dir, pos, side) {
    if (!this.buffer)
      return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
    let { buffer } = this.buffer;
    let index3 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
    if (index3 < 0)
      return false;
    this.stack.push(this.index);
    return this.yieldBuf(index3);
  }
  /**
  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(pos) {
    return this.enterChild(
      1,
      pos,
      2
      /* Side.After */
    );
  }
  /**
  Move to the last child that starts before `pos`.
  */
  childBefore(pos) {
    return this.enterChild(
      -1,
      pos,
      -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(pos, side, mode = this.mode) {
    if (!this.buffer)
      return this.yield(this._tree.enter(pos, side, mode));
    return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, 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 parent2 = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
    this.buffer = null;
    return this.yieldNode(parent2);
  }
  /**
  @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 } = 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(buffer.findChild(
          parentStart,
          this.index,
          -1,
          0,
          4
          /* Side.DontCare */
        ));
    } else {
      let after = buffer.buffer[this.index + 3];
      if (after < (d < 0 ? buffer.buffer.length : buffer.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 index3, parent2, { buffer } = this;
    if (buffer) {
      if (dir > 0) {
        if (this.index < buffer.buffer.buffer.length)
          return false;
      } else {
        for (let i2 = 0; i2 < this.index; i2++)
          if (buffer.buffer.buffer[i2 + 3] < this.index)
            return false;
      }
      ({ index: index3, parent: parent2 } = buffer);
    } else {
      ({ index: index3, _parent: parent2 } = this._tree);
    }
    for (; parent2; { index: index3, _parent: parent2 } = parent2) {
      if (index3 > -1)
        for (let i2 = index3 + dir, e = dir < 0 ? -1 : parent2._tree.children.length; i2 != e; i2 += dir) {
          let child2 = parent2._tree.children[i2];
          if (this.mode & IterMode.IncludeAnonymous || child2 instanceof TreeBuffer || !child2.type.isAnonymous || hasChild(child2))
            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(pos, side = 0) {
    while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
      if (!this.parent())
        break;
    while (this.enterChild(1, pos, 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, result = null, depth = 0;
    if (cache && cache.context == this.buffer) {
      scan: for (let index3 = this.index, d = this.stack.length; d >= 0; ) {
        for (let c = cache; c; c = c._parent)
          if (c.index == index3) {
            if (index3 == this.index)
              return c;
            result = c;
            depth = d + 1;
            break scan;
          }
        index3 = this.stack[--d];
      }
    }
    for (let i2 = depth; i2 < this.stack.length; i2++)
      result = new BufferNode(this.buffer, result, this.stack[i2]);
    return this.bufferNode = new BufferNode(this.buffer, result, 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(context2) {
    if (!this.buffer)
      return matchNodeContext(this.node.parent, context2);
    let { buffer } = this.buffer, { types: types2 } = buffer.set;
    for (let i2 = context2.length - 1, d = this.stack.length - 1; i2 >= 0; d--) {
      if (d < 0)
        return matchNodeContext(this._tree, context2, i2);
      let type = types2[buffer.buffer[this.stack[d]]];
      if (!type.isAnonymous) {
        if (context2[i2] && context2[i2] != type.name)
          return false;
        i2--;
      }
    }
    return true;
  }
};
function hasChild(tree) {
  return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
}
function buildTree(data) {
  var _a2;
  let { buffer, nodeSet: nodeSet2, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet2.types.length } = data;
  let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
  let types2 = nodeSet2.types;
  let contextHash = 0, lookAhead = 0;
  function takeNode(parentStart, minPos, children3, positions2, inRepeat, depth) {
    let { id: id3, start: start2, end, size } = cursor;
    let lookAheadAtStart = lookAhead, contextAtStart = contextHash;
    while (size < 0) {
      cursor.next();
      if (size == -1) {
        let node2 = reused[id3];
        children3.push(node2);
        positions2.push(start2 - parentStart);
        return;
      } else if (size == -3) {
        contextHash = id3;
        return;
      } else if (size == -4) {
        lookAhead = id3;
        return;
      } else {
        throw new RangeError(`Unrecognized record size: ${size}`);
      }
    }
    let type = types2[id3], node, buffer2;
    let startPos = start2 - parentStart;
    if (end - start2 <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
      let data2 = new Uint16Array(buffer2.size - buffer2.skip);
      let endPos = cursor.pos - buffer2.size, index3 = data2.length;
      while (cursor.pos > endPos)
        index3 = copyToBuffer(buffer2.start, data2, index3);
      node = new TreeBuffer(data2, end - buffer2.start, nodeSet2);
      startPos = buffer2.start - parentStart;
    } else {
      let endPos = cursor.pos - size;
      cursor.next();
      let localChildren = [], localPositions = [];
      let localInRepeat = id3 >= minRepeatType ? id3 : -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, start2, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
            lastGroup = localChildren.length;
            lastEnd = cursor.end;
          }
          cursor.next();
        } else if (depth > 2500) {
          takeFlatNode(start2, endPos, localChildren, localPositions);
        } else {
          takeNode(start2, endPos, localChildren, localPositions, localInRepeat, depth + 1);
        }
      }
      if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
        makeRepeatLeaf(localChildren, localPositions, start2, lastGroup, start2, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
      localChildren.reverse();
      localPositions.reverse();
      if (localInRepeat > -1 && lastGroup > 0) {
        let make = makeBalanced(type, contextAtStart);
        node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start2, make, make);
      } else {
        node = makeTree(type, localChildren, localPositions, end - start2, lookAheadAtStart - end, contextAtStart);
      }
    }
    children3.push(node);
    positions2.push(startPos);
  }
  function takeFlatNode(parentStart, minPos, children3, positions2) {
    let nodes = [];
    let nodeCount = 0, stopAt = -1;
    while (cursor.pos > minPos) {
      let { id: id3, start: start2, end, size } = cursor;
      if (size > 4) {
        cursor.next();
      } else if (stopAt > -1 && start2 < stopAt) {
        break;
      } else {
        if (stopAt < 0)
          stopAt = end - maxBufferLength;
        nodes.push(id3, start2, end);
        nodeCount++;
        cursor.next();
      }
    }
    if (nodeCount) {
      let buffer2 = new Uint16Array(nodeCount * 4);
      let start2 = nodes[nodes.length - 2];
      for (let i2 = nodes.length - 3, j = 0; i2 >= 0; i2 -= 3) {
        buffer2[j++] = nodes[i2];
        buffer2[j++] = nodes[i2 + 1] - start2;
        buffer2[j++] = nodes[i2 + 2] - start2;
        buffer2[j++] = j;
      }
      children3.push(new TreeBuffer(buffer2, nodes[2] - start2, nodeSet2));
      positions2.push(start2 - 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, to, 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, to - from, lookAhead2 - to, contextHash2));
    positions2.push(from - base2);
  }
  function makeTree(type, children3, positions2, length2, lookAhead2, contextHash2, props2) {
    if (contextHash2) {
      let pair = [NodeProp.contextHash, contextHash2];
      props2 = props2 ? [pair].concat(props2) : [pair];
    }
    if (lookAhead2 > 25) {
      let pair = [NodeProp.lookAhead, lookAhead2];
      props2 = props2 ? [pair].concat(props2) : [pair];
    }
    return new Tree(type, children3, positions2, length2, props2);
  }
  function findBufferSize(maxSize, inRepeat) {
    let fork = cursor.fork();
    let size = 0, start2 = 0, skip2 = 0, minStart = fork.end - maxBufferLength;
    let result = { 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) {
        result.size = size;
        result.start = start2;
        result.skip = skip2;
        skip2 += 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 nodeStart2 = 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();
      }
      start2 = nodeStart2;
      size += nodeSize2;
      skip2 += localSkipped;
    }
    if (inRepeat < 0 || size == maxSize) {
      result.size = size;
      result.start = start2;
      result.skip = skip2;
    }
    return result.size > 4 ? result : void 0;
  }
  function copyToBuffer(bufferStart, buffer2, index3) {
    let { id: id3, start: start2, end, size } = cursor;
    cursor.next();
    if (size >= 0 && id3 < minRepeatType) {
      let startIndex = index3;
      if (size > 4) {
        let endPos = cursor.pos - (size - 4);
        while (cursor.pos > endPos)
          index3 = copyToBuffer(bufferStart, buffer2, index3);
      }
      buffer2[--index3] = startIndex;
      buffer2[--index3] = end - bufferStart;
      buffer2[--index3] = start2 - bufferStart;
      buffer2[--index3] = id3;
    } else if (size == -3) {
      contextHash = id3;
    } else if (size == -4) {
      lookAhead = id3;
    }
    return index3;
  }
  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);
}
var nodeSizeCache = /* @__PURE__ */ new WeakMap();
function nodeSize(balanceType, node) {
  if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
    return 1;
  let size = nodeSizeCache.get(node);
  if (size == null) {
    size = 1;
    for (let child2 of node.children) {
      if (child2.type != balanceType || !(child2 instanceof Tree)) {
        size = 1;
        break;
      }
      size += nodeSize(balanceType, child2);
    }
    nodeSizeCache.set(node, size);
  }
  return size;
}
function balanceRange(balanceType, children2, positions, from, to, start2, length, mkTop, mkTree) {
  let total = 0;
  for (let i2 = from; i2 < to; i2++)
    total += nodeSize(balanceType, children2[i2]);
  let maxChild = Math.ceil(
    total * 1.5 / 8
    /* Balance.BranchFactor */
  );
  let localChildren = [], localPositions = [];
  function divide(children3, positions2, from2, to2, offset) {
    for (let i2 = from2; i2 < to2; ) {
      let groupFrom = i2, groupStart = positions2[i2], groupSize = nodeSize(balanceType, children3[i2]);
      i2++;
      for (; i2 < to2; 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 - start2);
    }
  }
  divide(children2, positions, from, to, 0);
  return (mkTop || mkTree)(localChildren, localPositions, length);
}
var TreeFragment = 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, to, tree, offset, openStart = false, openEnd = false) {
    this.from = from;
    this.to = to;
    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 result = [new _TreeFragment(0, tree.length, tree, 0, false, partial)];
    for (let f of fragments)
      if (f.to > tree.length)
        result.push(f);
    return result;
  }
  /**
  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 result = [];
    let fI = 1, nextF = fragments.length ? fragments[0] : null;
    for (let cI = 0, pos = 0, off = 0; ; cI++) {
      let nextC = cI < changes.length ? changes[cI] : null;
      let nextPos = nextC ? nextC.fromA : 1e9;
      if (nextPos - pos >= minGap)
        while (nextF && nextF.from < nextPos) {
          let cut = nextF;
          if (pos >= cut.from || nextPos <= cut.to || off) {
            let fFrom = Math.max(cut.from, pos) - 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)
            result.push(cut);
          if (nextF.to > nextPos)
            break;
          nextF = fI < fragments.length ? fragments[fI++] : null;
        }
      if (!nextC)
        break;
      pos = nextC.toA;
      off = nextC.toA - nextC.toB;
    }
    return result;
  }
};
var Parser = class {
  /**
  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(input, fragments, ranges) {
    if (typeof input == "string")
      input = new StringInput(input);
    ranges = !ranges ? [new Range2(0, input.length)] : ranges.length ? ranges.map((r2) => new Range2(r2.from, r2.to)) : [new Range2(0, 0)];
    return this.createParse(input, fragments || [], ranges);
  }
  /**
  Run a full parse, returning the resulting tree.
  */
  parse(input, fragments, ranges) {
    let parse = this.startParse(input, fragments, ranges);
    for (; ; ) {
      let done = parse.advance();
      if (done)
        return done;
    }
  }
};
var StringInput = class {
  constructor(string4) {
    this.string = string4;
  }
  get length() {
    return this.string.length;
  }
  chunk(from) {
    return this.string.slice(from);
  }
  get lineChunks() {
    return false;
  }
  read(from, to) {
    return this.string.slice(from, to);
  }
};
var stoppedInner = new NodeProp({ perNode: true });

// node_modules/@lezer/highlight/dist/index.js
var nextTagID = 0;
var Tag = class _Tag {
  /**
  @internal
  */
  constructor(name3, set4, base2, modified) {
    this.name = name3;
    this.set = set4;
    this.base = base2;
    this.modified = modified;
    this.id = nextTagID++;
  }
  toString() {
    let { name: name3 } = this;
    for (let mod of this.modified)
      if (mod.name)
        name3 = `${mod.name}(${name3})`;
    return name3;
  }
  static define(nameOrParent, parent2) {
    let name3 = typeof nameOrParent == "string" ? nameOrParent : "?";
    if (nameOrParent instanceof _Tag)
      parent2 = nameOrParent;
    if (parent2 === null || parent2 === void 0 ? void 0 : parent2.base)
      throw new Error("Can not derive from a modified tag");
    let tag = new _Tag(name3, [], null, []);
    tag.set.push(tag);
    if (parent2)
      for (let t4 of parent2.set)
        tag.set.push(t4);
    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(name3) {
    let mod = new Modifier(name3);
    return (tag) => {
      if (tag.modified.indexOf(mod) > -1)
        return tag;
      return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
    };
  }
};
var nextModifierID = 0;
var Modifier = class _Modifier {
  constructor(name3) {
    this.name = name3;
    this.instances = [];
    this.id = nextModifierID++;
  }
  static get(base2, mods) {
    if (!mods.length)
      return base2;
    let exists = mods[0].instances.find((t4) => t4.base == base2 && sameArray2(mods, t4.modified));
    if (exists)
      return exists;
    let set4 = [], tag = new Tag(base2.name, set4, base2, mods);
    for (let m2 of mods)
      m2.instances.push(tag);
    let configs = powerSet(mods);
    for (let parent2 of base2.set)
      if (!parent2.modified.length)
        for (let config2 of configs)
          set4.push(_Modifier.get(parent2, config2));
    return tag;
  }
};
function sameArray2(a, b) {
  return a.length == b.length && a.every((x2, i2) => x2 == b[i2]);
}
function powerSet(array3) {
  let sets = [[]];
  for (let i2 = 0; i2 < array3.length; i2++) {
    for (let j = 0, e = sets.length; j < e; j++) {
      sets.push(sets[j].concat(array3[i2]));
    }
  }
  return sets.sort((a, b) => b.length - a.length);
}
function styleTags(spec) {
  let byName = /* @__PURE__ */ Object.create(null);
  for (let prop2 in spec) {
    let tags3 = spec[prop2];
    if (!Array.isArray(tags3))
      tags3 = [tags3];
    for (let part of prop2.split(" "))
      if (part) {
        let pieces = [], mode = 2, rest = part;
        for (let pos = 0; ; ) {
          if (rest == "..." && pos > 0 && pos + 3 == part.length) {
            mode = 1;
            break;
          }
          let m2 = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
          if (!m2)
            throw new RangeError("Invalid path: " + part);
          pieces.push(m2[0] == "*" ? "" : m2[0][0] == '"' ? JSON.parse(m2[0]) : m2[0]);
          pos += m2[0].length;
          if (pos == part.length)
            break;
          let next2 = part[pos++];
          if (pos == part.length && next2 == "!") {
            mode = 0;
            break;
          }
          if (next2 != "/")
            throw new RangeError("Invalid path: " + part);
          rest = part.slice(pos);
        }
        let last = pieces.length - 1, inner = pieces[last];
        if (!inner)
          throw new RangeError("Invalid path: " + part);
        let rule = new Rule(tags3, mode, last > 0 ? pieces.slice(0, last) : null);
        byName[inner] = rule.sort(byName[inner]);
      }
  }
  return ruleNodeProp.add(byName);
}
var ruleNodeProp = new NodeProp();
var Rule = class {
  constructor(tags3, mode, context2, next2) {
    this.tags = tags3;
    this.mode = mode;
    this.context = context2;
    this.next = next2;
  }
  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(tags3, options4) {
  let map2 = /* @__PURE__ */ Object.create(null);
  for (let style of tags3) {
    if (!Array.isArray(style.tag))
      map2[style.tag.id] = style.class;
    else
      for (let tag of style.tag)
        map2[tag.id] = style.class;
  }
  let { scope, all = null } = options4 || {};
  return {
    style: (tags4) => {
      let cls = all;
      for (let tag of tags4) {
        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, tags3) {
  let result = null;
  for (let highlighter of highlighters) {
    let value = highlighter.style(tags3);
    if (value)
      result = result ? result + " " + value : value;
  }
  return result;
}
function highlightTree(tree, highlighter, putStyle, from = 0, to = tree.length) {
  let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
  builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
  builder.flush(to);
}
var HighlightBuilder = class {
  constructor(at, highlighters, span) {
    this.at = at;
    this.highlighters = highlighters;
    this.span = span;
    this.class = "";
  }
  startSpan(at, cls) {
    if (cls != this.class) {
      this.flush(at);
      if (at > this.at)
        this.at = at;
      this.class = cls;
    }
  }
  flush(to) {
    if (to > this.at && this.class)
      this.span(this.at, to, this.class);
  }
  highlightRange(cursor, from, to, inheritedClass, highlighters) {
    let { type, from: start2, to: end } = cursor;
    if (start2 >= to || 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, start2), 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 + start2, 1);
      let innerHighlighters = this.highlighters.filter((h) => !h.scope || h.scope(mounted.tree.type));
      let hasChild2 = cursor.firstChild();
      for (let i2 = 0, pos = start2; ; i2++) {
        let next2 = i2 < mounted.overlay.length ? mounted.overlay[i2] : null;
        let nextPos = next2 ? next2.from + start2 : end;
        let rangeFrom2 = Math.max(from, pos), rangeTo2 = Math.min(to, 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 (!next2 || nextPos > to)
          break;
        pos = next2.to + start2;
        if (pos > from) {
          this.highlightRange(inner.cursor(), Math.max(from, next2.from + start2), Math.min(to, pos), "", innerHighlighters);
          this.startSpan(Math.min(to, pos), cls);
        }
      }
      if (hasChild2)
        cursor.parent();
    } else if (cursor.firstChild()) {
      if (mounted)
        inheritedClass = "";
      do {
        if (cursor.to <= from)
          continue;
        if (cursor.from >= to)
          break;
        this.highlightRange(cursor, from, to, inheritedClass, highlighters);
        this.startSpan(Math.min(to, cursor.to), cls);
      } while (cursor.nextSibling());
      cursor.parent();
    }
  }
};
function getStyleTags(node) {
  let rule = node.type.prop(ruleNodeProp);
  while (rule && rule.context && !node.matchContext(rule.context))
    rule = rule.next;
  return rule || null;
}
var t = Tag.define;
var comment2 = t();
var name2 = t();
var typeName = t(name2);
var propertyName = t(name2);
var literal = t();
var string2 = t(literal);
var number3 = t(literal);
var content = t();
var heading = t(content);
var keyword = t();
var operator = t();
var punctuation = t();
var bracket = t(punctuation);
var meta = t();
var tags2 = {
  /**
  A comment.
  */
  comment: comment2,
  /**
  A line [comment](#highlight.tags.comment).
  */
  lineComment: t(comment2),
  /**
  A block [comment](#highlight.tags.comment).
  */
  blockComment: t(comment2),
  /**
  A documentation [comment](#highlight.tags.comment).
  */
  docComment: t(comment2),
  /**
  Any kind of identifier.
  */
  name: name2,
  /**
  The [name](#highlight.tags.name) of a variable.
  */
  variableName: t(name2),
  /**
  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(name2),
  /**
  A label [name](#highlight.tags.name).
  */
  labelName: t(name2),
  /**
  A namespace [name](#highlight.tags.name).
  */
  namespace: t(name2),
  /**
  The [name](#highlight.tags.name) of a macro.
  */
  macroName: t(name2),
  /**
  A literal value.
  */
  literal,
  /**
  A string [literal](#highlight.tags.literal).
  */
  string: string2,
  /**
  A documentation [string](#highlight.tags.string).
  */
  docString: t(string2),
  /**
  A character literal (subtag of [string](#highlight.tags.string)).
  */
  character: t(string2),
  /**
  An attribute value (subtag of [string](#highlight.tags.string)).
  */
  attributeValue: t(string2),
  /**
  A number [literal](#highlight.tags.literal).
  */
  number: number3,
  /**
  An integer [number](#highlight.tags.number) literal.
  */
  integer: t(number3),
  /**
  A floating-point [number](#highlight.tags.number) literal.
  */
  float: t(number3),
  /**
  A boolean [literal](#highlight.tags.literal).
  */
  bool: t(literal),
  /**
  Regular expression [literal](#highlight.tags.literal).
  */
  regexp: t(literal),
  /**
  An escape [literal](#highlight.tags.literal), for example a
  backslash escape in a string.
  */
  escape: t(literal),
  /**
  A color [literal](#highlight.tags.literal).
  */
  color: t(literal),
  /**
  A URL [literal](#highlight.tags.literal).
  */
  url: t(literal),
  /**
  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](#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),
  /**
  [Content](#highlight.tags.content) that represents a list.
  */
  list: t(content),
  /**
  [Content](#highlight.tags.content) that represents a quote.
  */
  quote: t(content),
  /**
  [Content](#highlight.tags.content) that is emphasized.
  */
  emphasis: t(content),
  /**
  [Content](#highlight.tags.content) that is styled strong.
  */
  strong: t(content),
  /**
  [Content](#highlight.tags.content) that is part of a link.
  */
  link: t(content),
  /**
  [Content](#highlight.tags.content) that is styled as code or
  monospace.
  */
  monospace: t(content),
  /**
  [Content](#highlight.tags.content) that has a strike-through
  style.
  */
  strikethrough: t(content),
  /**
  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 name3 in tags2) {
  let val = tags2[name3];
  if (val instanceof Tag)
    val.name = name3;
}
var classHighlighter = tagHighlighter([
  { tag: tags2.link, class: "tok-link" },
  { tag: tags2.heading, class: "tok-heading" },
  { tag: tags2.emphasis, class: "tok-emphasis" },
  { tag: tags2.strong, class: "tok-strong" },
  { tag: tags2.keyword, class: "tok-keyword" },
  { tag: tags2.atom, class: "tok-atom" },
  { tag: tags2.bool, class: "tok-bool" },
  { tag: tags2.url, class: "tok-url" },
  { tag: tags2.labelName, class: "tok-labelName" },
  { tag: tags2.inserted, class: "tok-inserted" },
  { tag: tags2.deleted, class: "tok-deleted" },
  { tag: tags2.literal, class: "tok-literal" },
  { tag: tags2.string, class: "tok-string" },
  { tag: tags2.number, class: "tok-number" },
  { tag: [tags2.regexp, tags2.escape, tags2.special(tags2.string)], class: "tok-string2" },
  { tag: tags2.variableName, class: "tok-variableName" },
  { tag: tags2.local(tags2.variableName), class: "tok-variableName tok-local" },
  { tag: tags2.definition(tags2.variableName), class: "tok-variableName tok-definition" },
  { tag: tags2.special(tags2.variableName), class: "tok-variableName2" },
  { tag: tags2.definition(tags2.propertyName), class: "tok-propertyName tok-definition" },
  { tag: tags2.typeName, class: "tok-typeName" },
  { tag: tags2.namespace, class: "tok-namespace" },
  { tag: tags2.className, class: "tok-className" },
  { tag: tags2.macroName, class: "tok-macroName" },
  { tag: tags2.propertyName, class: "tok-propertyName" },
  { tag: tags2.operator, class: "tok-operator" },
  { tag: tags2.comment, class: "tok-comment" },
  { tag: tags2.meta, class: "tok-meta" },
  { tag: tags2.invalid, class: "tok-invalid" },
  { tag: tags2.punctuation, class: "tok-punctuation" }
]);

// node_modules/@codemirror/language/dist/index.js
var _a;
var languageDataProp = /* @__PURE__ */ new NodeProp();
function defineLanguageFacet(baseData) {
  return Facet.define({
    combine: baseData ? (values) => values.concat(baseData) : void 0
  });
}
var sublanguageProp = /* @__PURE__ */ new NodeProp();
var Language = class {
  /**
  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, parser, extraExtensions = [], name3 = "") {
    this.data = data;
    this.name = name3;
    if (!EditorState.prototype.hasOwnProperty("tree"))
      Object.defineProperty(EditorState.prototype, "tree", { get() {
        return syntaxTree(this);
      } });
    this.parser = parser;
    this.extension = [
      language.of(this),
      EditorState.languageData.of((state2, pos, side) => {
        let top3 = topNodeAt(state2, pos, side), data2 = top3.type.prop(languageDataProp);
        if (!data2)
          return [];
        let base2 = state2.facet(data2), sub = top3.type.prop(sublanguageProp);
        if (sub) {
          let innerNode = top3.resolve(pos - top3.from, side);
          for (let sublang of sub)
            if (sublang.test(innerNode, state2)) {
              let data3 = state2.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(state2, pos, side = -1) {
    return topNodeAt(state2, pos, 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(state2) {
    let lang = state2.facet(language);
    if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
      return [{ from: 0, to: state2.doc.length }];
    if (!lang || !lang.allowsNesting)
      return [];
    let result = [];
    let explore = (tree, from) => {
      if (tree.prop(languageDataProp) == this.data) {
        result.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)
              result.push({ from: r2.from + from, to: r2.to + from });
          else
            result.push({ from, to: from + tree.length });
          return;
        } else if (mount2.overlay) {
          let size = result.length;
          explore(mount2.tree, mount2.overlay[0].from + from);
          if (result.length > size)
            return;
        }
      }
      for (let i2 = 0; i2 < tree.children.length; i2++) {
        let ch = tree.children[i2];
        if (ch instanceof Tree)
          explore(ch, tree.positions[i2] + from);
      }
    };
    explore(syntaxTree(state2), 0);
    return result;
  }
  /**
  Indicates whether this language allows nested languages. The
  default implementation returns true.
  */
  get allowsNesting() {
    return true;
  }
};
Language.setState = /* @__PURE__ */ StateEffect.define();
function topNodeAt(state2, pos, side) {
  let topLang = state2.facet(language), tree = syntaxTree(state2).topNode;
  if (!topLang || topLang.allowsNesting) {
    for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))
      if (node.type.isTop)
        tree = node;
  }
  return tree;
}
function syntaxTree(state2) {
  let field = state2.field(Language.state, false);
  return field ? field.tree : Tree.empty;
}
var DocInput = class {
  /**
  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(pos) {
    this.string = this.cursor.next(pos - this.cursorPos).value;
    this.cursorPos = pos + this.string.length;
    return this.cursorPos - this.string.length;
  }
  chunk(pos) {
    this.syncTo(pos);
    return this.string;
  }
  get lineChunks() {
    return true;
  }
  read(from, to) {
    let stringStart = this.cursorPos - this.string.length;
    if (from < stringStart || to >= this.cursorPos)
      return this.doc.sliceString(from, to);
    else
      return this.string.slice(from - stringStart, to - stringStart);
  }
};
var currentContext = null;
var ParseContext = class _ParseContext {
  constructor(parser, state2, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) {
    this.parser = parser;
    this.state = state2;
    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(parser, state2, viewport) {
    return new _ParseContext(parser, state2, [], 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 pos, tree;
    if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
      if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
        this.parse.stopAt(pos);
      this.withContext(() => {
        while (!(tree = this.parse.advance())) {
        }
      });
      this.treeLen = pos;
      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), to = changes.mapPos(r2.to, -1);
          if (from < to)
            skipped.push({ from, to });
        }
      }
    }
    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 } = this.skipped[i2];
      if (from < viewport.to && to > viewport.from) {
        this.fragments = cutFragments(this.fragments, from, to);
        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, to) {
    this.skipped.push({ from, to });
  }
  /**
  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(input, fragments, ranges) {
        let from = ranges[0].from, to = ranges[ranges.length - 1].to;
        let parser = {
          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 = to;
            return new Tree(NodeType.none, [], [], to - from);
          },
          stoppedAt: null,
          stopAt() {
          }
        };
        return parser;
      }
    }();
  }
  /**
  @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, to) {
  return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
}
var LanguageState = class _LanguageState {
  constructor(context2) {
    this.context = context2;
    this.tree = context2.tree;
  }
  apply(tr) {
    if (!tr.docChanged && this.tree == this.context.tree)
      return this;
    let newCx = this.context.changes(tr.changes, tr.state);
    let upto = this.context.treeLen == tr.startState.doc.length ? void 0 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
    if (!newCx.work(20, upto))
      newCx.takeTree();
    return new _LanguageState(newCx);
  }
  static init(state2) {
    let vpTo = Math.min(3e3, state2.doc.length);
    let parseState = ParseContext.create(state2.facet(language).parser, state2, { from: 0, to: vpTo });
    if (!parseState.work(20, vpTo))
      parseState.takeTree();
    return new _LanguageState(parseState);
  }
};
Language.state = /* @__PURE__ */ StateField.define({
  create: LanguageState.init,
  update(value, tr) {
    for (let e of tr.effects)
      if (e.is(Language.setState))
        return e.value;
    if (tr.startState.facet(language) != tr.state.facet(language))
      return LanguageState.init(tr.state);
    return value.apply(tr);
  }
});
var 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);
  };
var isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) ? () => navigator.scheduling.isInputPending() : null;
var 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(update3) {
    let cx = this.view.state.field(Language.state).context;
    if (cx.updateViewport(update3.view.viewport) || this.view.viewport.to > cx.treeLen)
      this.scheduleWork();
    if (update3.docChanged || update3.selectionSet) {
      if (this.view.hasFocus)
        this.chunkBudget += 50;
      this.scheduleWork();
    }
    this.checkAsyncSchedule(cx);
  }
  scheduleWork() {
    if (this.working)
      return;
    let { state: state2 } = this.view, field = state2.field(Language.state);
    if (field.tree != field.context.tree || !field.context.isDone(state2.doc.length))
      this.working = requestIdle(this.work);
  }
  work(deadline) {
    this.working = null;
    let now = Date.now();
    if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) {
      this.chunkEnd = now + 3e4;
      this.chunkBudget = 3e3;
    }
    if (this.chunkBudget <= 0)
      return;
    let { state: state2, viewport: { to: vpTo } } = this.view, field = state2.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 && state2.doc.length > vpTo + 1e3;
    let done = field.context.work(() => {
      return isInputPending && isInputPending() || Date.now() > endTime;
    }, vpTo + (viewportFirst ? 0 : 1e5));
    this.chunkBudget -= Date.now() - now;
    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((err3) => logException(this.view.state, err3)).then(() => this.workScheduled--);
      cx.scheduleOn = null;
    }
  }
  destroy() {
    if (this.working)
      this.working();
  }
  isWorking() {
    return !!(this.working || this.workScheduled > 0);
  }
}, {
  eventHandlers: { focus() {
    this.scheduleWork();
  } }
});
var language = /* @__PURE__ */ Facet.define({
  combine(languages) {
    return languages.length ? languages[0] : null;
  },
  enables: (language2) => [
    Language.state,
    parseWorker,
    EditorView.contentAttributes.compute([language2], (state2) => {
      let lang = state2.facet(language2);
      return lang && lang.name ? { "data-language": lang.name } : {};
    })
  ]
});
var LanguageSupport = class {
  /**
  Create a language support object.
  */
  constructor(language2, support = []) {
    this.language = language2;
    this.support = support;
    this.extension = [language2, support];
  }
};
var indentService = /* @__PURE__ */ Facet.define();
var indentUnit = /* @__PURE__ */ Facet.define({
  combine: (values) => {
    if (!values.length)
      return "  ";
    let unit2 = values[0];
    if (!unit2 || /\S/.test(unit2) || Array.from(unit2).some((e) => e != unit2[0]))
      throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
    return unit2;
  }
});
function getIndentUnit(state2) {
  let unit2 = state2.facet(indentUnit);
  return unit2.charCodeAt(0) == 9 ? state2.tabSize * unit2.length : unit2.length;
}
function indentString(state2, cols) {
  let result = "", ts = state2.tabSize, ch = state2.facet(indentUnit)[0];
  if (ch == "	") {
    while (cols >= ts) {
      result += "	";
      cols -= ts;
    }
    ch = " ";
  }
  for (let i2 = 0; i2 < cols; i2++)
    result += ch;
  return result;
}
function getIndentation(context2, pos) {
  if (context2 instanceof EditorState)
    context2 = new IndentContext(context2);
  for (let service of context2.state.facet(indentService)) {
    let result = service(context2, pos);
    if (result !== void 0)
      return result;
  }
  let tree = syntaxTree(context2.state);
  return tree.length >= pos ? syntaxIndentation(context2, tree, pos) : null;
}
var IndentContext = class {
  /**
  Create an indent context.
  */
  constructor(state2, options4 = {}) {
    this.state = state2;
    this.options = options4;
    this.unit = getIndentUnit(state2);
  }
  /**
  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(pos, bias = 1) {
    let line = this.state.doc.lineAt(pos);
    let { simulateBreak, simulateDoubleBreak } = this.options;
    if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
      if (simulateDoubleBreak && simulateBreak == pos)
        return { text: "", from: pos };
      else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
        return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
      else
        return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
    }
    return line;
  }
  /**
  Get the text directly after `pos`, either the entire line
  or the next 100 characters, whichever is shorter.
  */
  textAfterPos(pos, bias = 1) {
    if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
      return "";
    let { text: text2, from } = this.lineAt(pos, bias);
    return text2.slice(pos - from, Math.min(text2.length, pos + 100 - from));
  }
  /**
  Find the column for the given position.
  */
  column(pos, bias = 1) {
    let { text: text2, from } = this.lineAt(pos, bias);
    let result = this.countColumn(text2, pos - from);
    let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
    if (override > -1)
      result += override - this.countColumn(text2, text2.search(/\S|$/));
    return result;
  }
  /**
  Find the column position (taking tabs into account) of the given
  position in the given string.
  */
  countColumn(line, pos = line.length) {
    return countColumn(line, this.state.tabSize, pos);
  }
  /**
  Find the indentation column of the line at the given point.
  */
  lineIndent(pos, bias = 1) {
    let { text: text2, from } = this.lineAt(pos, 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;
  }
};
var indentNodeProp = /* @__PURE__ */ new NodeProp();
function syntaxIndentation(cx, ast, pos) {
  let stack2 = ast.resolveStack(pos);
  let inner = ast.resolveInner(pos, -1).resolve(pos, 0).enterUnfinishedNodesBefore(pos);
  if (inner != stack2.node) {
    let add3 = [];
    for (let cur2 = inner; cur2 && !(cur2.from == stack2.node.from && cur2.type == stack2.node.type); cur2 = cur2.parent)
      add3.push(cur2);
    for (let i2 = add3.length - 1; i2 >= 0; i2--)
      stack2 = { node: add3[i2], next: stack2 };
  }
  return indentFor(stack2, cx, pos);
}
function indentFor(stack2, cx, pos) {
  for (let cur2 = stack2; cur2; cur2 = cur2.next) {
    let strategy = indentStrategy(cur2.node);
    if (strategy)
      return strategy(TreeIndentContext.create(cx, pos, 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 first = tree.firstChild, close;
  if (first && (close = first.type.prop(NodeProp.closedBy))) {
    let last = tree.lastChild, closed = last && close.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;
}
var TreeIndentContext = class _TreeIndentContext extends IndentContext {
  constructor(base2, pos, context2) {
    super(base2.state, base2.options);
    this.base = base2;
    this.pos = pos;
    this.context = context2;
  }
  /**
  The syntax tree node to which the indentation strategy
  applies.
  */
  get node() {
    return this.context.node;
  }
  /**
  @internal
  */
  static create(base2, pos, context2) {
    return new _TreeIndentContext(base2, pos, context2);
  }
  /**
  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(node) {
    let line = this.state.doc.lineAt(node.from);
    for (; ; ) {
      let atBreak = node.resolve(line.from);
      while (atBreak.parent && atBreak.parent.from == atBreak.from)
        atBreak = atBreak.parent;
      if (isParent(atBreak, node))
        break;
      line = this.state.doc.lineAt(atBreak.from);
    }
    return this.lineIndent(line.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(parent2, of) {
  for (let cur2 = of; cur2; cur2 = cur2.parent)
    if (parent2 == cur2)
      return true;
  return false;
}
function bracketedAligned(context2) {
  let tree = context2.node;
  let openToken = tree.childAfter(tree.from), last = tree.lastChild;
  if (!openToken)
    return null;
  let sim = context2.options.simulateBreak;
  let openLine = context2.state.doc.lineAt(openToken.from);
  let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
  for (let pos = openToken.to; ; ) {
    let next2 = tree.childAfter(pos);
    if (!next2 || next2 == last)
      return null;
    if (!next2.type.isSkipped) {
      if (next2.from >= lineEnd)
        return null;
      let space = /^ */.exec(openLine.text.slice(openToken.to - openLine.from))[0].length;
      return { from: openToken.from, to: openToken.to + space };
    }
    pos = next2.to;
  }
}
function delimitedStrategy(context2, align, units, closing2, closedAt) {
  let after = context2.textAfter, space = after.match(/^\s*/)[0].length;
  let closed = closing2 && after.slice(space, space + closing2.length) == closing2 || closedAt == context2.pos + space;
  let aligned = align ? bracketedAligned(context2) : null;
  if (aligned)
    return closed ? context2.column(aligned.from) : context2.column(aligned.to);
  return context2.baseIndent + (closed ? 0 : context2.unit * units);
}
var DontIndentBeyond = 200;
function indentOnInput() {
  return EditorState.transactionFilter.of((tr) => {
    if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
      return tr;
    let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
    if (!rules.length)
      return tr;
    let doc2 = tr.newDoc, { head: head2 } = tr.newSelection.main, line = doc2.lineAt(head2);
    if (head2 > line.from + DontIndentBeyond)
      return tr;
    let lineStart = doc2.sliceString(line.from, head2);
    if (!rules.some((r2) => r2.test(lineStart)))
      return tr;
    let { state: state2 } = tr, last = -1, changes = [];
    for (let { head: head3 } of state2.selection.ranges) {
      let line2 = state2.doc.lineAt(head3);
      if (line2.from == last)
        continue;
      last = line2.from;
      let indent = getIndentation(state2, line2.from);
      if (indent == null)
        continue;
      let cur2 = /^\s*/.exec(line2.text)[0];
      let norm = indentString(state2, indent);
      if (cur2 != norm)
        changes.push({ from: line2.from, to: line2.from + cur2.length, insert: norm });
    }
    return changes.length ? [tr, { changes, sequential: true }] : tr;
  });
}
var foldService = /* @__PURE__ */ Facet.define();
var foldNodeProp = /* @__PURE__ */ new NodeProp();
function syntaxFolding(state2, start2, end) {
  let tree = syntaxTree(state2);
  if (tree.length < end)
    return null;
  let stack2 = tree.resolveStack(end, 1);
  let found = null;
  for (let iter = stack2; iter; iter = iter.next) {
    let cur2 = iter.node;
    if (cur2.to <= end || cur2.from > end)
      continue;
    if (found && cur2.from < start2)
      break;
    let prop2 = cur2.type.prop(foldNodeProp);
    if (prop2 && (cur2.to < tree.length - 50 || tree.length == state2.doc.length || !isUnfinished(cur2))) {
      let value = prop2(cur2, state2);
      if (value && value.from <= end && value.from >= start2 && value.to > end)
        found = value;
    }
  }
  return found;
}
function isUnfinished(node) {
  let ch = node.lastChild;
  return ch && ch.to == node.to && ch.type.isError;
}
function foldable(state2, lineStart, lineEnd) {
  for (let service of state2.facet(foldService)) {
    let result = service(state2, lineStart, lineEnd);
    if (result)
      return result;
  }
  return syntaxFolding(state2, lineStart, lineEnd);
}
function mapRange(range2, mapping) {
  let from = mapping.mapPos(range2.from, 1), to = mapping.mapPos(range2.to, -1);
  return from >= to ? void 0 : { from, to };
}
var foldEffect = /* @__PURE__ */ StateEffect.define({ map: mapRange });
var unfoldEffect = /* @__PURE__ */ StateEffect.define({ map: mapRange });
function selectedLines(view) {
  let lines = [];
  for (let { head: head2 } of view.state.selection.ranges) {
    if (lines.some((l) => l.from <= head2 && l.to >= head2))
      continue;
    lines.push(view.lineBlockAt(head2));
  }
  return lines;
}
var foldState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(folded, tr) {
    folded = folded.map(tr.changes);
    for (let e of tr.effects) {
      if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {
        let { preparePlaceholder } = tr.state.facet(foldConfig);
        let widget = !preparePlaceholder ? foldWidget : Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) });
        folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] });
      } else if (e.is(unfoldEffect)) {
        folded = folded.update({
          filter: (from, to) => e.value.from != from || e.value.to != to,
          filterFrom: e.value.from,
          filterTo: e.value.to
        });
      }
    }
    if (tr.selection) {
      let onSelection = false, { head: head2 } = tr.selection.main;
      folded.between(head2, head2, (a, b) => {
        if (a < head2 && b > head2)
          onSelection = true;
      });
      if (onSelection)
        folded = folded.update({
          filterFrom: head2,
          filterTo: head2,
          filter: (a, b) => b <= head2 || a >= head2
        });
    }
    return folded;
  },
  provide: (f) => EditorView.decorations.from(f),
  toJSON(folded, state2) {
    let ranges = [];
    folded.between(0, state2.doc.length, (from, to) => {
      ranges.push(from, to);
    });
    return ranges;
  },
  fromJSON(value) {
    if (!Array.isArray(value) || value.length % 2)
      throw new RangeError("Invalid JSON for fold state");
    let ranges = [];
    for (let i2 = 0; i2 < value.length; ) {
      let from = value[i2++], to = value[i2++];
      if (typeof from != "number" || typeof to != "number")
        throw new RangeError("Invalid JSON for fold state");
      ranges.push(foldWidget.range(from, to));
    }
    return Decoration.set(ranges, true);
  }
});
function findFold(state2, from, to) {
  var _a2;
  let found = null;
  (_a2 = state2.field(foldState, false)) === null || _a2 === void 0 ? void 0 : _a2.between(from, to, (from2, to2) => {
    if (!found || found.from > from2)
      found = { from: from2, to: to2 };
  });
  return found;
}
function foldExists(folded, from, to) {
  let found = false;
  folded.between(from, from, (a, b) => {
    if (a == from && b == to)
      found = true;
  });
  return found;
}
function maybeEnable(state2, other) {
  return state2.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
}
var foldCode = (view) => {
  for (let line of selectedLines(view)) {
    let range2 = foldable(view.state, line.from, line.to);
    if (range2) {
      view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range2), announceFold(view, range2)]) });
      return true;
    }
  }
  return false;
};
var unfoldCode = (view) => {
  if (!view.state.field(foldState, false))
    return false;
  let effects = [];
  for (let line of selectedLines(view)) {
    let folded = findFold(view.state, line.from, line.to);
    if (folded)
      effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
  }
  if (effects.length)
    view.dispatch({ effects });
  return effects.length > 0;
};
function announceFold(view, range2, fold = true) {
  let lineFrom = view.state.doc.lineAt(range2.from).number, lineTo = view.state.doc.lineAt(range2.to).number;
  return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
}
var foldAll = (view) => {
  let { state: state2 } = view, effects = [];
  for (let pos = 0; pos < state2.doc.length; ) {
    let line = view.lineBlockAt(pos), range2 = foldable(state2, line.from, line.to);
    if (range2)
      effects.push(foldEffect.of(range2));
    pos = (range2 ? view.lineBlockAt(range2.to) : line).to + 1;
  }
  if (effects.length)
    view.dispatch({ effects: maybeEnable(view.state, effects) });
  return !!effects.length;
};
var unfoldAll = (view) => {
  let field = view.state.field(foldState, false);
  if (!field || !field.size)
    return false;
  let effects = [];
  field.between(0, view.state.doc.length, (from, to) => {
    effects.push(unfoldEffect.of({ from, to }));
  });
  view.dispatch({ effects });
  return true;
};
var foldKeymap = [
  { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
  { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
  { key: "Ctrl-Alt-[", run: foldAll },
  { key: "Ctrl-Alt-]", run: unfoldAll }
];
var defaultConfig = {
  placeholderDOM: null,
  preparePlaceholder: null,
  placeholderText: "\u2026"
};
var foldConfig = /* @__PURE__ */ Facet.define({
  combine(values) {
    return combineConfig(values, defaultConfig);
  }
});
function codeFolding(config2) {
  let result = [foldState, baseTheme$12];
  if (config2)
    result.push(foldConfig.of(config2));
  return result;
}
function widgetToDOM(view, prepared) {
  let { state: state2 } = view, conf = state2.facet(foldConfig);
  let onclick = (event2) => {
    let line = view.lineBlockAt(view.posAtDOM(event2.target));
    let folded = findFold(view.state, line.from, line.to);
    if (folded)
      view.dispatch({ effects: unfoldEffect.of(folded) });
    event2.preventDefault();
  };
  if (conf.placeholderDOM)
    return conf.placeholderDOM(view, onclick, prepared);
  let element2 = document.createElement("span");
  element2.textContent = conf.placeholderText;
  element2.setAttribute("aria-label", state2.phrase("folded code"));
  element2.title = state2.phrase("unfold");
  element2.className = "cm-foldPlaceholder";
  element2.onclick = onclick;
  return element2;
}
var foldWidget = /* @__PURE__ */ Decoration.replace({ widget: /* @__PURE__ */ new class extends WidgetType {
  toDOM(view) {
    return widgetToDOM(view, null);
  }
}() });
var PreparedFoldWidget = class extends WidgetType {
  constructor(value) {
    super();
    this.value = value;
  }
  eq(other) {
    return this.value == other.value;
  }
  toDOM(view) {
    return widgetToDOM(view, this.value);
  }
};
var foldGutterDefaults = {
  openText: "\u2304",
  closedText: "\u203A",
  markerDOM: null,
  domEventHandlers: {},
  foldingChanged: () => false
};
var FoldMarker = class extends GutterMarker {
  constructor(config2, open) {
    super();
    this.config = config2;
    this.open = open;
  }
  eq(other) {
    return this.config == other.config && this.open == other.open;
  }
  toDOM(view) {
    if (this.config.markerDOM)
      return this.config.markerDOM(this.open);
    let span = document.createElement("span");
    span.textContent = this.open ? this.config.openText : this.config.closedText;
    span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
    return span;
  }
};
function foldGutter(config2 = {}) {
  let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config2);
  let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
  let markers = ViewPlugin.fromClass(class {
    constructor(view) {
      this.from = view.viewport.from;
      this.markers = this.buildMarkers(view);
    }
    update(update3) {
      if (update3.docChanged || update3.viewportChanged || update3.startState.facet(language) != update3.state.facet(language) || update3.startState.field(foldState, false) != update3.state.field(foldState, false) || syntaxTree(update3.startState) != syntaxTree(update3.state) || fullConfig.foldingChanged(update3))
        this.markers = this.buildMarkers(update3.view);
    }
    buildMarkers(view) {
      let builder = new RangeSetBuilder();
      for (let line of view.viewportLineBlocks) {
        let mark = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null;
        if (mark)
          builder.add(line.from, line.from, mark);
      }
      return builder.finish();
    }
  });
  let { domEventHandlers } = fullConfig;
  return [
    markers,
    gutter({
      class: "cm-foldGutter",
      markers(view) {
        var _a2;
        return ((_a2 = view.plugin(markers)) === null || _a2 === void 0 ? void 0 : _a2.markers) || RangeSet.empty;
      },
      initialSpacer() {
        return new FoldMarker(fullConfig, false);
      },
      domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event2) => {
        if (domEventHandlers.click && domEventHandlers.click(view, line, event2))
          return true;
        let folded = findFold(view.state, line.from, line.to);
        if (folded) {
          view.dispatch({ effects: unfoldEffect.of(folded) });
          return true;
        }
        let range2 = foldable(view.state, line.from, line.to);
        if (range2) {
          view.dispatch({ effects: foldEffect.of(range2) });
          return true;
        }
        return false;
      } })
    }),
    codeFolding()
  ];
}
var baseTheme$12 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-foldPlaceholder": {
    backgroundColor: "#eee",
    border: "1px solid #ddd",
    color: "#888",
    borderRadius: ".2em",
    margin: "0 1px",
    padding: "0 1px",
    cursor: "pointer"
  },
  ".cm-foldGutter span": {
    padding: "0 1px",
    cursor: "pointer"
  }
});
var HighlightStyle = class _HighlightStyle {
  constructor(specs, options4) {
    this.specs = specs;
    let modSpec;
    function def(spec) {
      let cls = StyleModule.newName();
      (modSpec || (modSpec = /* @__PURE__ */ Object.create(null)))["." + cls] = spec;
      return cls;
    }
    const all = typeof options4.all == "string" ? options4.all : options4.all ? def(options4.all) : void 0;
    const scopeOpt = options4.scope;
    this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? (type) => type == scopeOpt : void 0;
    this.style = tagHighlighter(specs.map((style) => ({
      tag: style.tag,
      class: style.class || def(Object.assign({}, style, { tag: null }))
    })), {
      all
    }).style;
    this.module = modSpec ? new StyleModule(modSpec) : null;
    this.themeType = options4.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, options4) {
    return new _HighlightStyle(specs, options4 || {});
  }
};
var highlighterFacet = /* @__PURE__ */ Facet.define();
var fallbackHighlighter = /* @__PURE__ */ Facet.define({
  combine(values) {
    return values.length ? [values[0]] : null;
  }
});
function getHighlighters(state2) {
  let main = state2.facet(highlighterFacet);
  return main.length ? main : state2.facet(fallbackHighlighter);
}
function syntaxHighlighting(highlighter, options4) {
  let ext2 = [treeHighlighter], themeType;
  if (highlighter instanceof HighlightStyle) {
    if (highlighter.module)
      ext2.push(EditorView.styleModule.of(highlighter.module));
    themeType = highlighter.themeType;
  }
  if (options4 === null || options4 === void 0 ? void 0 : options4.fallback)
    ext2.push(fallbackHighlighter.of(highlighter));
  else if (themeType)
    ext2.push(highlighterFacet.computeN([EditorView.darkTheme], (state2) => {
      return state2.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
    }));
  else
    ext2.push(highlighterFacet.of(highlighter));
  return ext2;
}
var TreeHighlighter = class {
  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(update3) {
    let tree = syntaxTree(update3.state), highlighters = getHighlighters(update3.state);
    let styleChange = highlighters != getHighlighters(update3.startState);
    let { viewport } = update3.view, decoratedToMapped = update3.changes.mapPos(this.decoratedTo, 1);
    if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
      this.decorations = this.decorations.map(update3.changes);
      this.decoratedTo = decoratedToMapped;
    } else if (tree != this.tree || update3.viewportChanged || styleChange) {
      this.tree = tree;
      this.decorations = this.buildDeco(update3.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 } of view.visibleRanges) {
      highlightTree(this.tree, highlighters, (from2, to2, style) => {
        builder.add(from2, to2, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
      }, from, to);
    }
    return builder.finish();
  }
};
var treeHighlighter = /* @__PURE__ */ Prec.high(/* @__PURE__ */ ViewPlugin.fromClass(TreeHighlighter, {
  decorations: (v) => v.decorations
}));
var defaultHighlightStyle = /* @__PURE__ */ HighlightStyle.define([
  {
    tag: tags2.meta,
    color: "#404740"
  },
  {
    tag: tags2.link,
    textDecoration: "underline"
  },
  {
    tag: tags2.heading,
    textDecoration: "underline",
    fontWeight: "bold"
  },
  {
    tag: tags2.emphasis,
    fontStyle: "italic"
  },
  {
    tag: tags2.strong,
    fontWeight: "bold"
  },
  {
    tag: tags2.strikethrough,
    textDecoration: "line-through"
  },
  {
    tag: tags2.keyword,
    color: "#708"
  },
  {
    tag: [tags2.atom, tags2.bool, tags2.url, tags2.contentSeparator, tags2.labelName],
    color: "#219"
  },
  {
    tag: [tags2.literal, tags2.inserted],
    color: "#164"
  },
  {
    tag: [tags2.string, tags2.deleted],
    color: "#a11"
  },
  {
    tag: [tags2.regexp, tags2.escape, /* @__PURE__ */ tags2.special(tags2.string)],
    color: "#e40"
  },
  {
    tag: /* @__PURE__ */ tags2.definition(tags2.variableName),
    color: "#00f"
  },
  {
    tag: /* @__PURE__ */ tags2.local(tags2.variableName),
    color: "#30a"
  },
  {
    tag: [tags2.typeName, tags2.namespace],
    color: "#085"
  },
  {
    tag: tags2.className,
    color: "#167"
  },
  {
    tag: [/* @__PURE__ */ tags2.special(tags2.variableName), tags2.macroName],
    color: "#256"
  },
  {
    tag: /* @__PURE__ */ tags2.definition(tags2.propertyName),
    color: "#00c"
  },
  {
    tag: tags2.comment,
    color: "#940"
  },
  {
    tag: tags2.invalid,
    color: "#f00"
  }
]);
var baseTheme2 = /* @__PURE__ */ EditorView.baseTheme({
  "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
  "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
});
var DefaultScanDist = 1e4;
var DefaultBrackets = "()[]{}";
var bracketMatchingConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      afterCursor: true,
      brackets: DefaultBrackets,
      maxScanDistance: DefaultScanDist,
      renderMatch: defaultRenderMatch
    });
  }
});
var matchingMark = /* @__PURE__ */ Decoration.mark({ class: "cm-matchingBracket" });
var 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;
}
var bracketMatchingState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(deco, tr) {
    if (!tr.docChanged && !tr.selection)
      return deco;
    let decorations2 = [];
    let config2 = tr.state.facet(bracketMatchingConfig);
    for (let range2 of tr.state.selection.ranges) {
      if (!range2.empty)
        continue;
      let match = matchBrackets(tr.state, range2.head, -1, config2) || range2.head > 0 && matchBrackets(tr.state, range2.head - 1, 1, config2) || config2.afterCursor && (matchBrackets(tr.state, range2.head, 1, config2) || range2.head < tr.state.doc.length && matchBrackets(tr.state, range2.head + 1, -1, config2));
      if (match)
        decorations2 = decorations2.concat(config2.renderMatch(match, tr.state));
    }
    return Decoration.set(decorations2, true);
  },
  provide: (f) => EditorView.decorations.from(f)
});
var bracketMatchingUnique = [
  bracketMatchingState,
  baseTheme2
];
function bracketMatching(config2 = {}) {
  return [bracketMatchingConfig.of(config2), bracketMatchingUnique];
}
var bracketMatchingHandle = /* @__PURE__ */ new NodeProp();
function matchingNodes(node, dir, brackets) {
  let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
  if (byProp)
    return byProp;
  if (node.name.length == 1) {
    let index3 = brackets.indexOf(node.name);
    if (index3 > -1 && index3 % 2 == (dir < 0 ? 1 : 0))
      return [brackets[index3 + dir]];
  }
  return null;
}
function findHandle(node) {
  let hasHandle = node.type.prop(bracketMatchingHandle);
  return hasHandle ? hasHandle(node.node) : node;
}
function matchBrackets(state2, pos, dir, config2 = {}) {
  let maxScanDistance = config2.maxScanDistance || DefaultScanDist, brackets = config2.brackets || DefaultBrackets;
  let tree = syntaxTree(state2), node = tree.resolveInner(pos, dir);
  for (let cur2 = node; cur2; cur2 = cur2.parent) {
    let matches = matchingNodes(cur2.type, dir, brackets);
    if (matches && cur2.from < cur2.to) {
      let handle2 = findHandle(cur2);
      if (handle2 && (dir > 0 ? pos >= handle2.from && pos < handle2.to : pos > handle2.from && pos <= handle2.to))
        return matchMarkedBrackets(state2, pos, dir, cur2, handle2, matches, brackets);
    }
  }
  return matchPlainBrackets(state2, pos, dir, tree, node.type, maxScanDistance, brackets);
}
function matchMarkedBrackets(_state, _pos, dir, token, handle2, matching, brackets) {
  let parent2 = token.parent, firstToken = { from: handle2.from, to: handle2.to };
  let depth = 0, cursor = parent2 === null || parent2 === void 0 ? void 0 : parent2.cursor();
  if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
    do {
      if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.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(state2, pos, dir, tree, tokenType, maxScanDistance, brackets) {
  let startCh = dir < 0 ? state2.sliceDoc(pos - 1, pos) : state2.sliceDoc(pos, pos + 1);
  let bracket2 = brackets.indexOf(startCh);
  if (bracket2 < 0 || bracket2 % 2 == 0 != dir > 0)
    return null;
  let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
  let iter = state2.doc.iterRange(pos, dir > 0 ? state2.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 = pos + distance * dir;
    for (let pos2 = dir > 0 ? 0 : text2.length - 1, end = dir > 0 ? text2.length : -1; pos2 != end; pos2 += dir) {
      let found = brackets.indexOf(text2[pos2]);
      if (found < 0 || tree.resolveInner(basePos + pos2, 1).type != tokenType)
        continue;
      if (found % 2 == 0 == dir > 0) {
        depth++;
      } else if (depth == 1) {
        return { start: startToken, end: { from: basePos + pos2, to: basePos + pos2 + 1 }, matched: found >> 1 == bracket2 >> 1 };
      } else {
        depth--;
      }
    }
    if (dir > 0)
      distance += text2.length;
  }
  return iter.done ? { start: startToken, matched: false } : null;
}
function countCol(string4, end, tabSize, startIndex = 0, startValue = 0) {
  if (end == null) {
    end = string4.search(/[^\s\u00a0]/);
    if (end == -1)
      end = string4.length;
  }
  let n = startValue;
  for (let i2 = startIndex; i2 < end; i2++) {
    if (string4.charCodeAt(i2) == 9)
      n += tabSize - n % tabSize;
    else
      n++;
  }
  return n;
}
var StringStream = class {
  /**
  Create a stream.
  */
  constructor(string4, tabSize, indentUnit2, overrideIndent) {
    this.string = string4;
    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 ch = this.string.charAt(this.pos);
    let ok2;
    if (typeof match == "string")
      ok2 = ch == match;
    else
      ok2 = ch && (match instanceof RegExp ? match.test(ch) : match(ch));
    if (ok2) {
      ++this.pos;
      return ch;
    }
  }
  /**
  Continue matching characters that match the given string,
  regular expression, or predicate function. Return true if any
  characters were consumed.
  */
  eatWhile(match) {
    let start2 = this.pos;
    while (this.eat(match)) {
    }
    return this.pos > start2;
  }
  /**
  Consume whitespace ahead of `this.pos`. Return true if any was
  found.
  */
  eatSpace() {
    let start2 = this.pos;
    while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
      ++this.pos;
    return this.pos > start2;
  }
  /**
  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(ch) {
    let found = this.string.indexOf(ch, 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 = (str) => caseInsensitive ? str.toLowerCase() : str;
      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(state2) {
  if (typeof state2 != "object")
    return state2;
  let newState = {};
  for (let prop2 in state2) {
    let val = state2[prop2];
    newState[prop2] = val instanceof Array ? val.slice() : val;
  }
  return newState;
}
var IndentedFrom = /* @__PURE__ */ new WeakMap();
var StreamLanguage = class _StreamLanguage extends Language {
  constructor(parser) {
    let data = defineLanguageFacet(parser.languageData);
    let p = fullParser(parser), self3;
    let impl = new class extends Parser {
      createParse(input, fragments, ranges) {
        return new Parse(self3, input, fragments, ranges);
      }
    }();
    super(data, impl, [], parser.name);
    this.topNode = docID(data, this);
    self3 = this;
    this.streamParser = p;
    this.stateAfter = new NodeProp({ perNode: true });
    this.tokenTable = parser.tokenTable ? new TokenTable(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 start2 = findState(this, cx.node.tree, cx.node.from, cx.node.from, from !== null && from !== void 0 ? from : cx.pos), statePos, state2;
    if (start2) {
      state2 = start2.state;
      statePos = start2.pos + 1;
    } else {
      state2 = this.streamParser.startState(cx.unit);
      statePos = cx.node.from;
    }
    if (cx.pos - statePos > 1e4)
      return null;
    while (statePos < cx.pos) {
      let line2 = cx.state.doc.lineAt(statePos), end = Math.min(cx.pos, line2.to);
      if (line2.length) {
        let indentation = overrideIndentation ? overrideIndentation(line2.from) : -1;
        let stream = new StringStream(line2.text, cx.state.tabSize, cx.unit, indentation < 0 ? void 0 : indentation);
        while (stream.pos < end - line2.from)
          readToken(this.streamParser.token, stream, state2);
      } else {
        this.streamParser.blankLine(state2, cx.unit);
      }
      if (end == cx.pos)
        break;
      statePos = line2.to + 1;
    }
    let line = cx.lineAt(cx.pos);
    if (overrideIndentation && from == null)
      IndentedFrom.set(cx.state, line.from);
    return this.streamParser.indent(state2, /^\s*(.*)/.exec(line.text)[1], cx);
  }
  get allowsNesting() {
    return false;
  }
};
function findState(lang, tree, off, startPos, before) {
  let state2 = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);
  if (state2)
    return { state: lang.streamParser.copyState(state2), pos: off + tree.length };
  for (let i2 = tree.children.length - 1; i2 >= 0; i2--) {
    let child2 = tree.children[i2], pos = off + tree.positions[i2];
    let found = child2 instanceof Tree && pos < before && findState(lang, child2, pos, startPos, before);
    if (found)
      return found;
  }
  return null;
}
function cutTree(lang, tree, from, to, inside2) {
  if (inside2 && from <= 0 && to >= 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 pos = tree.positions[i2], child2 = tree.children[i2], inner;
    if (pos < to && child2 instanceof Tree) {
      if (!(inner = cutTree(lang, child2, from - pos, to - pos, inside2)))
        break;
      return !inside2 ? inner : new Tree(tree.type, tree.children.slice(0, i2).concat(inner), tree.positions.slice(0, i2 + 1), pos + inner.length);
    }
  }
  return null;
}
function findStartInFragments(lang, fragments, startPos, endPos, editorState) {
  for (let f of fragments) {
    let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0);
    let found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), 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 };
}
var Parse = class {
  constructor(lang, input, fragments, ranges) {
    this.lang = lang;
    this.input = input;
    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 context2 = ParseContext.get(), from = ranges[0].from;
    let { state: state2, tree } = findStartInFragments(lang, fragments, from, this.to, context2 === null || context2 === void 0 ? void 0 : context2.state);
    this.state = state2;
    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 (context2 && this.parsedPos < context2.viewport.from - 1e5 && ranges.some((r2) => r2.from <= context2.viewport.from && r2.to >= context2.viewport.from)) {
      this.state = this.lang.streamParser.startState(getIndentUnit(context2.state));
      context2.skipUntilInView(this.parsedPos, context2.viewport.from);
      this.parsedPos = context2.viewport.from;
    }
    this.moveRangeIndex();
  }
  advance() {
    let context2 = 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 (context2)
      end = Math.min(end, context2.viewport.to);
    while (this.parsedPos < end)
      this.parseLine(context2);
    if (this.chunkStart < this.parsedPos)
      this.finishChunk();
    if (this.parsedPos >= parseEnd)
      return this.finish();
    if (context2 && this.parsedPos >= context2.viewport.to) {
      context2.skipUntilInView(this.parsedPos, parseEnd);
      return this.finish();
    }
    return null;
  }
  stopAt(pos) {
    this.stoppedAt = pos;
  }
  lineAfter(pos) {
    let chunk = this.input.chunk(pos);
    if (!this.input.lineChunks) {
      let eol = chunk.indexOf("\n");
      if (eol > -1)
        chunk = chunk.slice(0, eol);
    } else if (chunk == "\n") {
      chunk = "";
    }
    return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos);
  }
  nextLine() {
    let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length;
    for (let index3 = this.rangeIndex; ; ) {
      let rangeEnd2 = this.ranges[index3].to;
      if (rangeEnd2 >= end)
        break;
      line = line.slice(0, rangeEnd2 - (end - line.length));
      index3++;
      if (index3 == this.ranges.length)
        break;
      let rangeStart = this.ranges[index3].from;
      let after = this.lineAfter(rangeStart);
      line += after;
      end = rangeStart + after.length;
    }
    return { line, end };
  }
  skipGapsTo(pos, offset, side) {
    for (; ; ) {
      let end = this.ranges[this.rangeIndex].to, offPos = pos + offset;
      if (side > 0 ? end > offPos : end >= offPos)
        break;
      let start2 = this.ranges[++this.rangeIndex].from;
      offset += start2 - end;
    }
    return offset;
  }
  moveRangeIndex() {
    while (this.ranges[this.rangeIndex].to < this.parsedPos)
      this.rangeIndex++;
  }
  emitToken(id3, from, to, 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(to, offset, -1);
      to += offset;
      size += this.chunk.length - len0;
    }
    let last = this.chunk.length - 4;
    if (this.lang.streamParser.mergeTokens && size == 4 && last >= 0 && this.chunk[last] == id3 && this.chunk[last + 2] == from)
      this.chunk[last + 2] = to;
    else
      this.chunk.push(id3, from, to, size);
    return offset;
  }
  parseLine(context2) {
    let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
    let stream = new StringStream(line, context2 ? context2.state.tabSize : 4, context2 ? getIndentUnit(context2.state) : 2);
    if (stream.eol()) {
      streamParser.blankLine(this.state, stream.indentUnit);
    } else {
      while (!stream.eol()) {
        let token = readToken(streamParser.token, stream, this.state);
        if (token)
          offset = this.emitToken(this.lang.tokenTable.resolve(token), 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(token, stream, state2) {
  stream.start = stream.pos;
  for (let i2 = 0; i2 < 10; i2++) {
    let result = token(stream, state2);
    if (stream.pos > stream.start)
      return result;
  }
  throw new Error("Stream parser failed to advance stream.");
}
var noTokens = /* @__PURE__ */ Object.create(null);
var typeArray = [NodeType.none];
var nodeSet = /* @__PURE__ */ new NodeSet(typeArray);
var warned = [];
var byTag = /* @__PURE__ */ Object.create(null);
var defaultTable = /* @__PURE__ */ Object.create(null);
for (let [legacyName, name3] 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, name3);
var TokenTable = class {
  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));
  }
};
var defaultTokenTable = /* @__PURE__ */ new TokenTable(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 name4 of tagStr.split(" ")) {
    let found = [];
    for (let part of name4.split(".")) {
      let value = extra[part] || tags2[part];
      if (!value) {
        warnForPart(part, `Unknown highlighting tag ${part}`);
      } else if (typeof value == "function") {
        if (!found.length)
          warnForPart(part, `Modifier ${part} used at start of tag`);
        else
          found = found.map(value);
      } else {
        if (found.length)
          warnForPart(part, `Tag ${part} used as modifier`);
        else
          found = Array.isArray(value) ? value : [value];
      }
    }
    for (let tag of found)
      tags$1.push(tag);
  }
  if (!tags$1.length)
    return 0;
  let name3 = tagStr.replace(/ /g, "_"), key2 = name3 + " " + tags$1.map((t4) => t4.id);
  let known = byTag[key2];
  if (known)
    return known.id;
  let type = byTag[key2] = NodeType.define({
    id: typeArray.length,
    name: name3,
    props: [styleTags({ [name3]: 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;
}
var marks = {
  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 }),
  auto: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "auto" }, bidiIsolate: null })
};

// node_modules/@codemirror/autocomplete/dist/index.js
var CompletionContext = class {
  /**
  Create a new completion context. (Mostly useful for testing
  completion sources—in the editor, the extension will create
  these for you.)
  */
  constructor(state2, pos, explicit, view) {
    this.state = state2;
    this.pos = pos;
    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 token = syntaxTree(this.state).resolveInner(this.pos, -1);
    while (token && types2.indexOf(token.name) < 0)
      token = token.parent;
    return token ? {
      from: token.from,
      to: this.pos,
      text: this.state.sliceDoc(token.from, this.pos),
      type: token.type
    } : null;
  }
  /**
  Get the match of the given expression directly before the
  cursor.
  */
  matchBefore(expr) {
    let line = this.state.doc.lineAt(this.pos);
    let start2 = Math.max(line.from, this.pos - 250);
    let str = line.text.slice(start2 - line.from, this.pos - line.from);
    let found = str.search(ensureAnchor(expr, false));
    return found < 0 ? null : { from: start2 + found, to: this.pos, text: str.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, options4) {
    if (type == "abort" && this.abortListeners) {
      this.abortListeners.push(listener);
      if (options4 && options4.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(options4) {
  let first = /* @__PURE__ */ Object.create(null), rest = /* @__PURE__ */ Object.create(null);
  for (let { label } of options4) {
    first[label[0]] = true;
    for (let i2 = 1; i2 < label.length; i2++)
      rest[label[i2]] = true;
  }
  let source3 = toSet(first) + toSet(rest) + "*$";
  return [new RegExp("^" + source3), new RegExp(source3)];
}
function completeFromList(list) {
  let options4 = list.map((o) => typeof o == "string" ? { label: o } : o);
  let [validFor, match] = options4.every((o) => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options4);
  return (context2) => {
    let token = context2.matchBefore(match);
    return token || context2.explicit ? { from: token ? token.from : context2.pos, options: options4, validFor } : null;
  };
}
var Option = class {
  constructor(completion, source3, match, score2) {
    this.completion = completion;
    this.source = source3;
    this.match = match;
    this.score = score2;
  }
};
function cur(state2) {
  return state2.selection.main.from;
}
function ensureAnchor(expr, start2) {
  var _a2;
  let { source: source3 } = expr;
  let addStart = start2 && source3[0] != "^", addEnd = source3[source3.length - 1] != "$";
  if (!addStart && !addEnd)
    return expr;
  return new RegExp(`${addStart ? "^" : ""}(?:${source3})${addEnd ? "$" : ""}`, (_a2 = expr.flags) !== null && _a2 !== void 0 ? _a2 : expr.ignoreCase ? "i" : "");
}
var pickedCompletion = /* @__PURE__ */ Annotation.define();
function insertCompletionText(state2, text2, from, to) {
  let { main } = state2.selection, fromOff = from - main.from, toOff = to - main.from;
  return Object.assign(Object.assign({}, state2.changeByRange((range2) => {
    if (range2 != main && from != to && state2.sliceDoc(range2.from + fromOff, range2.from + toOff) != state2.sliceDoc(from, to))
      return { range: range2 };
    let lines = state2.toText(text2);
    return {
      changes: { from: range2.from + fromOff, to: to == main.from ? range2.to : range2.from + toOff, insert: lines },
      range: EditorSelection.cursor(range2.from + fromOff + lines.length)
    };
  })), { scrollIntoView: true, userEvent: "input.complete" });
}
var SourceCache = /* @__PURE__ */ new WeakMap();
function asSource(source3) {
  if (!Array.isArray(source3))
    return source3;
  let known = SourceCache.get(source3);
  if (!known)
    SourceCache.set(source3, known = completeFromList(source3));
  return known;
}
var startCompletionEffect = /* @__PURE__ */ StateEffect.define();
var closeCompletionEffect = /* @__PURE__ */ StateEffect.define();
var FuzzyMatcher = class {
  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 = codePointAt2(pattern, p), size = codePointSize2(char);
      this.chars.push(char);
      let part = pattern.slice(p, p + size), upper = part.toUpperCase();
      this.folded.push(codePointAt2(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 first = codePointAt2(word, 0), firstSize = codePointSize2(first);
      let score2 = firstSize == word.length ? 0 : -100;
      if (first == chars[0]) ;
      else if (first == 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 next2 = codePointAt2(word, i2);
        if (next2 == chars[anyTo] || next2 == folded[anyTo])
          any[anyTo++] = i2;
        i2 += codePointSize2(next2);
      }
      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 next2 = codePointAt2(word, i2);
      if (direct < 0) {
        if (preciseTo < len && next2 == chars[preciseTo])
          precise[preciseTo++] = i2;
        if (adjacentTo < len) {
          if (next2 == chars[adjacentTo] || next2 == folded[adjacentTo]) {
            if (adjacentTo == 0)
              adjacentStart = i2;
            adjacentEnd = i2 + 1;
            adjacentTo++;
          } else {
            adjacentTo = 0;
          }
        }
      }
      let ch, type = next2 < 255 ? next2 >= 48 && next2 <= 57 || next2 >= 97 && next2 <= 122 ? 2 : next2 >= 65 && next2 <= 90 ? 1 : 0 : (ch = fromCodePoint(next2)) != ch.toLowerCase() ? 1 : ch != ch.toUpperCase() ? 2 : 0;
      if (!i2 || type == 1 && hasLower || prevType == 0 && type != 0) {
        if (chars[byWordTo] == next2 || folded[byWordTo] == next2 && (byWordFolded = true))
          byWord[byWordTo++] = i2;
        else if (byWord.length)
          wordAdjacent = false;
      }
      prevType = type;
      i2 += codePointSize2(next2);
    }
    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 result = [], i2 = 0;
    for (let pos of positions) {
      let to = pos + (this.astral ? codePointSize2(codePointAt2(word, pos)) : 1);
      if (i2 && result[i2 - 1] == pos)
        result[i2 - 1] = to;
      else {
        result[i2++] = pos;
        result[i2++] = to;
      }
    }
    return this.ret(score2 - word.length, result);
  }
};
var StrictMatcher = class {
  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 start2 = word.slice(0, this.pattern.length);
    let match = start2 == this.pattern ? 0 : start2.toLowerCase() == this.folded ? -200 : null;
    if (match == null)
      return null;
    this.matched = [0, start2.length];
    this.score = match + (word.length == this.pattern.length ? 0 : -100);
    return this;
  }
};
var 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) => (c) => joinClass(a(c), b(c)),
      optionClass: (a, b) => (c) => joinClass(a(c), b(c)),
      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, list, option, info2, space, tooltip2) {
  let rtl = view.textDirection == Direction.RTL, left2 = rtl, narrow = false;
  let side = "top", offset, maxWidth;
  let spaceLeft = list.left - space.left, spaceRight = space.right - list.right;
  let infoWidth = info2.right - info2.left, infoHeight = info2.bottom - info2.top;
  if (left2 && spaceLeft < Math.min(infoWidth, spaceRight))
    left2 = false;
  else if (!left2 && spaceRight < Math.min(infoWidth, spaceLeft))
    left2 = true;
  if (infoWidth <= (left2 ? spaceLeft : spaceRight)) {
    offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list.top;
    maxWidth = Math.min(400, left2 ? spaceLeft : spaceRight);
  } else {
    narrow = true;
    maxWidth = Math.min(
      400,
      (rtl ? list.right : space.right - list.left) - 30
      /* Info.Margin */
    );
    let spaceBelow = space.bottom - list.bottom;
    if (spaceBelow >= infoHeight || spaceBelow > list.top) {
      offset = option.bottom - list.top;
    } else {
      side = "bottom";
      offset = list.bottom - option.top;
    }
  }
  let scaleY = (list.bottom - list.top) / tooltip2.offsetHeight;
  let scaleX = (list.right - list.left) / tooltip2.offsetWidth;
  return {
    style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
    class: "cm-completionInfo-" + (narrow ? rtl ? "left-narrow" : "right-narrow" : left2 ? "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 label = completion.displayLabel || completion.label, off = 0;
      for (let j = 0; j < match.length; ) {
        let from = match[j++], to = match[j++];
        if (from > off)
          labelElt.appendChild(document.createTextNode(label.slice(off, from)));
        let span = labelElt.appendChild(document.createElement("span"));
        span.appendChild(document.createTextNode(label.slice(from, to)));
        span.className = "cm-completionMatchedText";
        off = to;
      }
      if (off < label.length)
        labelElt.appendChild(document.createTextNode(label.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, selected, max3) {
  if (total <= max3)
    return { from: 0, to: total };
  if (selected < 0)
    selected = 0;
  if (selected <= total >> 1) {
    let off2 = Math.floor(selected / max3);
    return { from: off2 * max3, to: (off2 + 1) * max3 };
  }
  let off = Math.floor((total - selected) / max3);
  return { from: total - (off + 1) * max3, to: total - off * max3 };
}
var CompletionTooltip = class {
  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: (pos) => this.placeInfo(pos),
      key: this
    };
    this.space = null;
    this.currentClass = "";
    let cState = view.state.field(stateField);
    let { options: options4, selected } = cState.open;
    let config2 = view.state.facet(completionConfig);
    this.optionContent = optionContent(config2);
    this.optionClass = config2.optionClass;
    this.tooltipClass = config2.tooltipClass;
    this.range = rangeAroundSelected(options4.length, selected, config2.maxRenderedOptions);
    this.dom = document.createElement("div");
    this.dom.className = "cm-tooltip-autocomplete";
    this.updateTooltipClass(view.state);
    this.dom.addEventListener("mousedown", (e) => {
      let { options: options5 } = 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] < options5.length) {
          this.applyCompletion(view, options5[+match[1]]);
          e.preventDefault();
          return;
        }
      }
    });
    this.dom.addEventListener("focusout", (e) => {
      let state2 = view.state.field(this.stateField, false);
      if (state2 && state2.tooltip && view.state.facet(completionConfig).closeOnBlur && e.relatedTarget != view.contentDOM)
        view.dispatch({ effects: closeCompletionEffect.of(null) });
    });
    this.showOptions(options4, cState.id);
  }
  mount() {
    this.updateSel();
  }
  showOptions(options4, id3) {
    if (this.list)
      this.list.remove();
    this.list = this.dom.appendChild(this.createListBox(options4, id3, this.range));
    this.list.addEventListener("scroll", () => {
      if (this.info)
        this.view.requestMeasure(this.placeInfoReq);
    });
  }
  update(update3) {
    var _a2;
    let cState = update3.state.field(this.stateField);
    let prevState = update3.startState.field(this.stateField);
    this.updateTooltipClass(update3.state);
    if (cState != prevState) {
      let { options: options4, selected, disabled } = cState.open;
      if (!prevState.open || prevState.open.options != options4) {
        this.range = rangeAroundSelected(options4.length, selected, update3.state.facet(completionConfig).maxRenderedOptions);
        this.showOptions(options4, 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(state2) {
    let cls = this.tooltipClass(state2);
    if (cls != this.currentClass) {
      for (let c of this.currentClass.split(" "))
        if (c)
          this.dom.classList.remove(c);
      for (let c of cls.split(" "))
        if (c)
          this.dom.classList.add(c);
      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: info2 } = completion;
      if (!info2)
        return;
      let infoResult = typeof info2 === "string" ? document.createTextNode(info2) : info2(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 wrap = this.info = document.createElement("div");
    wrap.className = "cm-tooltip cm-completionInfo";
    if (content2.nodeType != null) {
      wrap.appendChild(content2);
      this.infoDestroy = null;
    } else {
      let { dom, destroy } = content2;
      wrap.appendChild(dom);
      this.infoDestroy = destroy || null;
    }
    this.dom.appendChild(wrap);
    this.view.requestMeasure(this.placeInfoReq);
  }
  updateSelectedOption(selected) {
    let set4 = 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 == selected) {
        if (!opt.hasAttribute("aria-selected")) {
          opt.setAttribute("aria-selected", "true");
          set4 = opt;
        }
      } else {
        if (opt.hasAttribute("aria-selected"))
          opt.removeAttribute("aria-selected");
      }
    }
    if (set4)
      scrollIntoView2(this.list, set4);
    return set4;
  }
  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(pos) {
    if (this.info) {
      if (pos) {
        if (pos.style)
          this.info.style.cssText = pos.style;
        this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
      } else {
        this.info.style.cssText = "top: -1e6px";
      }
    }
  }
  createListBox(options4, id3, range2) {
    const ul = document.createElement("ul");
    ul.id = id3;
    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 = range2.from; i2 < range2.to; i2++) {
      let { completion, match } = options4[i2], { section } = completion;
      if (section) {
        let name3 = typeof section == "string" ? section : section.name;
        if (name3 != curSection && (i2 > range2.from || range2.from == 0)) {
          curSection = name3;
          if (typeof section != "string" && section.header) {
            ul.appendChild(section.header(section));
          } else {
            let header = ul.appendChild(document.createElement("completion-section"));
            header.textContent = name3;
          }
        }
      }
      const li = ul.appendChild(document.createElement("li"));
      li.id = id3 + "-" + i2;
      li.setAttribute("role", "option");
      let cls = this.optionClass(completion);
      if (cls)
        li.className = cls;
      for (let source3 of this.optionContent) {
        let node = source3(completion, this.view.state, this.view, match);
        if (node)
          li.appendChild(node);
      }
    }
    if (range2.from)
      ul.classList.add("cm-completionListIncompleteTop");
    if (range2.to < options4.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 scrollIntoView2(container, element2) {
  let parent2 = container.getBoundingClientRect();
  let self3 = element2.getBoundingClientRect();
  let scaleY = parent2.height / container.offsetHeight;
  if (self3.top < parent2.top)
    container.scrollTop -= (parent2.top - self3.top) / scaleY;
  else if (self3.bottom > parent2.bottom)
    container.scrollTop += (self3.bottom - parent2.bottom) / scaleY;
}
function score(option) {
  return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + (option.type ? 1 : 0);
}
function sortOptions(active, state2) {
  let options4 = [];
  let sections = null;
  let addOption = (option) => {
    options4.push(option);
    let { section } = option.completion;
    if (section) {
      if (!sections)
        sections = [];
      let name3 = typeof section == "string" ? section : section.name;
      if (!sections.some((s) => s.name == name3))
        sections.push(typeof section == "string" ? { name: name3 } : section);
    }
  };
  let conf = state2.facet(completionConfig);
  for (let a of active)
    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 - options4.length));
        }
      } else {
        let pattern = state2.sliceDoc(a.from, a.to), match;
        let matcher2 = conf.filterStrict ? new StrictMatcher(pattern) : new FuzzyMatcher(pattern);
        for (let option of a.result.options)
          if (match = matcher2.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), pos = 0;
    let cmp = (a, b) => {
      var _a2, _b;
      return ((_a2 = a.rank) !== null && _a2 !== void 0 ? _a2 : 1e9) - ((_b = b.rank) !== null && _b !== void 0 ? _b : 1e9) || (a.name < b.name ? -1 : 1);
    };
    for (let s of sections.sort(cmp)) {
      pos -= 1e5;
      sectionOrder[s.name] = pos;
    }
    for (let option of options4) {
      let { section } = option.completion;
      if (section)
        option.score += sectionOrder[typeof section == "string" ? section : section.name];
    }
  }
  let result = [], prev = null;
  let compare2 = conf.compareCompletions;
  for (let opt of options4.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)
      result.push(opt);
    else if (score(opt.completion) > score(prev))
      result[result.length - 1] = opt;
    prev = opt.completion;
  }
  return result;
}
var CompletionDialog = class _CompletionDialog {
  constructor(options4, attrs, tooltip2, timestamp, selected, disabled) {
    this.options = options4;
    this.attrs = attrs;
    this.tooltip = tooltip2;
    this.timestamp = timestamp;
    this.selected = selected;
    this.disabled = disabled;
  }
  setSelected(selected, id3) {
    return selected == this.selected || selected >= this.options.length ? this : new _CompletionDialog(this.options, makeAttrs(id3, selected), this.tooltip, this.timestamp, selected, this.disabled);
  }
  static build(active, state2, id3, prev, conf, didSetActive) {
    if (prev && !didSetActive && active.some((s) => s.isPending))
      return prev.setDisabled();
    let options4 = sortOptions(active, state2);
    if (!options4.length)
      return prev && active.some((a) => a.isPending) ? prev.setDisabled() : null;
    let selected = state2.facet(completionConfig).selectOnOpen ? 0 : -1;
    if (prev && prev.selected != selected && prev.selected != -1) {
      let selectedValue = prev.options[prev.selected].completion;
      for (let i2 = 0; i2 < options4.length; i2++)
        if (options4[i2].completion == selectedValue) {
          selected = i2;
          break;
        }
    }
    return new _CompletionDialog(options4, makeAttrs(id3, selected), {
      pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
      create: createTooltip,
      above: conf.aboveCursor
    }, prev ? prev.timestamp : Date.now(), selected, 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);
  }
};
var CompletionState = class _CompletionState {
  constructor(active, id3, open) {
    this.active = active;
    this.id = id3;
    this.open = open;
  }
  static start() {
    return new _CompletionState(none2, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
  }
  update(tr) {
    let { state: state2 } = tr, conf = state2.facet(completionConfig);
    let sources = conf.override || state2.languageDataAt("autocomplete", cur(state2)).map(asSource);
    let active = sources.map((source3) => {
      let value = this.active.find((s) => s.source == source3) || new ActiveSource(
        source3,
        this.active.some(
          (a) => a.state != 0
          /* State.Inactive */
        ) ? 1 : 0
        /* State.Inactive */
      );
      return value.update(tr, conf);
    });
    if (active.length == this.active.length && active.every((a, i2) => a == this.active[i2]))
      active = this.active;
    let open = this.open, didSet = tr.effects.some((e) => e.is(setActiveEffect));
    if (open && tr.docChanged)
      open = open.map(tr.changes);
    if (tr.selection || active.some((a) => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || !sameResults(active, this.active) || didSet)
      open = CompletionDialog.build(active, state2, this.id, open, conf, didSet);
    else if (open && open.disabled && !active.some((a) => a.isPending))
      open = null;
    if (!open && active.every((a) => !a.isPending) && active.some((a) => a.hasResult()))
      active = active.map((a) => a.hasResult() ? new ActiveSource(
        a.source,
        0
        /* State.Inactive */
      ) : a);
    for (let effect2 of tr.effects)
      if (effect2.is(setSelectedEffect))
        open = open && open.setSelected(effect2.value, this.id);
    return active == this.active && open == this.open ? this : new _CompletionState(active, this.id, open);
  }
  get tooltip() {
    return this.open ? this.open.tooltip : null;
  }
  get attrs() {
    return this.open ? this.open.attrs : this.active.length ? baseAttrs : noAttrs2;
  }
};
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;
  }
}
var baseAttrs = {
  "aria-autocomplete": "list"
};
var noAttrs2 = {};
function makeAttrs(id3, selected) {
  let result = {
    "aria-autocomplete": "list",
    "aria-haspopup": "listbox",
    "aria-controls": id3
  };
  if (selected > -1)
    result["aria-activedescendant"] = id3 + "-" + selected;
  return result;
}
var none2 = [];
function getUpdateType(tr, conf) {
  if (tr.isUserEvent("input.complete")) {
    let completion = tr.annotation(pickedCompletion);
    if (completion && conf.activateOnCompletion(completion))
      return 4 | 8;
  }
  let typing = tr.isUserEvent("input.type");
  return typing && conf.activateOnTyping ? 4 | 1 : typing ? 1 : tr.isUserEvent("delete.backward") ? 2 : tr.selection ? 8 : tr.docChanged ? 16 : 0;
}
var ActiveSource = class _ActiveSource {
  constructor(source3, state2, explicit = false) {
    this.source = source3;
    this.state = state2;
    this.explicit = explicit;
  }
  hasResult() {
    return false;
  }
  get isPending() {
    return this.state == 1;
  }
  update(tr, conf) {
    let type = getUpdateType(tr, conf), value = this;
    if (type & 8 || type & 16 && this.touches(tr))
      value = new _ActiveSource(
        value.source,
        0
        /* State.Inactive */
      );
    if (type & 4 && value.state == 0)
      value = new _ActiveSource(
        this.source,
        1
        /* State.Pending */
      );
    value = value.updateFor(tr, type);
    for (let effect2 of tr.effects) {
      if (effect2.is(startCompletionEffect))
        value = new _ActiveSource(value.source, 1, effect2.value);
      else if (effect2.is(closeCompletionEffect))
        value = new _ActiveSource(
          value.source,
          0
          /* State.Inactive */
        );
      else if (effect2.is(setActiveEffect)) {
        for (let active of effect2.value)
          if (active.source == value.source)
            value = active;
      }
    }
    return value;
  }
  updateFor(tr, type) {
    return this.map(tr.changes);
  }
  map(changes) {
    return this;
  }
  touches(tr) {
    return tr.changes.touchesRange(cur(tr.state));
  }
};
var ActiveResult = class _ActiveResult extends ActiveSource {
  constructor(source3, explicit, limit, result, from, to) {
    super(source3, 3, explicit);
    this.limit = limit;
    this.result = result;
    this.from = from;
    this.to = to;
  }
  hasResult() {
    return true;
  }
  updateFor(tr, type) {
    var _a2;
    if (!(type & 3))
      return this.map(tr.changes);
    let result = this.result;
    if (result.map && !tr.changes.empty)
      result = result.map(result, tr.changes);
    let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
    let pos = cur(tr.state);
    if (pos > to || !result || type & 2 && (cur(tr.startState) == this.from || pos < this.limit))
      return new ActiveSource(
        this.source,
        type & 4 ? 1 : 0
        /* State.Inactive */
      );
    let limit = tr.changes.mapPos(this.limit);
    if (checkValid(result.validFor, tr.state, from, to))
      return new _ActiveResult(this.source, this.explicit, limit, result, from, to);
    if (result.update && (result = result.update(result, from, to, new CompletionContext(tr.state, pos, false))))
      return new _ActiveResult(this.source, this.explicit, limit, result, result.from, (_a2 = result.to) !== null && _a2 !== void 0 ? _a2 : cur(tr.state));
    return new ActiveSource(this.source, 1, this.explicit);
  }
  map(mapping) {
    if (mapping.empty)
      return this;
    let result = this.result.map ? this.result.map(this.result, mapping) : this.result;
    if (!result)
      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(tr) {
    return tr.changes.touchesRange(this.from, this.to);
  }
};
function checkValid(validFor, state2, from, to) {
  if (!validFor)
    return false;
  let text2 = state2.sliceDoc(from, to);
  return typeof validFor == "function" ? validFor(text2, from, to, state2) : ensureAnchor(validFor, true).test(text2);
}
var setActiveEffect = /* @__PURE__ */ StateEffect.define({
  map(sources, mapping) {
    return sources.map((s) => s.map(mapping));
  }
});
var setSelectedEffect = /* @__PURE__ */ StateEffect.define();
var completionState = /* @__PURE__ */ StateField.define({
  create() {
    return CompletionState.start();
  },
  update(value, tr) {
    return value.update(tr);
  },
  provide: (f) => [
    showTooltip.from(f, (val) => val.tooltip),
    EditorView.contentAttributes.from(f, (state2) => state2.attrs)
  ]
});
function applyCompletion(view, option) {
  const apply2 = option.completion.apply || option.completion.label;
  let result = view.state.field(completionState).active.find((a) => a.source == option.source);
  if (!(result instanceof ActiveResult))
    return false;
  if (typeof apply2 == "string")
    view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply2, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
  else
    apply2(view, option.completion, result.from, result.to);
  return true;
}
var 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, tooltip2;
    if (by == "page" && (tooltip2 = getTooltip(view, cState.open.tooltip)))
      step = Math.max(2, Math.floor(tooltip2.dom.offsetHeight / tooltip2.dom.querySelector("li").offsetHeight) - 1);
    let { length } = cState.open.options;
    let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
    if (selected < 0)
      selected = by == "page" ? 0 : length - 1;
    else if (selected >= length)
      selected = by == "page" ? length - 1 : 0;
    view.dispatch({ effects: setSelectedEffect.of(selected) });
    return true;
  };
}
var 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]);
};
var startCompletion = (view) => {
  let cState = view.state.field(completionState, false);
  if (!cState)
    return false;
  view.dispatch({ effects: startCompletionEffect.of(true) });
  return true;
};
var 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;
};
var RunningQuery = class {
  constructor(active, context2) {
    this.active = active;
    this.context = context2;
    this.time = Date.now();
    this.updates = [];
    this.done = void 0;
  }
};
var MaxUpdateCount = 50;
var MinAbortTime = 1e3;
var 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 active of view.state.field(completionState).active)
      if (active.isPending)
        this.startQuery(active);
  }
  update(update3) {
    let cState = update3.state.field(completionState);
    let conf = update3.state.facet(completionConfig);
    if (!update3.selectionSet && !update3.docChanged && update3.startState.field(completionState) == cState)
      return;
    let doesReset = update3.transactions.some((tr) => {
      let type = getUpdateType(tr, conf);
      return type & 8 || (tr.selection || tr.docChanged) && !(type & 3);
    });
    for (let i2 = 0; i2 < this.running.length; i2++) {
      let query2 = this.running[i2];
      if (doesReset || query2.context.abortOnDocChange && update3.docChanged || query2.updates.length + update3.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(...update3.transactions);
      }
    }
    if (this.debounceUpdate > -1)
      clearTimeout(this.debounceUpdate);
    if (update3.transactions.some((tr) => tr.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 tr of update3.transactions) {
        if (tr.isUserEvent("input.type"))
          this.composing = 2;
        else if (this.composing == 2 && tr.selection)
          this.composing = 3;
      }
  }
  startUpdate() {
    this.debounceUpdate = -1;
    this.pendingStart = false;
    let { state: state2 } = this.view, cState = state2.field(completionState);
    for (let active of cState.active) {
      if (active.isPending && !this.running.some((r2) => r2.active.source == active.source))
        this.startQuery(active);
    }
    if (this.running.length && cState.open && cState.open.disabled)
      this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
  }
  startQuery(active) {
    let { state: state2 } = this.view, pos = cur(state2);
    let context2 = new CompletionContext(state2, pos, active.explicit, this.view);
    let pending2 = new RunningQuery(active, context2);
    this.running.push(pending2);
    Promise.resolve(active.source(context2)).then((result) => {
      if (!pending2.context.aborted) {
        pending2.done = result || null;
        this.scheduleAccept();
      }
    }, (err3) => {
      this.view.dispatch({ effects: closeCompletionEffect.of(null) });
      logException(this.view.state, err3);
    });
  }
  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 pos = cur(query2.updates.length ? query2.updates[0].startState : this.view.state);
        let limit = Math.min(pos, query2.done.from + (query2.active.explicit ? 0 : 1));
        let active = new ActiveResult(query2.active.source, query2.active.explicit, limit, query2.done, query2.done.from, (_a2 = query2.done.to) !== null && _a2 !== void 0 ? _a2 : pos);
        for (let tr of query2.updates)
          active = active.update(tr, conf);
        if (active.hasResult()) {
          updated.push(active);
          continue;
        }
      }
      let current = cState.active.find((a) => a.source == query2.active.source);
      if (current && current.isPending) {
        if (query2.done == null) {
          let active = new ActiveSource(
            query2.active.source,
            0
            /* State.Inactive */
          );
          for (let tr of query2.updates)
            active = active.update(tr, conf);
          if (!active.isPending)
            updated.push(active);
        } else {
          this.startQuery(current);
        }
      }
    }
    if (updated.length || cState.open && cState.open.disabled)
      this.view.dispatch({ effects: setActiveEffect.of(updated) });
  }
}, {
  eventHandlers: {
    blur(event2) {
      let state2 = this.view.state.field(completionState, false);
      if (state2 && state2.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
        let dialog = state2.open && getTooltip(this.view, state2.open.tooltip);
        if (!dialog || !dialog.dom.contains(event2.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;
    }
  }
});
var windows = typeof navigator == "object" && /* @__PURE__ */ /Win/.test(navigator.platform);
var commitCharacters = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.domEventHandlers({
  keydown(event2, view) {
    let field = view.state.field(completionState, false);
    if (!field || !field.open || field.open.disabled || field.open.selected < 0 || event2.key.length > 1 || event2.ctrlKey && !(windows && event2.altKey) || event2.metaKey)
      return false;
    let option = field.open.options[field.open.selected];
    let result = field.active.find((a) => a.source == option.source);
    let commitChars = option.completion.commitCharacters || result.result.commitCharacters;
    if (commitChars && commitChars.indexOf(event2.key) > -1)
      applyCompletion(view, option);
    return false;
  }
}));
var baseTheme3 = /* @__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: '"\xB7\xB7\xB7"',
    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: "'\u0192'" }
  },
  ".cm-completionIcon-class": {
    "&:after": { content: "'\u25CB'" }
  },
  ".cm-completionIcon-interface": {
    "&:after": { content: "'\u25CC'" }
  },
  ".cm-completionIcon-variable": {
    "&:after": { content: "'\u{1D465}'" }
  },
  ".cm-completionIcon-constant": {
    "&:after": { content: "'\u{1D436}'" }
  },
  ".cm-completionIcon-type": {
    "&:after": { content: "'\u{1D461}'" }
  },
  ".cm-completionIcon-enum": {
    "&:after": { content: "'\u222A'" }
  },
  ".cm-completionIcon-property": {
    "&:after": { content: "'\u25A1'" }
  },
  ".cm-completionIcon-keyword": {
    "&:after": { content: "'\u{1F511}\uFE0E'" }
    // Disable emoji rendering
  },
  ".cm-completionIcon-namespace": {
    "&:after": { content: "'\u25A2'" }
  },
  ".cm-completionIcon-text": {
    "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
  }
});
var FieldPos = class {
  constructor(field, line, from, to) {
    this.field = field;
    this.line = line;
    this.from = from;
    this.to = to;
  }
};
var FieldRange = class _FieldRange {
  constructor(field, from, to) {
    this.field = field;
    this.from = from;
    this.to = to;
  }
  map(changes) {
    let from = changes.mapPos(this.from, -1, MapMode.TrackDel);
    let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
    return from == null || to == null ? null : new _FieldRange(this.field, from, to);
  }
};
var Snippet = class _Snippet {
  constructor(lines, fieldPositions) {
    this.lines = lines;
    this.fieldPositions = fieldPositions;
  }
  instantiate(state2, pos) {
    let text2 = [], lineStart = [pos];
    let lineObj = state2.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
    for (let line of this.lines) {
      if (text2.length) {
        let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
        for (let i2 = 0; i2 < tabs; i2++)
          indent += state2.facet(indentUnit);
        lineStart.push(pos + indent.length - tabs);
        line = indent + line.slice(tabs);
      }
      text2.push(line);
      pos += line.length + 1;
    }
    let ranges = this.fieldPositions.map((pos2) => new FieldRange(pos2.field, lineStart[pos2.line] + pos2.from, lineStart[pos2.line] + pos2.to));
    return { text: text2, ranges };
  }
  static parse(template2) {
    let fields = [];
    let lines = [], positions = [], m2;
    for (let line of template2.split(/\r\n?|\n/)) {
      while (m2 = /[#$]\{(?:(\d+)(?::([^}]*))?|((?:\\[{}]|[^}])*))\}/.exec(line)) {
        let seq = m2[1] ? +m2[1] : null, rawName = m2[2] || m2[3] || "", found = -1;
        let name3 = rawName.replace(/\\[{}]/g, (m3) => m3[1]);
        for (let i2 = 0; i2 < fields.length; i2++) {
          if (seq != null ? fields[i2].seq == seq : name3 ? fields[i2].name == name3 : false)
            found = i2;
        }
        if (found < 0) {
          let i2 = 0;
          while (i2 < fields.length && (seq == null || fields[i2].seq != null && fields[i2].seq < seq))
            i2++;
          fields.splice(i2, 0, { seq, name: name3 });
          found = i2;
          for (let pos of positions)
            if (pos.field >= found)
              pos.field++;
        }
        positions.push(new FieldPos(found, lines.length, m2.index, m2.index + name3.length));
        line = line.slice(0, m2.index) + rawName + line.slice(m2.index + m2[0].length);
      }
      line = line.replace(/\\([{}])/g, (_2, brace, index3) => {
        for (let pos of positions)
          if (pos.line == lines.length && pos.from > index3) {
            pos.from--;
            pos.to--;
          }
        return brace;
      });
      lines.push(line);
    }
    return new _Snippet(lines, positions);
  }
};
var fieldMarker = /* @__PURE__ */ Decoration.widget({ widget: /* @__PURE__ */ new class extends WidgetType {
  toDOM() {
    let span = document.createElement("span");
    span.className = "cm-snippetFieldPosition";
    return span;
  }
  ignoreEvent() {
    return false;
  }
}() });
var fieldRange = /* @__PURE__ */ Decoration.mark({ class: "cm-snippetField" });
var ActiveSnippet = class _ActiveSnippet {
  constructor(ranges, active) {
    this.ranges = ranges;
    this.active = active;
    this.deco = Decoration.set(ranges.map((r2) => (r2.from == r2.to ? fieldMarker : fieldRange).range(r2.from, r2.to)));
  }
  map(changes) {
    let ranges = [];
    for (let r2 of this.ranges) {
      let mapped = r2.map(changes);
      if (!mapped)
        return null;
      ranges.push(mapped);
    }
    return new _ActiveSnippet(ranges, this.active);
  }
  selectionInsideField(sel) {
    return sel.ranges.every((range2) => this.ranges.some((r2) => r2.field == this.active && r2.from <= range2.from && r2.to >= range2.to));
  }
};
var setActive = /* @__PURE__ */ StateEffect.define({
  map(value, changes) {
    return value && value.map(changes);
  }
});
var moveToField = /* @__PURE__ */ StateEffect.define();
var snippetState = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(value, tr) {
    for (let effect2 of tr.effects) {
      if (effect2.is(setActive))
        return effect2.value;
      if (effect2.is(moveToField) && value)
        return new ActiveSnippet(value.ranges, effect2.value);
    }
    if (value && tr.docChanged)
      value = value.map(tr.changes);
    if (value && tr.selection && !value.selectionInsideField(tr.selection))
      value = null;
    return value;
  },
  provide: (f) => EditorView.decorations.from(f, (val) => val ? val.deco : Decoration.none)
});
function fieldSelection(ranges, field) {
  return EditorSelection.create(ranges.filter((r2) => r2.field == field).map((r2) => EditorSelection.range(r2.from, r2.to)));
}
function snippet2(template2) {
  let snippet3 = Snippet.parse(template2);
  return (editor2, completion, from, to) => {
    let { text: text2, ranges } = snippet3.instantiate(editor2.state, from);
    let { main } = editor2.state.selection;
    let spec = {
      changes: { from, to: to == main.from ? main.to : to, insert: Text2.of(text2) },
      scrollIntoView: true,
      annotations: completion ? [pickedCompletion.of(completion), Transaction2.userEvent.of("input.complete")] : void 0
    };
    if (ranges.length)
      spec.selection = fieldSelection(ranges, 0);
    if (ranges.some((r2) => r2.field > 0)) {
      let active = new ActiveSnippet(ranges, 0);
      let effects = spec.effects = [setActive.of(active)];
      if (editor2.state.field(snippetState, false) === void 0)
        effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme3]));
    }
    editor2.dispatch(editor2.state.update(spec));
  };
}
function moveField(dir) {
  return ({ state: state2, dispatch }) => {
    let active = state2.field(snippetState, false);
    if (!active || dir < 0 && active.active == 0)
      return false;
    let next2 = active.active + dir, last = dir > 0 && !active.ranges.some((r2) => r2.field == next2 + dir);
    dispatch(state2.update({
      selection: fieldSelection(active.ranges, next2),
      effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next2)),
      scrollIntoView: true
    }));
    return true;
  };
}
var clearSnippet = ({ state: state2, dispatch }) => {
  let active = state2.field(snippetState, false);
  if (!active)
    return false;
  dispatch(state2.update({ effects: setActive.of(null) }));
  return true;
};
var nextSnippetField = /* @__PURE__ */ moveField(1);
var prevSnippetField = /* @__PURE__ */ moveField(-1);
var defaultSnippetKeymap = [
  { key: "Tab", run: nextSnippetField, shift: prevSnippetField },
  { key: "Escape", run: clearSnippet }
];
var snippetKeymap = /* @__PURE__ */ Facet.define({
  combine(maps) {
    return maps.length ? maps[0] : defaultSnippetKeymap;
  }
});
var addSnippetKeymap = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ keymap.compute([snippetKeymap], (state2) => state2.facet(snippetKeymap)));
function snippetCompletion(template2, completion) {
  return Object.assign(Object.assign({}, completion), { apply: snippet2(template2) });
}
var snippetPointerHandler = /* @__PURE__ */ EditorView.domEventHandlers({
  mousedown(event2, view) {
    let active = view.state.field(snippetState, false), pos;
    if (!active || (pos = view.posAtCoords({ x: event2.clientX, y: event2.clientY })) == null)
      return false;
    let match = active.ranges.find((r2) => r2.from <= pos && r2.to >= pos);
    if (!match || match.field == active.active)
      return false;
    view.dispatch({
      selection: fieldSelection(active.ranges, match.field),
      effects: setActive.of(active.ranges.some((r2) => r2.field > match.field) ? new ActiveSnippet(active.ranges, match.field) : null),
      scrollIntoView: true
    });
    return true;
  }
});
var defaults2 = {
  brackets: ["(", "[", "{", "'", '"'],
  before: ")]}:;>",
  stringPrefixes: []
};
var closeBracketEffect = /* @__PURE__ */ StateEffect.define({
  map(value, mapping) {
    let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
    return mapped == null ? void 0 : mapped;
  }
});
var closedBracket = /* @__PURE__ */ new class extends RangeValue {
}();
closedBracket.startSide = 1;
closedBracket.endSide = -1;
var bracketState = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(value, tr) {
    value = value.map(tr.changes);
    if (tr.selection) {
      let line = tr.state.doc.lineAt(tr.selection.main.head);
      value = value.update({ filter: (from) => from >= line.from && from <= line.to });
    }
    for (let effect2 of tr.effects)
      if (effect2.is(closeBracketEffect))
        value = value.update({ add: [closedBracket.range(effect2.value, effect2.value + 1)] });
    return value;
  }
});
function closeBrackets() {
  return [inputHandler2, bracketState];
}
var definedClosing = "()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";
function closing(ch) {
  for (let i2 = 0; i2 < definedClosing.length; i2 += 2)
    if (definedClosing.charCodeAt(i2) == ch)
      return definedClosing.charAt(i2 + 1);
  return fromCodePoint(ch < 128 ? ch : ch + 1);
}
function config(state2, pos) {
  return state2.languageDataAt("closeBrackets", pos)[0] || defaults2;
}
var android = typeof navigator == "object" && /* @__PURE__ */ /Android\b/.test(navigator.userAgent);
var inputHandler2 = /* @__PURE__ */ EditorView.inputHandler.of((view, from, to, insert2) => {
  if ((android ? view.composing : view.compositionStarted) || view.state.readOnly)
    return false;
  let sel = view.state.selection.main;
  if (insert2.length > 2 || insert2.length == 2 && codePointSize2(codePointAt2(insert2, 0)) == 1 || from != sel.from || to != sel.to)
    return false;
  let tr = insertBracket(view.state, insert2);
  if (!tr)
    return false;
  view.dispatch(tr);
  return true;
});
var deleteBracketPair = ({ state: state2, dispatch }) => {
  if (state2.readOnly)
    return false;
  let conf = config(state2, state2.selection.main.head);
  let tokens = conf.brackets || defaults2.brackets;
  let dont = null, changes = state2.changeByRange((range2) => {
    if (range2.empty) {
      let before = prevChar(state2.doc, range2.head);
      for (let token of tokens) {
        if (token == before && nextChar(state2.doc, range2.head) == closing(codePointAt2(token, 0)))
          return {
            changes: { from: range2.head - token.length, to: range2.head + token.length },
            range: EditorSelection.cursor(range2.head - token.length)
          };
      }
    }
    return { range: dont = range2 };
  });
  if (!dont)
    dispatch(state2.update(changes, { scrollIntoView: true, userEvent: "delete.backward" }));
  return !dont;
};
var closeBracketsKeymap = [
  { key: "Backspace", run: deleteBracketPair }
];
function insertBracket(state2, bracket2) {
  let conf = config(state2, state2.selection.main.head);
  let tokens = conf.brackets || defaults2.brackets;
  for (let tok of tokens) {
    let closed = closing(codePointAt2(tok, 0));
    if (bracket2 == tok)
      return closed == tok ? handleSame(state2, tok, tokens.indexOf(tok + tok + tok) > -1, conf) : handleOpen(state2, tok, closed, conf.before || defaults2.before);
    if (bracket2 == closed && closedBracketAt(state2, state2.selection.main.from))
      return handleClose(state2, tok, closed);
  }
  return null;
}
function closedBracketAt(state2, pos) {
  let found = false;
  state2.field(bracketState).between(0, state2.doc.length, (from) => {
    if (from == pos)
      found = true;
  });
  return found;
}
function nextChar(doc2, pos) {
  let next2 = doc2.sliceString(pos, pos + 2);
  return next2.slice(0, codePointSize2(codePointAt2(next2, 0)));
}
function prevChar(doc2, pos) {
  let prev = doc2.sliceString(pos - 2, pos);
  return codePointSize2(codePointAt2(prev, 0)) == prev.length ? prev : prev.slice(1);
}
function handleOpen(state2, open, close, closeBefore) {
  let dont = null, changes = state2.changeByRange((range2) => {
    if (!range2.empty)
      return {
        changes: [{ insert: open, from: range2.from }, { insert: close, from: range2.to }],
        effects: closeBracketEffect.of(range2.to + open.length),
        range: EditorSelection.range(range2.anchor + open.length, range2.head + open.length)
      };
    let next2 = nextChar(state2.doc, range2.head);
    if (!next2 || /\s/.test(next2) || closeBefore.indexOf(next2) > -1)
      return {
        changes: { insert: open + close, from: range2.head },
        effects: closeBracketEffect.of(range2.head + open.length),
        range: EditorSelection.cursor(range2.head + open.length)
      };
    return { range: dont = range2 };
  });
  return dont ? null : state2.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function handleClose(state2, _open, close) {
  let dont = null, changes = state2.changeByRange((range2) => {
    if (range2.empty && nextChar(state2.doc, range2.head) == close)
      return {
        changes: { from: range2.head, to: range2.head + close.length, insert: close },
        range: EditorSelection.cursor(range2.head + close.length)
      };
    return dont = { range: range2 };
  });
  return dont ? null : state2.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function handleSame(state2, token, allowTriple, config2) {
  let stringPrefixes = config2.stringPrefixes || defaults2.stringPrefixes;
  let dont = null, changes = state2.changeByRange((range2) => {
    if (!range2.empty)
      return {
        changes: [{ insert: token, from: range2.from }, { insert: token, from: range2.to }],
        effects: closeBracketEffect.of(range2.to + token.length),
        range: EditorSelection.range(range2.anchor + token.length, range2.head + token.length)
      };
    let pos = range2.head, next2 = nextChar(state2.doc, pos), start2;
    if (next2 == token) {
      if (nodeStart(state2, pos)) {
        return {
          changes: { insert: token + token, from: pos },
          effects: closeBracketEffect.of(pos + token.length),
          range: EditorSelection.cursor(pos + token.length)
        };
      } else if (closedBracketAt(state2, pos)) {
        let isTriple = allowTriple && state2.sliceDoc(pos, pos + token.length * 3) == token + token + token;
        let content2 = isTriple ? token + token + token : token;
        return {
          changes: { from: pos, to: pos + content2.length, insert: content2 },
          range: EditorSelection.cursor(pos + content2.length)
        };
      }
    } else if (allowTriple && state2.sliceDoc(pos - 2 * token.length, pos) == token + token && (start2 = canStartStringAt(state2, pos - 2 * token.length, stringPrefixes)) > -1 && nodeStart(state2, start2)) {
      return {
        changes: { insert: token + token + token + token, from: pos },
        effects: closeBracketEffect.of(pos + token.length),
        range: EditorSelection.cursor(pos + token.length)
      };
    } else if (state2.charCategorizer(pos)(next2) != CharCategory.Word) {
      if (canStartStringAt(state2, pos, stringPrefixes) > -1 && !probablyInString(state2, pos, token, stringPrefixes))
        return {
          changes: { insert: token + token, from: pos },
          effects: closeBracketEffect.of(pos + token.length),
          range: EditorSelection.cursor(pos + token.length)
        };
    }
    return { range: dont = range2 };
  });
  return dont ? null : state2.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function nodeStart(state2, pos) {
  let tree = syntaxTree(state2).resolveInner(pos + 1);
  return tree.parent && tree.from == pos;
}
function probablyInString(state2, pos, quoteToken, prefixes2) {
  let node = syntaxTree(state2).resolveInner(pos, -1);
  let maxPrefix = prefixes2.reduce((m2, p) => Math.max(m2, p.length), 0);
  for (let i2 = 0; i2 < 5; i2++) {
    let start2 = state2.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
    let quotePos = start2.indexOf(quoteToken);
    if (!quotePos || quotePos > -1 && prefixes2.indexOf(start2.slice(0, quotePos)) > -1) {
      let first = node.firstChild;
      while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
        if (state2.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)
          return false;
        first = first.firstChild;
      }
      return true;
    }
    let parent2 = node.to == pos && node.parent;
    if (!parent2)
      break;
    node = parent2;
  }
  return false;
}
function canStartStringAt(state2, pos, prefixes2) {
  let charCat = state2.charCategorizer(pos);
  if (charCat(state2.sliceDoc(pos - 1, pos)) != CharCategory.Word)
    return pos;
  for (let prefix of prefixes2) {
    let start2 = pos - prefix.length;
    if (state2.sliceDoc(start2, pos) == prefix && charCat(state2.sliceDoc(start2 - 1, start2)) != CharCategory.Word)
      return start2;
  }
  return -1;
}
function autocompletion(config2 = {}) {
  return [
    commitCharacters,
    completionState,
    completionConfig.of(config2),
    completionPlugin,
    completionKeymapExt,
    baseTheme3
  ];
}
var 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 }
];
var completionKeymapExt = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ keymap.computeN([completionConfig], (state2) => state2.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));

// node_modules/@codemirror/commands/dist/index.js
var toggleComment = (target) => {
  let { state: state2 } = target, line = state2.doc.lineAt(state2.selection.main.from), config2 = getConfig(target.state, line.from);
  return config2.line ? toggleLineComment(target) : config2.block ? toggleBlockCommentByLine(target) : false;
};
function command(f, option) {
  return ({ state: state2, dispatch }) => {
    if (state2.readOnly)
      return false;
    let tr = f(option, state2);
    if (!tr)
      return false;
    dispatch(state2.update(tr));
    return true;
  };
}
var toggleLineComment = /* @__PURE__ */ command(
  changeLineComment,
  0
  /* CommentOption.Toggle */
);
var toggleBlockComment = /* @__PURE__ */ command(
  changeBlockComment,
  0
  /* CommentOption.Toggle */
);
var toggleBlockCommentByLine = /* @__PURE__ */ command(
  (o, s) => changeBlockComment(o, s, selectedLineRanges(s)),
  0
  /* CommentOption.Toggle */
);
function getConfig(state2, pos) {
  let data = state2.languageDataAt("commentTokens", pos);
  return data.length ? data[0] : {};
}
var SearchMargin = 50;
function findBlockComment(state2, { open, close }, from, to) {
  let textBefore = state2.sliceDoc(from - SearchMargin, from);
  let textAfter = state2.sliceDoc(to, to + 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 + close.length) == close) {
    return {
      open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
      close: { pos: to + spaceAfter, margin: spaceAfter && 1 }
    };
  }
  let startText, endText;
  if (to - from <= 2 * SearchMargin) {
    startText = endText = state2.sliceDoc(from, to);
  } else {
    startText = state2.sliceDoc(from, from + SearchMargin);
    endText = state2.sliceDoc(to - SearchMargin, to);
  }
  let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
  let endOff = endText.length - endSpace - close.length;
  if (startText.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close.length) == close) {
    return {
      open: {
        pos: from + startSpace + open.length,
        margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0
      },
      close: {
        pos: to - endSpace - close.length,
        margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0
      }
    };
  }
  return null;
}
function selectedLineRanges(state2) {
  let ranges = [];
  for (let r2 of state2.selection.ranges) {
    let fromLine = state2.doc.lineAt(r2.from);
    let toLine = r2.to <= fromLine.to ? fromLine : state2.doc.lineAt(r2.to);
    if (toLine.from > fromLine.from && toLine.from == r2.to)
      toLine = r2.to == fromLine.to + 1 ? fromLine : state2.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, state2, ranges = state2.selection.ranges) {
  let tokens = ranges.map((r2) => getConfig(state2, r2.from).block);
  if (!tokens.every((c) => c))
    return null;
  let comments = ranges.map((r2, i2) => findBlockComment(state2, tokens[i2], r2.from, r2.to));
  if (option != 2 && !comments.every((c) => c)) {
    return { changes: state2.changes(ranges.map((range2, i2) => {
      if (comments[i2])
        return [];
      return [{ from: range2.from, insert: tokens[i2].open + " " }, { from: range2.to, insert: " " + tokens[i2].close }];
    })) };
  } else if (option != 1 && comments.some((c) => c)) {
    let changes = [];
    for (let i2 = 0, comment3; i2 < comments.length; i2++)
      if (comment3 = comments[i2]) {
        let token = tokens[i2], { open, close } = comment3;
        changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
      }
    return { changes };
  }
  return null;
}
function changeLineComment(option, state2, ranges = state2.selection.ranges) {
  let lines = [];
  let prevLine = -1;
  for (let { from, to } of ranges) {
    let startI = lines.length, minIndent = 1e9;
    let token = getConfig(state2, from).line;
    if (!token)
      continue;
    for (let pos = from; pos <= to; ) {
      let line = state2.doc.lineAt(pos);
      if (line.from > prevLine && (from == to || to > line.from)) {
        prevLine = line.from;
        let indent = /^\s*/.exec(line.text)[0].length;
        let empty3 = indent == line.length;
        let comment3 = line.text.slice(indent, indent + token.length) == token ? indent : -1;
        if (indent < line.text.length && indent < minIndent)
          minIndent = indent;
        lines.push({ line, comment: comment3, token, indent, empty: empty3, single: false });
      }
      pos = line.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, token, indent, empty: empty3, single } of lines)
      if (single || !empty3)
        changes.push({ from: line.from + indent, insert: token + " " });
    let changeSet = state2.changes(changes);
    return { changes: changeSet, selection: state2.selection.map(changeSet, 1) };
  } else if (option != 1 && lines.some((l) => l.comment >= 0)) {
    let changes = [];
    for (let { line, comment: comment3, token } of lines)
      if (comment3 >= 0) {
        let from = line.from + comment3, to = from + token.length;
        if (line.text[to - line.from] == " ")
          to++;
        changes.push({ from, to });
      }
    return { changes };
  }
  return null;
}
var fromHistory = /* @__PURE__ */ Annotation.define();
var isolateHistory = /* @__PURE__ */ Annotation.define();
var invertedEffects = /* @__PURE__ */ Facet.define();
var historyConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      minDepth: 100,
      newGroupDelay: 500,
      joinToEvent: (_t, isAdjacent2) => isAdjacent2
    }, {
      minDepth: Math.max,
      newGroupDelay: Math.min,
      joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
    });
  }
});
var historyField_ = /* @__PURE__ */ StateField.define({
  create() {
    return HistoryState.empty;
  },
  update(state2, tr) {
    let config2 = tr.state.facet(historyConfig);
    let fromHist = tr.annotation(fromHistory);
    if (fromHist) {
      let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side;
      let other = from == 0 ? state2.undone : state2.done;
      if (item)
        other = updateBranch(other, other.length, config2.minDepth, item);
      else
        other = addSelection(other, tr.startState.selection);
      return new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest);
    }
    let isolate = tr.annotation(isolateHistory);
    if (isolate == "full" || isolate == "before")
      state2 = state2.isolate();
    if (tr.annotation(Transaction2.addToHistory) === false)
      return !tr.changes.empty ? state2.addMapping(tr.changes.desc) : state2;
    let event2 = HistEvent.fromTransaction(tr);
    let time = tr.annotation(Transaction2.time), userEvent = tr.annotation(Transaction2.userEvent);
    if (event2)
      state2 = state2.addChanges(event2, time, userEvent, config2, tr);
    else if (tr.selection)
      state2 = state2.addSelection(tr.startState.selection, time, userEvent, config2.newGroupDelay);
    if (isolate == "full" || isolate == "after")
      state2 = state2.isolate();
    return state2;
  },
  toJSON(value) {
    return { done: value.done.map((e) => e.toJSON()), undone: value.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, selection2) {
  return function({ state: state2, dispatch }) {
    if (!selection2 && state2.readOnly)
      return false;
    let historyState = state2.field(historyField_, false);
    if (!historyState)
      return false;
    let tr = historyState.pop(side, state2, selection2);
    if (!tr)
      return false;
    dispatch(tr);
    return true;
  };
}
var undo = /* @__PURE__ */ cmd(0, false);
var redo = /* @__PURE__ */ cmd(1, false);
var undoSelection = /* @__PURE__ */ cmd(0, true);
var redoSelection = /* @__PURE__ */ cmd(1, true);
var HistEvent = 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, _b, _c;
    return {
      changes: (_a2 = this.changes) === null || _a2 === void 0 ? void 0 : _a2.toJSON(),
      mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.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(tr, selection2) {
    let effects = none3;
    for (let invert of tr.startState.facet(invertedEffects)) {
      let result = invert(tr);
      if (result.length)
        effects = effects.concat(result);
    }
    if (!effects.length && tr.changes.empty)
      return null;
    return new _HistEvent(tr.changes.invert(tr.startState.doc), effects, void 0, selection2 || tr.startState.selection, none3);
  }
  static selection(selections) {
    return new _HistEvent(void 0, none3, void 0, void 0, selections);
  }
};
function updateBranch(branch2, to, maxLen, newEvent) {
  let start2 = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
  let newBranch = branch2.slice(start2, to);
  newBranch.push(newEvent);
  return newBranch;
}
function isAdjacent(a, b) {
  let ranges = [], isAdjacent2 = false;
  a.iterChangedRanges((f, t4) => ranges.push(f, t4));
  b.iterChangedRanges((_f, _t, f, t4) => {
    for (let i2 = 0; i2 < ranges.length; ) {
      let from = ranges[i2++], to = ranges[i2++];
      if (t4 >= from && f <= to)
        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);
}
var none3 = [];
var MaxSelectionsPerEvent = 200;
function addSelection(branch2, selection2) {
  if (!branch2.length) {
    return [HistEvent.selection([selection2])];
  } else {
    let lastEvent = branch2[branch2.length - 1];
    let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
    if (sels.length && sels[sels.length - 1].eq(selection2))
      return branch2;
    sels.push(selection2);
    return updateBranch(branch2, branch2.length - 1, 1e9, lastEvent.setSelAfter(sels));
  }
}
function popSelection(branch2) {
  let last = branch2[branch2.length - 1];
  let newBranch = branch2.slice();
  newBranch[branch2.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
  return newBranch;
}
function addMappingToBranch(branch2, mapping) {
  if (!branch2.length)
    return branch2;
  let length = branch2.length, selections = none3;
  while (length) {
    let event2 = mapEvent(branch2[length - 1], mapping, selections);
    if (event2.changes && !event2.changes.empty || event2.effects.length) {
      let result = branch2.slice(0, length);
      result[length - 1] = event2;
      return result;
    } else {
      mapping = event2.mapped;
      length--;
      selections = event2.selectionsAfter;
    }
  }
  return selections.length ? [HistEvent.selection(selections)] : none3;
}
function mapEvent(event2, mapping, extraSelections) {
  let selections = conc(event2.selectionsAfter.length ? event2.selectionsAfter.map((s) => s.map(mapping)) : none3, extraSelections);
  if (!event2.changes)
    return HistEvent.selection(selections);
  let mappedChanges = event2.changes.map(mapping), before = mapping.mapDesc(event2.changes, true);
  let fullMapping = event2.mapped ? event2.mapped.composeDesc(before) : before;
  return new HistEvent(mappedChanges, StateEffect.mapEffects(event2.effects, mapping), fullMapping, event2.startSelection.map(before), selections);
}
var joinableUserEvent = /^(input\.type|delete)($|\.)/;
var HistoryState = 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(event2, time, userEvent, config2, tr) {
    let done = this.done, lastEvent = done[done.length - 1];
    if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event2.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < config2.newGroupDelay && config2.joinToEvent(tr, isAdjacent(lastEvent.changes, event2.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(event2.changes.compose(lastEvent.changes), conc(StateEffect.mapEffects(event2.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none3));
    } else {
      done = updateBranch(done, done.length, config2.minDepth, event2);
    }
    return new _HistoryState(done, none3, time, userEvent);
  }
  addSelection(selection2, time, userEvent, newGroupDelay) {
    let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none3;
    if (last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection2))
      return this;
    return new _HistoryState(addSelection(this.done, selection2), this.undone, time, userEvent);
  }
  addMapping(mapping) {
    return new _HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
  }
  pop(side, state2, onlySelection) {
    let branch2 = side == 0 ? this.done : this.undone;
    if (branch2.length == 0)
      return null;
    let event2 = branch2[branch2.length - 1], selection2 = event2.selectionsAfter[0] || state2.selection;
    if (onlySelection && event2.selectionsAfter.length) {
      return state2.update({
        selection: event2.selectionsAfter[event2.selectionsAfter.length - 1],
        annotations: fromHistory.of({ side, rest: popSelection(branch2), selection: selection2 }),
        userEvent: side == 0 ? "select.undo" : "select.redo",
        scrollIntoView: true
      });
    } else if (!event2.changes) {
      return null;
    } else {
      let rest = branch2.length == 1 ? none3 : branch2.slice(0, branch2.length - 1);
      if (event2.mapped)
        rest = addMappingToBranch(rest, event2.mapped);
      return state2.update({
        changes: event2.changes,
        selection: event2.startSelection,
        effects: event2.effects,
        annotations: fromHistory.of({ side, rest, selection: selection2 }),
        filter: false,
        userEvent: side == 0 ? "undo" : "redo",
        scrollIntoView: true
      });
    }
  }
};
HistoryState.empty = /* @__PURE__ */ new HistoryState(none3, none3);
var 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(state2, selection2) {
  return state2.update({ selection: selection2, scrollIntoView: true, userEvent: "select" });
}
function moveSel({ state: state2, dispatch }, how) {
  let selection2 = updateSel(state2.selection, how);
  if (selection2.eq(state2.selection, true))
    return false;
  dispatch(setSel(state2, selection2));
  return true;
}
function rangeEnd(range2, forward) {
  return EditorSelection.cursor(forward ? range2.to : range2.from);
}
function cursorByChar(view, forward) {
  return moveSel(view, (range2) => range2.empty ? view.moveByChar(range2, forward) : rangeEnd(range2, forward));
}
function ltrAtCursor(view) {
  return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;
}
var cursorCharLeft = (view) => cursorByChar(view, !ltrAtCursor(view));
var cursorCharRight = (view) => cursorByChar(view, ltrAtCursor(view));
function cursorByGroup(view, forward) {
  return moveSel(view, (range2) => range2.empty ? view.moveByGroup(range2, forward) : rangeEnd(range2, forward));
}
var cursorGroupLeft = (view) => cursorByGroup(view, !ltrAtCursor(view));
var cursorGroupRight = (view) => cursorByGroup(view, ltrAtCursor(view));
var segmenter = typeof Intl != "undefined" && Intl.Segmenter ? /* @__PURE__ */ new Intl.Segmenter(void 0, { granularity: "word" }) : null;
function interestingNode(state2, node, bracketProp) {
  if (node.type.prop(bracketProp))
    return true;
  let len = node.to - node.from;
  return len && (len > 2 || /[^\s,.;:]/.test(state2.sliceDoc(node.from, node.to))) || node.firstChild;
}
function moveBySyntax(state2, start2, forward) {
  let pos = syntaxTree(state2).resolveInner(start2.head);
  let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
  for (let at = start2.head; ; ) {
    let next2 = forward ? pos.childAfter(at) : pos.childBefore(at);
    if (!next2)
      break;
    if (interestingNode(state2, next2, bracketProp))
      pos = next2;
    else
      at = forward ? next2.to : next2.from;
  }
  let bracket2 = pos.type.prop(bracketProp), match, newPos;
  if (bracket2 && (match = forward ? matchBrackets(state2, pos.from, 1) : matchBrackets(state2, pos.to, -1)) && match.matched)
    newPos = forward ? match.end.to : match.end.from;
  else
    newPos = forward ? pos.to : pos.from;
  return EditorSelection.cursor(newPos, forward ? -1 : 1);
}
var cursorSyntaxLeft = (view) => moveSel(view, (range2) => moveBySyntax(view.state, range2, !ltrAtCursor(view)));
var cursorSyntaxRight = (view) => moveSel(view, (range2) => moveBySyntax(view.state, range2, ltrAtCursor(view)));
function cursorByLine(view, forward) {
  return moveSel(view, (range2) => {
    if (!range2.empty)
      return rangeEnd(range2, forward);
    let moved = view.moveVertically(range2, forward);
    return moved.head != range2.head ? moved : view.moveToLineBoundary(range2, forward);
  });
}
var cursorLineUp = (view) => cursorByLine(view, false);
var 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 source3 of view.state.facet(EditorView.scrollMargins)) {
      let margins = source3(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: state2 } = view, selection2 = updateSel(state2.selection, (range2) => {
    return range2.empty ? view.moveVertically(range2, forward, page.height) : rangeEnd(range2, forward);
  });
  if (selection2.eq(state2.selection))
    return false;
  let effect2;
  if (page.selfScroll) {
    let startPos = view.coordsAtPos(state2.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)
      effect2 = EditorView.scrollIntoView(selection2.main.head, { y: "start", yMargin: startPos.top - scrollTop });
  }
  view.dispatch(setSel(state2, selection2), { effects: effect2 });
  return true;
}
var cursorPageUp = (view) => cursorByPage(view, false);
var cursorPageDown = (view) => cursorByPage(view, true);
function moveByLineBoundary(view, start2, forward) {
  let line = view.lineBlockAt(start2.head), moved = view.moveToLineBoundary(start2, forward);
  if (moved.head == start2.head && moved.head != (forward ? line.to : line.from))
    moved = view.moveToLineBoundary(start2, forward, false);
  if (!forward && moved.head == line.from && line.length) {
    let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
    if (space && start2.head != line.from + space)
      moved = EditorSelection.cursor(line.from + space);
  }
  return moved;
}
var cursorLineBoundaryForward = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, true));
var cursorLineBoundaryBackward = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, false));
var cursorLineBoundaryLeft = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, !ltrAtCursor(view)));
var cursorLineBoundaryRight = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, ltrAtCursor(view)));
var cursorLineStart = (view) => moveSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).from, 1));
var cursorLineEnd = (view) => moveSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).to, -1));
function toMatchingBracket(state2, dispatch, extend2) {
  let found = false, selection2 = updateSel(state2.selection, (range2) => {
    let matching = matchBrackets(state2, range2.head, -1) || matchBrackets(state2, range2.head, 1) || range2.head > 0 && matchBrackets(state2, range2.head - 1, 1) || range2.head < state2.doc.length && matchBrackets(state2, range2.head + 1, -1);
    if (!matching || !matching.end)
      return range2;
    found = true;
    let head2 = matching.start.from == range2.head ? matching.end.to : matching.end.from;
    return extend2 ? EditorSelection.range(range2.anchor, head2) : EditorSelection.cursor(head2);
  });
  if (!found)
    return false;
  dispatch(setSel(state2, selection2));
  return true;
}
var cursorMatchingBracket = ({ state: state2, dispatch }) => toMatchingBracket(state2, dispatch, false);
function extendSel(target, how) {
  let selection2 = updateSel(target.state.selection, (range2) => {
    let head2 = how(range2);
    return EditorSelection.range(range2.anchor, head2.head, head2.goalColumn, head2.bidiLevel || void 0);
  });
  if (selection2.eq(target.state.selection))
    return false;
  target.dispatch(setSel(target.state, selection2));
  return true;
}
function selectByChar(view, forward) {
  return extendSel(view, (range2) => view.moveByChar(range2, forward));
}
var selectCharLeft = (view) => selectByChar(view, !ltrAtCursor(view));
var selectCharRight = (view) => selectByChar(view, ltrAtCursor(view));
function selectByGroup(view, forward) {
  return extendSel(view, (range2) => view.moveByGroup(range2, forward));
}
var selectGroupLeft = (view) => selectByGroup(view, !ltrAtCursor(view));
var selectGroupRight = (view) => selectByGroup(view, ltrAtCursor(view));
var selectSyntaxLeft = (view) => extendSel(view, (range2) => moveBySyntax(view.state, range2, !ltrAtCursor(view)));
var selectSyntaxRight = (view) => extendSel(view, (range2) => moveBySyntax(view.state, range2, ltrAtCursor(view)));
function selectByLine(view, forward) {
  return extendSel(view, (range2) => view.moveVertically(range2, forward));
}
var selectLineUp = (view) => selectByLine(view, false);
var selectLineDown = (view) => selectByLine(view, true);
function selectByPage(view, forward) {
  return extendSel(view, (range2) => view.moveVertically(range2, forward, pageInfo(view).height));
}
var selectPageUp = (view) => selectByPage(view, false);
var selectPageDown = (view) => selectByPage(view, true);
var selectLineBoundaryForward = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, true));
var selectLineBoundaryBackward = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, false));
var selectLineBoundaryLeft = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, !ltrAtCursor(view)));
var selectLineBoundaryRight = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, ltrAtCursor(view)));
var selectLineStart = (view) => extendSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).from));
var selectLineEnd = (view) => extendSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).to));
var cursorDocStart = ({ state: state2, dispatch }) => {
  dispatch(setSel(state2, { anchor: 0 }));
  return true;
};
var cursorDocEnd = ({ state: state2, dispatch }) => {
  dispatch(setSel(state2, { anchor: state2.doc.length }));
  return true;
};
var selectDocStart = ({ state: state2, dispatch }) => {
  dispatch(setSel(state2, { anchor: state2.selection.main.anchor, head: 0 }));
  return true;
};
var selectDocEnd = ({ state: state2, dispatch }) => {
  dispatch(setSel(state2, { anchor: state2.selection.main.anchor, head: state2.doc.length }));
  return true;
};
var selectAll = ({ state: state2, dispatch }) => {
  dispatch(state2.update({ selection: { anchor: 0, head: state2.doc.length }, userEvent: "select" }));
  return true;
};
var selectLine = ({ state: state2, dispatch }) => {
  let ranges = selectedLineBlocks(state2).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state2.doc.length)));
  dispatch(state2.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
  return true;
};
var selectParentSyntax = ({ state: state2, dispatch }) => {
  let selection2 = updateSel(state2.selection, (range2) => {
    let tree = syntaxTree(state2), stack2 = tree.resolveStack(range2.from, 1);
    if (range2.empty) {
      let stackBefore = tree.resolveStack(range2.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 } = cur2;
      if ((node.from < range2.from && node.to >= range2.to || node.to > range2.to && node.from <= range2.from) && cur2.next)
        return EditorSelection.range(node.to, node.from);
    }
    return range2;
  });
  if (selection2.eq(state2.selection))
    return false;
  dispatch(setSel(state2, selection2));
  return true;
};
var simplifySelection = ({ state: state2, dispatch }) => {
  let cur2 = state2.selection, selection2 = null;
  if (cur2.ranges.length > 1)
    selection2 = EditorSelection.create([cur2.main]);
  else if (!cur2.main.empty)
    selection2 = EditorSelection.create([EditorSelection.cursor(cur2.main.head)]);
  if (!selection2)
    return false;
  dispatch(setSel(state2, selection2));
  return true;
};
function deleteBy(target, by) {
  if (target.state.readOnly)
    return false;
  let event2 = "delete.selection", { state: state2 } = target;
  let changes = state2.changeByRange((range2) => {
    let { from, to } = range2;
    if (from == to) {
      let towards = by(range2);
      if (towards < from) {
        event2 = "delete.backward";
        towards = skipAtomic(target, towards, false);
      } else if (towards > from) {
        event2 = "delete.forward";
        towards = skipAtomic(target, towards, true);
      }
      from = Math.min(from, towards);
      to = Math.max(to, towards);
    } else {
      from = skipAtomic(target, from, false);
      to = skipAtomic(target, to, true);
    }
    return from == to ? { range: range2 } : { changes: { from, to }, range: EditorSelection.cursor(from, from < range2.head ? -1 : 1) };
  });
  if (changes.changes.empty)
    return false;
  target.dispatch(state2.update(changes, {
    scrollIntoView: true,
    userEvent: event2,
    effects: event2 == "delete.selection" ? EditorView.announce.of(state2.phrase("Selection deleted")) : void 0
  }));
  return true;
}
function skipAtomic(target, pos, forward) {
  if (target instanceof EditorView)
    for (let ranges of target.state.facet(EditorView.atomicRanges).map((f) => f(target)))
      ranges.between(pos, pos, (from, to) => {
        if (from < pos && to > pos)
          pos = forward ? to : from;
      });
  return pos;
}
var deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, (range2) => {
  let pos = range2.from, { state: state2 } = target, line = state2.doc.lineAt(pos), before, targetPos;
  if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 && !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
    if (before[before.length - 1] == "	")
      return pos - 1;
    let col = countColumn(before, state2.tabSize), drop2 = col % getIndentUnit(state2) || getIndentUnit(state2);
    for (let i2 = 0; i2 < drop2 && before[before.length - 1 - i2] == " "; i2++)
      pos--;
    targetPos = pos;
  } else {
    targetPos = findClusterBreak2(line.text, pos - line.from, forward, forward) + line.from;
    if (targetPos == pos && line.number != (forward ? state2.doc.lines : 1))
      targetPos += forward ? 1 : -1;
    else if (!forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)))
      targetPos = findClusterBreak2(line.text, targetPos - line.from, false, false) + line.from;
  }
  return targetPos;
});
var deleteCharBackward = (view) => deleteByChar(view, false, true);
var deleteCharForward = (view) => deleteByChar(view, true, false);
var deleteByGroup = (target, forward) => deleteBy(target, (range2) => {
  let pos = range2.head, { state: state2 } = target, line = state2.doc.lineAt(pos);
  let categorize = state2.charCategorizer(pos);
  for (let cat = null; ; ) {
    if (pos == (forward ? line.to : line.from)) {
      if (pos == range2.head && line.number != (forward ? state2.doc.lines : 1))
        pos += forward ? 1 : -1;
      break;
    }
    let next2 = findClusterBreak2(line.text, pos - line.from, forward) + line.from;
    let nextChar2 = line.text.slice(Math.min(pos, next2) - line.from, Math.max(pos, next2) - line.from);
    let nextCat = categorize(nextChar2);
    if (cat != null && nextCat != cat)
      break;
    if (nextChar2 != " " || pos != range2.head)
      cat = nextCat;
    pos = next2;
  }
  return pos;
});
var deleteGroupBackward = (target) => deleteByGroup(target, false);
var deleteGroupForward = (target) => deleteByGroup(target, true);
var deleteToLineEnd = (view) => deleteBy(view, (range2) => {
  let lineEnd = view.lineBlockAt(range2.head).to;
  return range2.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range2.head + 1);
});
var deleteLineBoundaryBackward = (view) => deleteBy(view, (range2) => {
  let lineStart = view.moveToLineBoundary(range2, false).head;
  return range2.head > lineStart ? lineStart : Math.max(0, range2.head - 1);
});
var deleteLineBoundaryForward = (view) => deleteBy(view, (range2) => {
  let lineStart = view.moveToLineBoundary(range2, true).head;
  return range2.head < lineStart ? lineStart : Math.min(view.state.doc.length, range2.head + 1);
});
var splitLine = ({ state: state2, dispatch }) => {
  if (state2.readOnly)
    return false;
  let changes = state2.changeByRange((range2) => {
    return {
      changes: { from: range2.from, to: range2.to, insert: Text2.of(["", ""]) },
      range: EditorSelection.cursor(range2.from)
    };
  });
  dispatch(state2.update(changes, { scrollIntoView: true, userEvent: "input" }));
  return true;
};
var transposeChars = ({ state: state2, dispatch }) => {
  if (state2.readOnly)
    return false;
  let changes = state2.changeByRange((range2) => {
    if (!range2.empty || range2.from == 0 || range2.from == state2.doc.length)
      return { range: range2 };
    let pos = range2.from, line = state2.doc.lineAt(pos);
    let from = pos == line.from ? pos - 1 : findClusterBreak2(line.text, pos - line.from, false) + line.from;
    let to = pos == line.to ? pos + 1 : findClusterBreak2(line.text, pos - line.from, true) + line.from;
    return {
      changes: { from, to, insert: state2.doc.slice(pos, to).append(state2.doc.slice(from, pos)) },
      range: EditorSelection.cursor(to)
    };
  });
  if (changes.changes.empty)
    return false;
  dispatch(state2.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
  return true;
};
function selectedLineBlocks(state2) {
  let blocks = [], upto = -1;
  for (let range2 of state2.selection.ranges) {
    let startLine = state2.doc.lineAt(range2.from), endLine = state2.doc.lineAt(range2.to);
    if (!range2.empty && range2.to == endLine.from)
      endLine = state2.doc.lineAt(range2.to - 1);
    if (upto >= startLine.number) {
      let prev = blocks[blocks.length - 1];
      prev.to = endLine.to;
      prev.ranges.push(range2);
    } else {
      blocks.push({ from: startLine.from, to: endLine.to, ranges: [range2] });
    }
    upto = endLine.number + 1;
  }
  return blocks;
}
function moveLine(state2, dispatch, forward) {
  if (state2.readOnly)
    return false;
  let changes = [], ranges = [];
  for (let block2 of selectedLineBlocks(state2)) {
    if (forward ? block2.to == state2.doc.length : block2.from == 0)
      continue;
    let nextLine = state2.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 + state2.lineBreak });
      for (let r2 of block2.ranges)
        ranges.push(EditorSelection.range(Math.min(state2.doc.length, r2.anchor + size), Math.min(state2.doc.length, r2.head + size)));
    } else {
      changes.push({ from: nextLine.from, to: block2.from }, { from: block2.to, insert: state2.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(state2.update({
    changes,
    scrollIntoView: true,
    selection: EditorSelection.create(ranges, state2.selection.mainIndex),
    userEvent: "move.line"
  }));
  return true;
}
var moveLineUp = ({ state: state2, dispatch }) => moveLine(state2, dispatch, false);
var moveLineDown = ({ state: state2, dispatch }) => moveLine(state2, dispatch, true);
function copyLine(state2, dispatch, forward) {
  if (state2.readOnly)
    return false;
  let changes = [];
  for (let block2 of selectedLineBlocks(state2)) {
    if (forward)
      changes.push({ from: block2.from, insert: state2.doc.slice(block2.from, block2.to) + state2.lineBreak });
    else
      changes.push({ from: block2.to, insert: state2.lineBreak + state2.doc.slice(block2.from, block2.to) });
  }
  dispatch(state2.update({ changes, scrollIntoView: true, userEvent: "input.copyline" }));
  return true;
}
var copyLineUp = ({ state: state2, dispatch }) => copyLine(state2, dispatch, false);
var copyLineDown = ({ state: state2, dispatch }) => copyLine(state2, dispatch, true);
var deleteLine = (view) => {
  if (view.state.readOnly)
    return false;
  let { state: state2 } = view, changes = state2.changes(selectedLineBlocks(state2).map(({ from, to }) => {
    if (from > 0)
      from--;
    else if (to < state2.doc.length)
      to++;
    return { from, to };
  }));
  let selection2 = updateSel(state2.selection, (range2) => {
    let dist2 = void 0;
    if (view.lineWrapping) {
      let block2 = view.lineBlockAt(range2.head), pos = view.coordsAtPos(range2.head, range2.assoc || 1);
      if (pos)
        dist2 = block2.bottom + view.documentTop - pos.bottom + view.defaultLineHeight / 2;
    }
    return view.moveVertically(range2, true, dist2);
  }).map(changes);
  view.dispatch({ changes, selection: selection2, scrollIntoView: true, userEvent: "delete.line" });
  return true;
};
function isBetweenBrackets(state2, pos) {
  if (/\(\)|\[\]|\{\}/.test(state2.sliceDoc(pos - 1, pos + 1)))
    return { from: pos, to: pos };
  let context2 = syntaxTree(state2).resolveInner(pos);
  let before = context2.childBefore(pos), after = context2.childAfter(pos), closedBy;
  if (before && after && before.to <= pos && after.from >= pos && (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && state2.doc.lineAt(before.to).from == state2.doc.lineAt(after.from).from && !/\S/.test(state2.sliceDoc(before.to, after.from)))
    return { from: before.to, to: after.from };
  return null;
}
var insertNewlineAndIndent = /* @__PURE__ */ newlineAndIndent(false);
var insertBlankLine = /* @__PURE__ */ newlineAndIndent(true);
function newlineAndIndent(atEof) {
  return ({ state: state2, dispatch }) => {
    if (state2.readOnly)
      return false;
    let changes = state2.changeByRange((range2) => {
      let { from, to } = range2, line = state2.doc.lineAt(from);
      let explode = !atEof && from == to && isBetweenBrackets(state2, from);
      if (atEof)
        from = to = (to <= line.to ? line : state2.doc.lineAt(to)).to;
      let cx = new IndentContext(state2, { simulateBreak: from, simulateDoubleBreak: !!explode });
      let indent = getIndentation(cx, from);
      if (indent == null)
        indent = countColumn(/^\s*/.exec(state2.doc.lineAt(from).text)[0], state2.tabSize);
      while (to < line.to && /\s/.test(line.text[to - line.from]))
        to++;
      if (explode)
        ({ from, to } = explode);
      else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
        from = line.from;
      let insert2 = ["", indentString(state2, indent)];
      if (explode)
        insert2.push(indentString(state2, cx.lineIndent(line.from, -1)));
      return {
        changes: { from, to, insert: Text2.of(insert2) },
        range: EditorSelection.cursor(from + 1 + insert2[1].length)
      };
    });
    dispatch(state2.update(changes, { scrollIntoView: true, userEvent: "input" }));
    return true;
  };
}
function changeBySelectedLine(state2, f) {
  let atLine = -1;
  return state2.changeByRange((range2) => {
    let changes = [];
    for (let pos = range2.from; pos <= range2.to; ) {
      let line = state2.doc.lineAt(pos);
      if (line.number > atLine && (range2.empty || range2.to > line.from)) {
        f(line, changes, range2);
        atLine = line.number;
      }
      pos = line.to + 1;
    }
    let changeSet = state2.changes(changes);
    return {
      changes,
      range: EditorSelection.range(changeSet.mapPos(range2.anchor, 1), changeSet.mapPos(range2.head, 1))
    };
  });
}
var indentSelection = ({ state: state2, dispatch }) => {
  if (state2.readOnly)
    return false;
  let updated = /* @__PURE__ */ Object.create(null);
  let context2 = new IndentContext(state2, { overrideIndentation: (start2) => {
    let found = updated[start2];
    return found == null ? -1 : found;
  } });
  let changes = changeBySelectedLine(state2, (line, changes2, range2) => {
    let indent = getIndentation(context2, line.from);
    if (indent == null)
      return;
    if (!/\S/.test(line.text))
      indent = 0;
    let cur2 = /^\s*/.exec(line.text)[0];
    let norm = indentString(state2, indent);
    if (cur2 != norm || range2.from < line.from + cur2.length) {
      updated[line.from] = indent;
      changes2.push({ from: line.from, to: line.from + cur2.length, insert: norm });
    }
  });
  if (!changes.changes.empty)
    dispatch(state2.update(changes, { userEvent: "indent" }));
  return true;
};
var indentMore = ({ state: state2, dispatch }) => {
  if (state2.readOnly)
    return false;
  dispatch(state2.update(changeBySelectedLine(state2, (line, changes) => {
    changes.push({ from: line.from, insert: state2.facet(indentUnit) });
  }), { userEvent: "input.indent" }));
  return true;
};
var indentLess = ({ state: state2, dispatch }) => {
  if (state2.readOnly)
    return false;
  dispatch(state2.update(changeBySelectedLine(state2, (line, changes) => {
    let space = /^\s*/.exec(line.text)[0];
    if (!space)
      return;
    let col = countColumn(space, state2.tabSize), keep = 0;
    let insert2 = indentString(state2, Math.max(0, col - getIndentUnit(state2)));
    while (keep < space.length && keep < insert2.length && space.charCodeAt(keep) == insert2.charCodeAt(keep))
      keep++;
    changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert2.slice(keep) });
  }), { userEvent: "delete.dedent" }));
  return true;
};
var toggleTabFocusMode = (view) => {
  view.setTabFocusMode();
  return true;
};
var 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 }
];
var 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 })));
var 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);
var indentWithTab = { key: "Tab", run: indentMore, shift: indentLess };

// node_modules/crelt/index.js
function crelt() {
  var elt = arguments[0];
  if (typeof elt == "string") elt = document.createElement(elt);
  var i2 = 1, next2 = arguments[1];
  if (next2 && typeof next2 == "object" && next2.nodeType == null && !Array.isArray(next2)) {
    for (var name3 in next2) if (Object.prototype.hasOwnProperty.call(next2, name3)) {
      var value = next2[name3];
      if (typeof value == "string") elt.setAttribute(name3, value);
      else if (value != null) elt[name3] = value;
    }
    i2++;
  }
  for (; i2 < arguments.length; i2++) add(elt, arguments[i2]);
  return elt;
}
function add(elt, child2) {
  if (typeof child2 == "string") {
    elt.appendChild(document.createTextNode(child2));
  } else if (child2 == null) {
  } else if (child2.nodeType != null) {
    elt.appendChild(child2);
  } else if (Array.isArray(child2)) {
    for (var i2 = 0; i2 < child2.length; i2++) add(elt, child2[i2]);
  } else {
    throw new RangeError("Unsupported child node: " + child2);
  }
}

// node_modules/@codemirror/lint/dist/index.js
var SelectedDiagnostic = class {
  constructor(from, to, diagnostic) {
    this.from = from;
    this.to = to;
    this.diagnostic = diagnostic;
  }
};
var LintState = class _LintState {
  constructor(diagnostics, panel, selected) {
    this.diagnostics = diagnostics;
    this.panel = panel;
    this.selected = selected;
  }
  static init(diagnostics, panel, state2) {
    let markedDiagnostics = diagnostics;
    let diagnosticFilter = state2.facet(lintConfig).markerFilter;
    if (diagnosticFilter)
      markedDiagnostics = diagnosticFilter(markedDiagnostics, state2);
    let sorted = diagnostics.slice().sort((a, b) => a.from - b.from || a.to - b.to);
    let deco = new RangeSetBuilder(), active = [], pos = 0;
    for (let i2 = 0; ; ) {
      let next2 = i2 == sorted.length ? null : sorted[i2];
      if (!next2 && !active.length)
        break;
      let from, to;
      if (active.length) {
        from = pos;
        to = active.reduce((p, d) => Math.min(p, d.to), next2 && next2.from > from ? next2.from : 1e8);
      } else {
        from = next2.from;
        to = next2.to;
        active.push(next2);
        i2++;
      }
      while (i2 < sorted.length) {
        let next3 = sorted[i2];
        if (next3.from == from && (next3.to > next3.from || next3.to == from)) {
          active.push(next3);
          i2++;
          to = Math.min(next3.to, to);
        } else {
          to = Math.min(next3.from, to);
          break;
        }
      }
      let sev = maxSeverity(active);
      if (active.some((d) => d.from == d.to || d.from == d.to - 1 && state2.doc.lineAt(d.from).to == d.from)) {
        deco.add(from, from, Decoration.widget({
          widget: new DiagnosticWidget(sev),
          diagnostics: active.slice()
        }));
      } else {
        let markClass = active.reduce((c, d) => d.markClass ? c + " " + d.markClass : c, "");
        deco.add(from, to, Decoration.mark({
          class: "cm-lintRange cm-lintRange-" + sev + markClass,
          diagnostics: active.slice(),
          inclusiveEnd: active.some((a) => a.to > to)
        }));
      }
      pos = to;
      for (let i3 = 0; i3 < active.length; i3++)
        if (active[i3].to <= pos)
          active.splice(i3--, 1);
    }
    let set4 = deco.finish();
    return new _LintState(set4, panel, findDiagnostic(set4));
  }
};
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
  let found = null;
  diagnostics.between(after, 1e9, (from, to, { spec }) => {
    if (diagnostic && spec.diagnostics.indexOf(diagnostic) < 0)
      return;
    if (!found)
      found = new SelectedDiagnostic(from, to, diagnostic || spec.diagnostics[0]);
    else if (spec.diagnostics.indexOf(found.diagnostic) < 0)
      return false;
    else
      found = new SelectedDiagnostic(found.from, to, found.diagnostic);
  });
  return found;
}
function hideTooltip(tr, tooltip2) {
  let from = tooltip2.pos, to = tooltip2.end || from;
  let result = tr.state.facet(lintConfig).hideOn(tr, from, to);
  if (result != null)
    return result;
  let line = tr.startState.doc.lineAt(tooltip2.pos);
  return !!(tr.effects.some((e) => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(line.from, Math.max(line.to, to)));
}
function maybeEnableLint(state2, effects) {
  return state2.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of(lintExtensions));
}
function setDiagnostics(state2, diagnostics) {
  return {
    effects: maybeEnableLint(state2, [setDiagnosticsEffect.of(diagnostics)])
  };
}
var setDiagnosticsEffect = /* @__PURE__ */ StateEffect.define();
var togglePanel = /* @__PURE__ */ StateEffect.define();
var movePanelSelection = /* @__PURE__ */ StateEffect.define();
var lintState = /* @__PURE__ */ StateField.define({
  create() {
    return new LintState(Decoration.none, null, null);
  },
  update(value, tr) {
    if (tr.docChanged && value.diagnostics.size) {
      let mapped = value.diagnostics.map(tr.changes), selected = null, panel = value.panel;
      if (value.selected) {
        let selPos = tr.changes.mapPos(value.selected.from, 1);
        selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
      }
      if (!mapped.size && panel && tr.state.facet(lintConfig).autoPanel)
        panel = null;
      value = new LintState(mapped, panel, selected);
    }
    for (let effect2 of tr.effects) {
      if (effect2.is(setDiagnosticsEffect)) {
        let panel = !tr.state.facet(lintConfig).autoPanel ? value.panel : effect2.value.length ? LintPanel.open : null;
        value = LintState.init(effect2.value, panel, tr.state);
      } else if (effect2.is(togglePanel)) {
        value = new LintState(value.diagnostics, effect2.value ? LintPanel.open : null, value.selected);
      } else if (effect2.is(movePanelSelection)) {
        value = new LintState(value.diagnostics, value.panel, effect2.value);
      }
    }
    return value;
  },
  provide: (f) => [
    showPanel.from(f, (val) => val.panel),
    EditorView.decorations.from(f, (s) => s.diagnostics)
  ]
});
var activeMark = /* @__PURE__ */ Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
function lintTooltip(view, pos, side) {
  let { diagnostics } = view.state.field(lintState);
  let found, start2 = -1, end = -1;
  diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
    if (pos >= from && pos <= to && (from == to || (pos > from || side > 0) && (pos < to || side < 0))) {
      found = spec.diagnostics;
      start2 = from;
      end = to;
      return false;
    }
  });
  let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
  if (found && diagnosticFilter)
    found = diagnosticFilter(found, view.state);
  if (!found)
    return null;
  return {
    pos: start2,
    end,
    above: view.state.doc.lineAt(start2).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)));
}
var openLintPanel = (view) => {
  let field = view.state.field(lintState, false);
  if (!field || !field.panel)
    view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) });
  let panel = getPanel(view, LintPanel.open);
  if (panel)
    panel.dom.querySelector(".cm-panel-lint ul").focus();
  return true;
};
var closeLintPanel = (view) => {
  let field = view.state.field(lintState, false);
  if (!field || !field.panel)
    return false;
  view.dispatch({ effects: togglePanel.of(false) });
  return true;
};
var nextDiagnostic = (view) => {
  let field = view.state.field(lintState, false);
  if (!field)
    return false;
  let sel = view.state.selection.main, next2 = field.diagnostics.iter(sel.to + 1);
  if (!next2.value) {
    next2 = field.diagnostics.iter(0);
    if (!next2.value || next2.from == sel.from && next2.to == sel.to)
      return false;
  }
  view.dispatch({ selection: { anchor: next2.from, head: next2.to }, scrollIntoView: true });
  return true;
};
var lintKeymap = [
  { key: "Mod-Shift-m", run: openLintPanel, preventDefault: true },
  { key: "F8", run: nextDiagnostic }
];
var lintConfig = /* @__PURE__ */ Facet.define({
  combine(input) {
    return Object.assign({ sources: input.map((i2) => i2.source).filter((x2) => x2 != null) }, combineConfig(input.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 assignKeys(actions) {
  let assigned = [];
  if (actions)
    actions: for (let { name: name3 } of actions) {
      for (let i2 = 0; i2 < name3.length; i2++) {
        let ch = name3[i2];
        if (/[a-zA-Z]/.test(ch) && !assigned.some((c) => c.toLowerCase() == ch.toLowerCase())) {
          assigned.push(ch);
          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((action2, i2) => {
    let fired = false, click = (e) => {
      e.preventDefault();
      if (fired)
        return;
      fired = true;
      let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
      if (found)
        action2.apply(view, found.from, found.to);
    };
    let { name: name3 } = action2, keyIndex = keys[i2] ? name3.indexOf(keys[i2]) : -1;
    let nameElt = keyIndex < 0 ? name3 : [
      name3.slice(0, keyIndex),
      crelt("u", name3.slice(keyIndex, keyIndex + 1)),
      name3.slice(keyIndex + 1)
    ];
    return crelt("button", {
      type: "button",
      class: "cm-diagnosticAction",
      onclick: click,
      onmousedown: click,
      "aria-label": ` Action: ${name3}${keyIndex < 0 ? "" : ` (access key "${keys[i2]})"`}.`
    }, nameElt);
  }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source));
}
var DiagnosticWidget = class 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 });
  }
};
var PanelItem = class {
  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");
  }
};
var LintPanel = class _LintPanel {
  constructor(view) {
    this.view = view;
    this.items = [];
    let onkeydown = (event2) => {
      if (event2.keyCode == 27) {
        closeLintPanel(this.view);
        this.view.focus();
      } else if (event2.keyCode == 38 || event2.keyCode == 33) {
        this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
      } else if (event2.keyCode == 40 || event2.keyCode == 34) {
        this.moveSelection((this.selectedIndex + 1) % this.items.length);
      } else if (event2.keyCode == 36) {
        this.moveSelection(0);
      } else if (event2.keyCode == 35) {
        this.moveSelection(this.items.length - 1);
      } else if (event2.keyCode == 13) {
        this.view.focus();
      } else if (event2.keyCode >= 65 && event2.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) == event2.keyCode) {
            let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
            if (found)
              diagnostic.actions[i2].apply(view, found.from, found.to);
          }
      } else {
        return;
      }
      event2.preventDefault();
    };
    let onclick = (event2) => {
      for (let i2 = 0; i2 < this.items.length; i2++) {
        if (this.items[i2].dom.contains(event2.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)
    }, "\xD7"));
    this.update();
  }
  get selectedIndex() {
    let selected = this.view.state.field(lintState).selected;
    if (!selected)
      return -1;
    for (let i2 = 0; i2 < this.items.length; i2++)
      if (this.items[i2].diagnostic == selected.diagnostic)
        return i2;
    return -1;
  }
  update() {
    let { diagnostics, selected } = 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, item;
        for (let j = i2; j < this.items.length; j++)
          if (this.items[j].diagnostic == diagnostic) {
            found = j;
            break;
          }
        if (found < 0) {
          item = new PanelItem(this.view, diagnostic);
          this.items.splice(i2, 0, item);
          needsSync = true;
        } else {
          item = this.items[found];
          if (found > i2) {
            this.items.splice(i2, found - i2);
            needsSync = true;
          }
        }
        if (selected && item.diagnostic == selected.diagnostic) {
          if (!item.dom.hasAttribute("aria-selected")) {
            item.dom.setAttribute("aria-selected", "true");
            newSelectedItem = item;
          }
        } else if (item.dom.hasAttribute("aria-selected")) {
          item.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 }) => {
          let scaleY = panel.height / this.list.offsetHeight;
          if (sel.top < panel.top)
            this.list.scrollTop -= (panel.top - sel.top) / scaleY;
          else if (sel.bottom > panel.bottom)
            this.list.scrollTop += (sel.bottom - panel.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 item of this.items) {
      if (item.dom.parentNode == this.list) {
        while (domPos != item.dom)
          rm2();
        domPos = item.dom.nextSibling;
      } else {
        this.list.insertBefore(item.dom, domPos);
      }
    }
    while (domPos)
      rm2();
  }
  moveSelection(selectedIndex) {
    if (this.selectedIndex < 0)
      return;
    let field = this.view.state.field(lintState);
    let selection2 = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
    if (!selection2)
      return;
    this.view.dispatch({
      selection: { anchor: selection2.from, head: selection2.to },
      scrollIntoView: true,
      effects: movePanelSelection.of(selection2)
    });
  }
  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(color2) {
  return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color2}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
}
var baseTheme4 = /* @__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 w = severityWeight(d.severity);
    if (w > weight) {
      weight = w;
      sev = d.severity;
    }
  }
  return sev;
}
var LintGutterMarker = class extends GutterMarker {
  constructor(diagnostics) {
    super();
    this.diagnostics = diagnostics;
    this.severity = maxSeverity(diagnostics);
  }
  toDOM(view) {
    let elt = document.createElement("div");
    elt.className = "cm-lint-marker cm-lint-marker-" + this.severity;
    let diagnostics = this.diagnostics;
    let diagnosticsFilter = view.state.facet(lintGutterConfig).tooltipFilter;
    if (diagnosticsFilter)
      diagnostics = diagnosticsFilter(diagnostics, view.state);
    if (diagnostics.length)
      elt.onmouseover = () => gutterMarkerMouseOver(view, elt, diagnostics);
    return elt;
  }
};
function trackHoverOn(view, marker) {
  let mousemove2 = (event2) => {
    let rect = marker.getBoundingClientRect();
    if (event2.clientX > rect.left - 10 && event2.clientX < rect.right + 10 && event2.clientY > rect.top - 10 && event2.clientY < rect.bottom + 10)
      return;
    for (let target = event2.target; target; target = target.parentNode) {
      if (target.nodeType == 1 && target.classList.contains("cm-tooltip-lint"))
        return;
    }
    window.removeEventListener("mousemove", mousemove2);
    if (view.state.field(lintGutterTooltip))
      view.dispatch({ effects: setLintGutterTooltip.of(null) });
  };
  window.addEventListener("mousemove", mousemove2);
}
function gutterMarkerMouseOver(view, marker, diagnostics) {
  function hovered() {
    let line = view.elementAtHeight(marker.getBoundingClientRect().top + 5 - view.documentTop);
    const linePos = view.coordsAtPos(line.from);
    if (linePos) {
      view.dispatch({ effects: setLintGutterTooltip.of({
        pos: line.from,
        above: false,
        clip: false,
        create() {
          return {
            dom: diagnosticsTooltip(view, diagnostics),
            getCoords: () => marker.getBoundingClientRect()
          };
        }
      }) });
    }
    marker.onmouseout = marker.onmousemove = null;
    trackHoverOn(view, marker);
  }
  let { hoverTime } = view.state.facet(lintGutterConfig);
  let hoverTimeout = setTimeout(hovered, hoverTime);
  marker.onmouseout = () => {
    clearTimeout(hoverTimeout);
    marker.onmouseout = marker.onmousemove = null;
  };
  marker.onmousemove = () => {
    clearTimeout(hoverTimeout);
    hoverTimeout = setTimeout(hovered, hoverTime);
  };
}
function markersForDiagnostics(doc2, diagnostics) {
  let byLine = /* @__PURE__ */ Object.create(null);
  for (let diagnostic of diagnostics) {
    let line = doc2.lineAt(diagnostic.from);
    (byLine[line.from] || (byLine[line.from] = [])).push(diagnostic);
  }
  let markers = [];
  for (let line in byLine) {
    markers.push(new LintGutterMarker(byLine[line]).range(+line));
  }
  return RangeSet.of(markers, true);
}
var lintGutterExtension = /* @__PURE__ */ gutter({
  class: "cm-gutter-lint",
  markers: (view) => view.state.field(lintGutterMarkers),
  widgetMarker: (view, widget, block2) => {
    let diagnostics = [];
    view.state.field(lintGutterMarkers).between(block2.from, block2.to, (from, to, value) => {
      if (from > block2.from && from < block2.to)
        diagnostics.push(...value.diagnostics);
    });
    return diagnostics.length ? new LintGutterMarker(diagnostics) : null;
  }
});
var lintGutterMarkers = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(markers, tr) {
    markers = markers.map(tr.changes);
    let diagnosticFilter = tr.state.facet(lintGutterConfig).markerFilter;
    for (let effect2 of tr.effects) {
      if (effect2.is(setDiagnosticsEffect)) {
        let diagnostics = effect2.value;
        if (diagnosticFilter)
          diagnostics = diagnosticFilter(diagnostics || [], tr.state);
        markers = markersForDiagnostics(tr.state.doc, diagnostics.slice(0));
      }
    }
    return markers;
  }
});
var setLintGutterTooltip = /* @__PURE__ */ StateEffect.define();
var lintGutterTooltip = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(tooltip2, tr) {
    if (tooltip2 && tr.docChanged)
      tooltip2 = hideTooltip(tr, tooltip2) ? null : Object.assign(Object.assign({}, tooltip2), { pos: tr.changes.mapPos(tooltip2.pos) });
    return tr.effects.reduce((t4, e) => e.is(setLintGutterTooltip) ? e.value : t4, tooltip2);
  },
  provide: (field) => showTooltip.from(field)
});
var lintGutterTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-gutter-lint": {
    width: "1.4em",
    "& .cm-gutterElement": {
      padding: ".2em"
    }
  },
  ".cm-lint-marker": {
    width: "1em",
    height: "1em"
  },
  ".cm-lint-marker-info": {
    content: /* @__PURE__ */ svg(`<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>`)
  },
  ".cm-lint-marker-warning": {
    content: /* @__PURE__ */ svg(`<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`)
  },
  ".cm-lint-marker-error": {
    content: /* @__PURE__ */ svg(`<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`)
  }
});
var lintExtensions = [
  lintState,
  /* @__PURE__ */ EditorView.decorations.compute([lintState], (state2) => {
    let { selected, panel } = state2.field(lintState);
    return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
      activeMark.range(selected.from, selected.to)
    ]);
  }),
  /* @__PURE__ */ hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
  baseTheme4
];
var lintGutterConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      hoverTime: 300,
      markerFilter: null,
      tooltipFilter: null
    });
  }
});
function lintGutter(config2 = {}) {
  return [lintGutterConfig.of(config2), lintGutterMarkers, lintGutterExtension, lintGutterTheme, lintGutterTooltip];
}

// node_modules/@codemirror/search/dist/index.js
var basicNormalize = typeof String.prototype.normalize == "function" ? (x2) => x2.normalize("NFKD") : (x2) => x2;
var SearchCursor = class {
  /**
  Create a text cursor. The query is the search string, `from` to
  `to` provides the region to search.
  
  When `normalize` is given, it will be called, on both the query
  string and the content it is matched against, before comparing.
  You can, for example, create a case-insensitive search by
  passing `s => s.toLowerCase()`.
  
  Text is always normalized with
  [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
  (when supported).
  */
  constructor(text2, query2, from = 0, to = text2.length, normalize2, test) {
    this.test = test;
    this.value = { from: 0, to: 0 };
    this.done = false;
    this.matches = [];
    this.buffer = "";
    this.bufferPos = 0;
    this.iter = text2.iterRange(from, to);
    this.bufferStart = from;
    this.normalize = normalize2 ? (x2) => normalize2(basicNormalize(x2)) : basicNormalize;
    this.query = this.normalize(query2);
  }
  peek() {
    if (this.bufferPos == this.buffer.length) {
      this.bufferStart += this.buffer.length;
      this.iter.next();
      if (this.iter.done)
        return -1;
      this.bufferPos = 0;
      this.buffer = this.iter.value;
    }
    return codePointAt2(this.buffer, this.bufferPos);
  }
  /**
  Look for the next match. Updates the iterator's
  [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
  [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
  at least once before using the cursor.
  */
  next() {
    while (this.matches.length)
      this.matches.pop();
    return this.nextOverlapping();
  }
  /**
  The `next` method will ignore matches that partially overlap a
  previous match. This method behaves like `next`, but includes
  such matches.
  */
  nextOverlapping() {
    for (; ; ) {
      let next2 = this.peek();
      if (next2 < 0) {
        this.done = true;
        return this;
      }
      let str = fromCodePoint(next2), start2 = this.bufferStart + this.bufferPos;
      this.bufferPos += codePointSize2(next2);
      let norm = this.normalize(str);
      if (norm.length)
        for (let i2 = 0, pos = start2; ; i2++) {
          let code = norm.charCodeAt(i2);
          let match = this.match(code, pos, this.bufferPos + this.bufferStart);
          if (i2 == norm.length - 1) {
            if (match) {
              this.value = match;
              return this;
            }
            break;
          }
          if (pos == start2 && i2 < str.length && str.charCodeAt(i2) == code)
            pos++;
        }
    }
  }
  match(code, pos, end) {
    let match = null;
    for (let i2 = 0; i2 < this.matches.length; i2 += 2) {
      let index3 = this.matches[i2], keep = false;
      if (this.query.charCodeAt(index3) == code) {
        if (index3 == this.query.length - 1) {
          match = { from: this.matches[i2 + 1], to: end };
        } else {
          this.matches[i2]++;
          keep = true;
        }
      }
      if (!keep) {
        this.matches.splice(i2, 2);
        i2 -= 2;
      }
    }
    if (this.query.charCodeAt(0) == code) {
      if (this.query.length == 1)
        match = { from: pos, to: end };
      else
        this.matches.push(1, pos);
    }
    if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart))
      match = null;
    return match;
  }
};
if (typeof Symbol != "undefined")
  SearchCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
var empty = { from: -1, to: -1, match: /* @__PURE__ */ /.*/.exec("") };
var baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
var RegExpCursor = class {
  /**
  Create a cursor that will search the given range in the given
  document. `query` should be the raw pattern (as you'd pass it to
  `new RegExp`).
  */
  constructor(text2, query2, options4, from = 0, to = text2.length) {
    this.text = text2;
    this.to = to;
    this.curLine = "";
    this.done = false;
    this.value = empty;
    if (/\\[sWDnr]|\n|\r|\[\^/.test(query2))
      return new MultilineRegExpCursor(text2, query2, options4, from, to);
    this.re = new RegExp(query2, baseFlags + ((options4 === null || options4 === void 0 ? void 0 : options4.ignoreCase) ? "i" : ""));
    this.test = options4 === null || options4 === void 0 ? void 0 : options4.test;
    this.iter = text2.iter();
    let startLine = text2.lineAt(from);
    this.curLineStart = startLine.from;
    this.matchPos = toCharEnd(text2, from);
    this.getLine(this.curLineStart);
  }
  getLine(skip2) {
    this.iter.next(skip2);
    if (this.iter.lineBreak) {
      this.curLine = "";
    } else {
      this.curLine = this.iter.value;
      if (this.curLineStart + this.curLine.length > this.to)
        this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
      this.iter.next();
    }
  }
  nextLine() {
    this.curLineStart = this.curLineStart + this.curLine.length + 1;
    if (this.curLineStart > this.to)
      this.curLine = "";
    else
      this.getLine(0);
  }
  /**
  Move to the next match, if there is one.
  */
  next() {
    for (let off = this.matchPos - this.curLineStart; ; ) {
      this.re.lastIndex = off;
      let match = this.matchPos <= this.to && this.re.exec(this.curLine);
      if (match) {
        let from = this.curLineStart + match.index, to = from + match[0].length;
        this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
        if (from == this.curLineStart + this.curLine.length)
          this.nextLine();
        if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
          this.value = { from, to, match };
          return this;
        }
        off = this.matchPos - this.curLineStart;
      } else if (this.curLineStart + this.curLine.length < this.to) {
        this.nextLine();
        off = 0;
      } else {
        this.done = true;
        return this;
      }
    }
  }
};
var flattened = /* @__PURE__ */ new WeakMap();
var FlattenedDoc = class _FlattenedDoc {
  constructor(from, text2) {
    this.from = from;
    this.text = text2;
  }
  get to() {
    return this.from + this.text.length;
  }
  static get(doc2, from, to) {
    let cached = flattened.get(doc2);
    if (!cached || cached.from >= to || cached.to <= from) {
      let flat = new _FlattenedDoc(from, doc2.sliceString(from, to));
      flattened.set(doc2, flat);
      return flat;
    }
    if (cached.from == from && cached.to == to)
      return cached;
    let { text: text2, from: cachedFrom } = cached;
    if (cachedFrom > from) {
      text2 = doc2.sliceString(from, cachedFrom) + text2;
      cachedFrom = from;
    }
    if (cached.to < to)
      text2 += doc2.sliceString(cached.to, to);
    flattened.set(doc2, new _FlattenedDoc(cachedFrom, text2));
    return new _FlattenedDoc(from, text2.slice(from - cachedFrom, to - cachedFrom));
  }
};
var MultilineRegExpCursor = class {
  constructor(text2, query2, options4, from, to) {
    this.text = text2;
    this.to = to;
    this.done = false;
    this.value = empty;
    this.matchPos = toCharEnd(text2, from);
    this.re = new RegExp(query2, baseFlags + ((options4 === null || options4 === void 0 ? void 0 : options4.ignoreCase) ? "i" : ""));
    this.test = options4 === null || options4 === void 0 ? void 0 : options4.test;
    this.flat = FlattenedDoc.get(text2, from, this.chunkEnd(
      from + 5e3
      /* Chunk.Base */
    ));
  }
  chunkEnd(pos) {
    return pos >= this.to ? this.to : this.text.lineAt(pos).to;
  }
  next() {
    for (; ; ) {
      let off = this.re.lastIndex = this.matchPos - this.flat.from;
      let match = this.re.exec(this.flat.text);
      if (match && !match[0] && match.index == off) {
        this.re.lastIndex = off + 1;
        match = this.re.exec(this.flat.text);
      }
      if (match) {
        let from = this.flat.from + match.index, to = from + match[0].length;
        if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && (!this.test || this.test(from, to, match))) {
          this.value = { from, to, match };
          this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
          return this;
        }
      }
      if (this.flat.to == this.to) {
        this.done = true;
        return this;
      }
      this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
    }
  }
};
if (typeof Symbol != "undefined") {
  RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
}
function validRegExp(source3) {
  try {
    new RegExp(source3, baseFlags);
    return true;
  } catch (_a2) {
    return false;
  }
}
function toCharEnd(text2, pos) {
  if (pos >= text2.length)
    return pos;
  let line = text2.lineAt(pos), next2;
  while (pos < line.to && (next2 = line.text.charCodeAt(pos - line.from)) >= 56320 && next2 < 57344)
    pos++;
  return pos;
}
function createLineDialog(view) {
  let line = String(view.state.doc.lineAt(view.state.selection.main.head).number);
  let input = crelt("input", { class: "cm-textfield", name: "line", value: line });
  let dom = crelt("form", {
    class: "cm-gotoLine",
    onkeydown: (event2) => {
      if (event2.keyCode == 27) {
        event2.preventDefault();
        view.dispatch({ effects: dialogEffect.of(false) });
        view.focus();
      } else if (event2.keyCode == 13) {
        event2.preventDefault();
        go();
      }
    },
    onsubmit: (event2) => {
      event2.preventDefault();
      go();
    }
  }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go")), crelt("button", {
    name: "close",
    onclick: () => {
      view.dispatch({ effects: dialogEffect.of(false) });
      view.focus();
    },
    "aria-label": view.state.phrase("close"),
    type: "button"
  }, ["\xD7"]));
  function go() {
    let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
    if (!match)
      return;
    let { state: state2 } = view, startLine = state2.doc.lineAt(state2.selection.main.head);
    let [, sign, ln, cl, percent] = match;
    let col = cl ? +cl.slice(1) : 0;
    let line2 = ln ? +ln : startLine.number;
    if (ln && percent) {
      let pc = line2 / 100;
      if (sign)
        pc = pc * (sign == "-" ? -1 : 1) + startLine.number / state2.doc.lines;
      line2 = Math.round(state2.doc.lines * pc);
    } else if (ln && sign) {
      line2 = line2 * (sign == "-" ? -1 : 1) + startLine.number;
    }
    let docLine = state2.doc.line(Math.max(1, Math.min(state2.doc.lines, line2)));
    let selection2 = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
    view.dispatch({
      effects: [dialogEffect.of(false), EditorView.scrollIntoView(selection2.from, { y: "center" })],
      selection: selection2
    });
    view.focus();
  }
  return { dom };
}
var dialogEffect = /* @__PURE__ */ StateEffect.define();
var dialogField = /* @__PURE__ */ StateField.define({
  create() {
    return true;
  },
  update(value, tr) {
    for (let e of tr.effects)
      if (e.is(dialogEffect))
        value = e.value;
    return value;
  },
  provide: (f) => showPanel.from(f, (val) => val ? createLineDialog : null)
});
var gotoLine = (view) => {
  let panel = getPanel(view, createLineDialog);
  if (!panel) {
    let effects = [dialogEffect.of(true)];
    if (view.state.field(dialogField, false) == null)
      effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$13]));
    view.dispatch({ effects });
    panel = getPanel(view, createLineDialog);
  }
  if (panel)
    panel.dom.querySelector("input").select();
  return true;
};
var baseTheme$13 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-panel.cm-gotoLine": {
    padding: "2px 6px 4px",
    position: "relative",
    "& label": { fontSize: "80%" },
    "& [name=close]": {
      position: "absolute",
      top: "0",
      bottom: "0",
      right: "4px",
      backgroundColor: "inherit",
      border: "none",
      font: "inherit",
      padding: "0"
    }
  }
});
var defaultHighlightOptions = {
  highlightWordAroundCursor: false,
  minSelectionLength: 1,
  maxMatches: 100,
  wholeWords: false
};
var highlightConfig = /* @__PURE__ */ Facet.define({
  combine(options4) {
    return combineConfig(options4, defaultHighlightOptions, {
      highlightWordAroundCursor: (a, b) => a || b,
      minSelectionLength: Math.min,
      maxMatches: Math.min
    });
  }
});
function highlightSelectionMatches(options4) {
  let ext2 = [defaultTheme, matchHighlighter];
  if (options4)
    ext2.push(highlightConfig.of(options4));
  return ext2;
}
var matchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch" });
var mainMatchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
function insideWordBoundaries(check, state2, from, to) {
  return (from == 0 || check(state2.sliceDoc(from - 1, from)) != CharCategory.Word) && (to == state2.doc.length || check(state2.sliceDoc(to, to + 1)) != CharCategory.Word);
}
function insideWord(check, state2, from, to) {
  return check(state2.sliceDoc(from, from + 1)) == CharCategory.Word && check(state2.sliceDoc(to - 1, to)) == CharCategory.Word;
}
var matchHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = this.getDeco(view);
  }
  update(update3) {
    if (update3.selectionSet || update3.docChanged || update3.viewportChanged)
      this.decorations = this.getDeco(update3.view);
  }
  getDeco(view) {
    let conf = view.state.facet(highlightConfig);
    let { state: state2 } = view, sel = state2.selection;
    if (sel.ranges.length > 1)
      return Decoration.none;
    let range2 = sel.main, query2, check = null;
    if (range2.empty) {
      if (!conf.highlightWordAroundCursor)
        return Decoration.none;
      let word = state2.wordAt(range2.head);
      if (!word)
        return Decoration.none;
      check = state2.charCategorizer(range2.head);
      query2 = state2.sliceDoc(word.from, word.to);
    } else {
      let len = range2.to - range2.from;
      if (len < conf.minSelectionLength || len > 200)
        return Decoration.none;
      if (conf.wholeWords) {
        query2 = state2.sliceDoc(range2.from, range2.to);
        check = state2.charCategorizer(range2.head);
        if (!(insideWordBoundaries(check, state2, range2.from, range2.to) && insideWord(check, state2, range2.from, range2.to)))
          return Decoration.none;
      } else {
        query2 = state2.sliceDoc(range2.from, range2.to);
        if (!query2)
          return Decoration.none;
      }
    }
    let deco = [];
    for (let part of view.visibleRanges) {
      let cursor = new SearchCursor(state2.doc, query2, part.from, part.to);
      while (!cursor.next().done) {
        let { from, to } = cursor.value;
        if (!check || insideWordBoundaries(check, state2, from, to)) {
          if (range2.empty && from <= range2.from && to >= range2.to)
            deco.push(mainMatchDeco.range(from, to));
          else if (from >= range2.to || to <= range2.from)
            deco.push(matchDeco.range(from, to));
          if (deco.length > conf.maxMatches)
            return Decoration.none;
        }
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v) => v.decorations
});
var defaultTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
  ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
});
var selectWord = ({ state: state2, dispatch }) => {
  let { selection: selection2 } = state2;
  let newSel = EditorSelection.create(selection2.ranges.map((range2) => state2.wordAt(range2.head) || EditorSelection.cursor(range2.head)), selection2.mainIndex);
  if (newSel.eq(selection2))
    return false;
  dispatch(state2.update({ selection: newSel }));
  return true;
};
function findNextOccurrence(state2, query2) {
  let { main, ranges } = state2.selection;
  let word = state2.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to;
  for (let cycled = false, cursor = new SearchCursor(state2.doc, query2, ranges[ranges.length - 1].to); ; ) {
    cursor.next();
    if (cursor.done) {
      if (cycled)
        return null;
      cursor = new SearchCursor(state2.doc, query2, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
      cycled = true;
    } else {
      if (cycled && ranges.some((r2) => r2.from == cursor.value.from))
        continue;
      if (fullWord) {
        let word2 = state2.wordAt(cursor.value.from);
        if (!word2 || word2.from != cursor.value.from || word2.to != cursor.value.to)
          continue;
      }
      return cursor.value;
    }
  }
}
var selectNextOccurrence = ({ state: state2, dispatch }) => {
  let { ranges } = state2.selection;
  if (ranges.some((sel) => sel.from === sel.to))
    return selectWord({ state: state2, dispatch });
  let searchedText = state2.sliceDoc(ranges[0].from, ranges[0].to);
  if (state2.selection.ranges.some((r2) => state2.sliceDoc(r2.from, r2.to) != searchedText))
    return false;
  let range2 = findNextOccurrence(state2, searchedText);
  if (!range2)
    return false;
  dispatch(state2.update({
    selection: state2.selection.addRange(EditorSelection.range(range2.from, range2.to), false),
    effects: EditorView.scrollIntoView(range2.to)
  }));
  return true;
};
var searchConfigFacet = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      top: false,
      caseSensitive: false,
      literal: false,
      regexp: false,
      wholeWord: false,
      createPanel: (view) => new SearchPanel(view),
      scrollToMatch: (range2) => EditorView.scrollIntoView(range2)
    });
  }
});
var SearchQuery = class {
  /**
  Create a query object.
  */
  constructor(config2) {
    this.search = config2.search;
    this.caseSensitive = !!config2.caseSensitive;
    this.literal = !!config2.literal;
    this.regexp = !!config2.regexp;
    this.replace = config2.replace || "";
    this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
    this.unquoted = this.unquote(this.search);
    this.wholeWord = !!config2.wholeWord;
  }
  /**
  @internal
  */
  unquote(text2) {
    return this.literal ? text2 : text2.replace(/\\([nrt\\])/g, (_2, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "	" : "\\");
  }
  /**
  Compare this query to another query.
  */
  eq(other) {
    return this.search == other.search && this.replace == other.replace && this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && this.wholeWord == other.wholeWord;
  }
  /**
  @internal
  */
  create() {
    return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
  }
  /**
  Get a search cursor for this query, searching through the given
  range in the given state.
  */
  getCursor(state2, from = 0, to) {
    let st = state2.doc ? state2 : EditorState.create({ doc: state2 });
    if (to == null)
      to = st.doc.length;
    return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
  }
};
var QueryType2 = class {
  constructor(spec) {
    this.spec = spec;
  }
};
function stringCursor(spec, state2, from, to) {
  return new SearchCursor(state2.doc, spec.unquoted, from, to, spec.caseSensitive ? void 0 : (x2) => x2.toLowerCase(), spec.wholeWord ? stringWordTest(state2.doc, state2.charCategorizer(state2.selection.main.head)) : void 0);
}
function stringWordTest(doc2, categorizer) {
  return (from, to, buf, bufPos) => {
    if (bufPos > from || bufPos + buf.length < to) {
      bufPos = Math.max(0, from - 2);
      buf = doc2.sliceString(bufPos, Math.min(doc2.length, to + 2));
    }
    return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word || categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) && (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word || categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word);
  };
}
var StringQuery = class extends QueryType2 {
  constructor(spec) {
    super(spec);
  }
  nextMatch(state2, curFrom, curTo) {
    let cursor = stringCursor(this.spec, state2, curTo, state2.doc.length).nextOverlapping();
    if (cursor.done) {
      let end = Math.min(state2.doc.length, curFrom + this.spec.unquoted.length);
      cursor = stringCursor(this.spec, state2, 0, end).nextOverlapping();
    }
    return cursor.done || cursor.value.from == curFrom && cursor.value.to == curTo ? null : cursor.value;
  }
  // Searching in reverse is, rather than implementing an inverted search
  // cursor, done by scanning chunk after chunk forward.
  prevMatchInRange(state2, from, to) {
    for (let pos = to; ; ) {
      let start2 = Math.max(from, pos - 1e4 - this.spec.unquoted.length);
      let cursor = stringCursor(this.spec, state2, start2, pos), range2 = null;
      while (!cursor.nextOverlapping().done)
        range2 = cursor.value;
      if (range2)
        return range2;
      if (start2 == from)
        return null;
      pos -= 1e4;
    }
  }
  prevMatch(state2, curFrom, curTo) {
    let found = this.prevMatchInRange(state2, 0, curFrom);
    if (!found)
      found = this.prevMatchInRange(state2, Math.max(0, curTo - this.spec.unquoted.length), state2.doc.length);
    return found && (found.from != curFrom || found.to != curTo) ? found : null;
  }
  getReplacement(_result) {
    return this.spec.unquote(this.spec.replace);
  }
  matchAll(state2, limit) {
    let cursor = stringCursor(this.spec, state2, 0, state2.doc.length), ranges = [];
    while (!cursor.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor.value);
    }
    return ranges;
  }
  highlight(state2, from, to, add3) {
    let cursor = stringCursor(this.spec, state2, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state2.doc.length));
    while (!cursor.next().done)
      add3(cursor.value.from, cursor.value.to);
  }
};
function regexpCursor(spec, state2, from, to) {
  return new RegExpCursor(state2.doc, spec.search, {
    ignoreCase: !spec.caseSensitive,
    test: spec.wholeWord ? regexpWordTest(state2.charCategorizer(state2.selection.main.head)) : void 0
  }, from, to);
}
function charBefore(str, index3) {
  return str.slice(findClusterBreak2(str, index3, false), index3);
}
function charAfter(str, index3) {
  return str.slice(index3, findClusterBreak2(str, index3));
}
function regexpWordTest(categorizer) {
  return (_from, _to, match) => !match[0].length || (categorizer(charBefore(match.input, match.index)) != CharCategory.Word || categorizer(charAfter(match.input, match.index)) != CharCategory.Word) && (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word || categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word);
}
var RegExpQuery = class extends QueryType2 {
  nextMatch(state2, curFrom, curTo) {
    let cursor = regexpCursor(this.spec, state2, curTo, state2.doc.length).next();
    if (cursor.done)
      cursor = regexpCursor(this.spec, state2, 0, curFrom).next();
    return cursor.done ? null : cursor.value;
  }
  prevMatchInRange(state2, from, to) {
    for (let size = 1; ; size++) {
      let start2 = Math.max(
        from,
        to - size * 1e4
        /* FindPrev.ChunkSize */
      );
      let cursor = regexpCursor(this.spec, state2, start2, to), range2 = null;
      while (!cursor.next().done)
        range2 = cursor.value;
      if (range2 && (start2 == from || range2.from > start2 + 10))
        return range2;
      if (start2 == from)
        return null;
    }
  }
  prevMatch(state2, curFrom, curTo) {
    return this.prevMatchInRange(state2, 0, curFrom) || this.prevMatchInRange(state2, curTo, state2.doc.length);
  }
  getReplacement(result) {
    return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m2, i2) => {
      if (i2 == "&")
        return result.match[0];
      if (i2 == "$")
        return "$";
      for (let l = i2.length; l > 0; l--) {
        let n = +i2.slice(0, l);
        if (n > 0 && n < result.match.length)
          return result.match[n] + i2.slice(l);
      }
      return m2;
    });
  }
  matchAll(state2, limit) {
    let cursor = regexpCursor(this.spec, state2, 0, state2.doc.length), ranges = [];
    while (!cursor.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor.value);
    }
    return ranges;
  }
  highlight(state2, from, to, add3) {
    let cursor = regexpCursor(this.spec, state2, Math.max(
      0,
      from - 250
      /* RegExp.HighlightMargin */
    ), Math.min(to + 250, state2.doc.length));
    while (!cursor.next().done)
      add3(cursor.value.from, cursor.value.to);
  }
};
var setSearchQuery = /* @__PURE__ */ StateEffect.define();
var togglePanel2 = /* @__PURE__ */ StateEffect.define();
var searchState = /* @__PURE__ */ StateField.define({
  create(state2) {
    return new SearchState(defaultQuery(state2).create(), null);
  },
  update(value, tr) {
    for (let effect2 of tr.effects) {
      if (effect2.is(setSearchQuery))
        value = new SearchState(effect2.value.create(), value.panel);
      else if (effect2.is(togglePanel2))
        value = new SearchState(value.query, effect2.value ? createSearchPanel : null);
    }
    return value;
  },
  provide: (f) => showPanel.from(f, (val) => val.panel)
});
var SearchState = class {
  constructor(query2, panel) {
    this.query = query2;
    this.panel = panel;
  }
};
var matchMark = /* @__PURE__ */ Decoration.mark({ class: "cm-searchMatch" });
var selectedMatchMark = /* @__PURE__ */ Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" });
var searchHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.decorations = this.highlight(view.state.field(searchState));
  }
  update(update3) {
    let state2 = update3.state.field(searchState);
    if (state2 != update3.startState.field(searchState) || update3.docChanged || update3.selectionSet || update3.viewportChanged)
      this.decorations = this.highlight(state2);
  }
  highlight({ query: query2, panel }) {
    if (!panel || !query2.spec.valid)
      return Decoration.none;
    let { view } = this;
    let builder = new RangeSetBuilder();
    for (let i2 = 0, ranges = view.visibleRanges, l = ranges.length; i2 < l; i2++) {
      let { from, to } = ranges[i2];
      while (i2 < l - 1 && to > ranges[i2 + 1].from - 2 * 250)
        to = ranges[++i2].to;
      query2.highlight(view.state, from, to, (from2, to2) => {
        let selected = view.state.selection.ranges.some((r2) => r2.from == from2 && r2.to == to2);
        builder.add(from2, to2, selected ? selectedMatchMark : matchMark);
      });
    }
    return builder.finish();
  }
}, {
  decorations: (v) => v.decorations
});
function searchCommand(f) {
  return (view) => {
    let state2 = view.state.field(searchState, false);
    return state2 && state2.query.spec.valid ? f(view, state2) : openSearchPanel(view);
  };
}
var findNext = /* @__PURE__ */ searchCommand((view, { query: query2 }) => {
  let { to } = view.state.selection.main;
  let next2 = query2.nextMatch(view.state, to, to);
  if (!next2)
    return false;
  let selection2 = EditorSelection.single(next2.from, next2.to);
  let config2 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection: selection2,
    effects: [announceMatch(view, next2), config2.scrollToMatch(selection2.main, view)],
    userEvent: "select.search"
  });
  selectSearchInput(view);
  return true;
});
var findPrevious = /* @__PURE__ */ searchCommand((view, { query: query2 }) => {
  let { state: state2 } = view, { from } = state2.selection.main;
  let prev = query2.prevMatch(state2, from, from);
  if (!prev)
    return false;
  let selection2 = EditorSelection.single(prev.from, prev.to);
  let config2 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection: selection2,
    effects: [announceMatch(view, prev), config2.scrollToMatch(selection2.main, view)],
    userEvent: "select.search"
  });
  selectSearchInput(view);
  return true;
});
var selectMatches = /* @__PURE__ */ searchCommand((view, { query: query2 }) => {
  let ranges = query2.matchAll(view.state, 1e3);
  if (!ranges || !ranges.length)
    return false;
  view.dispatch({
    selection: EditorSelection.create(ranges.map((r2) => EditorSelection.range(r2.from, r2.to))),
    userEvent: "select.search.matches"
  });
  return true;
});
var selectSelectionMatches = ({ state: state2, dispatch }) => {
  let sel = state2.selection;
  if (sel.ranges.length > 1 || sel.main.empty)
    return false;
  let { from, to } = sel.main;
  let ranges = [], main = 0;
  for (let cur2 = new SearchCursor(state2.doc, state2.sliceDoc(from, to)); !cur2.next().done; ) {
    if (ranges.length > 1e3)
      return false;
    if (cur2.value.from == from)
      main = ranges.length;
    ranges.push(EditorSelection.range(cur2.value.from, cur2.value.to));
  }
  dispatch(state2.update({
    selection: EditorSelection.create(ranges, main),
    userEvent: "select.search.matches"
  }));
  return true;
};
var replaceNext = /* @__PURE__ */ searchCommand((view, { query: query2 }) => {
  let { state: state2 } = view, { from, to } = state2.selection.main;
  if (state2.readOnly)
    return false;
  let match = query2.nextMatch(state2, from, from);
  if (!match)
    return false;
  let next2 = match;
  let changes = [], selection2, replacement;
  let effects = [];
  if (next2.from == from && next2.to == to) {
    replacement = state2.toText(query2.getReplacement(next2));
    changes.push({ from: next2.from, to: next2.to, insert: replacement });
    next2 = query2.nextMatch(state2, next2.from, next2.to);
    effects.push(EditorView.announce.of(state2.phrase("replaced match on line $", state2.doc.lineAt(from).number) + "."));
  }
  if (next2) {
    let off = changes.length == 0 || changes[0].from >= match.to ? 0 : match.to - match.from - replacement.length;
    selection2 = EditorSelection.single(next2.from - off, next2.to - off);
    effects.push(announceMatch(view, next2));
    effects.push(state2.facet(searchConfigFacet).scrollToMatch(selection2.main, view));
  }
  view.dispatch({
    changes,
    selection: selection2,
    effects,
    userEvent: "input.replace"
  });
  return true;
});
var replaceAll = /* @__PURE__ */ searchCommand((view, { query: query2 }) => {
  if (view.state.readOnly)
    return false;
  let changes = query2.matchAll(view.state, 1e9).map((match) => {
    let { from, to } = match;
    return { from, to, insert: query2.getReplacement(match) };
  });
  if (!changes.length)
    return false;
  let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
  view.dispatch({
    changes,
    effects: EditorView.announce.of(announceText),
    userEvent: "input.replace.all"
  });
  return true;
});
function createSearchPanel(view) {
  return view.state.facet(searchConfigFacet).createPanel(view);
}
function defaultQuery(state2, fallback2) {
  var _a2, _b, _c, _d, _e;
  let sel = state2.selection.main;
  let selText = sel.empty || sel.to > sel.from + 100 ? "" : state2.sliceDoc(sel.from, sel.to);
  if (fallback2 && !selText)
    return fallback2;
  let config2 = state2.facet(searchConfigFacet);
  return new SearchQuery({
    search: ((_a2 = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.literal) !== null && _a2 !== void 0 ? _a2 : config2.literal) ? selText : selText.replace(/\n/g, "\\n"),
    caseSensitive: (_b = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.caseSensitive) !== null && _b !== void 0 ? _b : config2.caseSensitive,
    literal: (_c = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.literal) !== null && _c !== void 0 ? _c : config2.literal,
    regexp: (_d = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.regexp) !== null && _d !== void 0 ? _d : config2.regexp,
    wholeWord: (_e = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.wholeWord) !== null && _e !== void 0 ? _e : config2.wholeWord
  });
}
function getSearchInput(view) {
  let panel = getPanel(view, createSearchPanel);
  return panel && panel.dom.querySelector("[main-field]");
}
function selectSearchInput(view) {
  let input = getSearchInput(view);
  if (input && input == view.root.activeElement)
    input.select();
}
var openSearchPanel = (view) => {
  let state2 = view.state.field(searchState, false);
  if (state2 && state2.panel) {
    let searchInput = getSearchInput(view);
    if (searchInput && searchInput != view.root.activeElement) {
      let query2 = defaultQuery(view.state, state2.query.spec);
      if (query2.valid)
        view.dispatch({ effects: setSearchQuery.of(query2) });
      searchInput.focus();
      searchInput.select();
    }
  } else {
    view.dispatch({ effects: [
      togglePanel2.of(true),
      state2 ? setSearchQuery.of(defaultQuery(view.state, state2.query.spec)) : StateEffect.appendConfig.of(searchExtensions)
    ] });
  }
  return true;
};
var closeSearchPanel = (view) => {
  let state2 = view.state.field(searchState, false);
  if (!state2 || !state2.panel)
    return false;
  let panel = getPanel(view, createSearchPanel);
  if (panel && panel.dom.contains(view.root.activeElement))
    view.focus();
  view.dispatch({ effects: togglePanel2.of(false) });
  return true;
};
var searchKeymap = [
  { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
  { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
  { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
  { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
  { key: "Mod-Shift-l", run: selectSelectionMatches },
  { key: "Mod-Alt-g", run: gotoLine },
  { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }
];
var SearchPanel = class {
  constructor(view) {
    this.view = view;
    let query2 = this.query = view.state.field(searchState).query.spec;
    this.commit = this.commit.bind(this);
    this.searchField = crelt("input", {
      value: query2.search,
      placeholder: phrase(view, "Find"),
      "aria-label": phrase(view, "Find"),
      class: "cm-textfield",
      name: "search",
      form: "",
      "main-field": "true",
      onchange: this.commit,
      onkeyup: this.commit
    });
    this.replaceField = crelt("input", {
      value: query2.replace,
      placeholder: phrase(view, "Replace"),
      "aria-label": phrase(view, "Replace"),
      class: "cm-textfield",
      name: "replace",
      form: "",
      onchange: this.commit,
      onkeyup: this.commit
    });
    this.caseField = crelt("input", {
      type: "checkbox",
      name: "case",
      form: "",
      checked: query2.caseSensitive,
      onchange: this.commit
    });
    this.reField = crelt("input", {
      type: "checkbox",
      name: "re",
      form: "",
      checked: query2.regexp,
      onchange: this.commit
    });
    this.wordField = crelt("input", {
      type: "checkbox",
      name: "word",
      form: "",
      checked: query2.wholeWord,
      onchange: this.commit
    });
    function button(name3, onclick, content2) {
      return crelt("button", { class: "cm-button", name: name3, onclick, type: "button" }, content2);
    }
    this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [
      this.searchField,
      button("next", () => findNext(view), [phrase(view, "next")]),
      button("prev", () => findPrevious(view), [phrase(view, "previous")]),
      button("select", () => selectMatches(view), [phrase(view, "all")]),
      crelt("label", null, [this.caseField, phrase(view, "match case")]),
      crelt("label", null, [this.reField, phrase(view, "regexp")]),
      crelt("label", null, [this.wordField, phrase(view, "by word")]),
      ...view.state.readOnly ? [] : [
        crelt("br"),
        this.replaceField,
        button("replace", () => replaceNext(view), [phrase(view, "replace")]),
        button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])
      ],
      crelt("button", {
        name: "close",
        onclick: () => closeSearchPanel(view),
        "aria-label": phrase(view, "close"),
        type: "button"
      }, ["\xD7"])
    ]);
  }
  commit() {
    let query2 = new SearchQuery({
      search: this.searchField.value,
      caseSensitive: this.caseField.checked,
      regexp: this.reField.checked,
      wholeWord: this.wordField.checked,
      replace: this.replaceField.value
    });
    if (!query2.eq(this.query)) {
      this.query = query2;
      this.view.dispatch({ effects: setSearchQuery.of(query2) });
    }
  }
  keydown(e) {
    if (runScopeHandlers(this.view, e, "search-panel")) {
      e.preventDefault();
    } else if (e.keyCode == 13 && e.target == this.searchField) {
      e.preventDefault();
      (e.shiftKey ? findPrevious : findNext)(this.view);
    } else if (e.keyCode == 13 && e.target == this.replaceField) {
      e.preventDefault();
      replaceNext(this.view);
    }
  }
  update(update3) {
    for (let tr of update3.transactions)
      for (let effect2 of tr.effects) {
        if (effect2.is(setSearchQuery) && !effect2.value.eq(this.query))
          this.setQuery(effect2.value);
      }
  }
  setQuery(query2) {
    this.query = query2;
    this.searchField.value = query2.search;
    this.replaceField.value = query2.replace;
    this.caseField.checked = query2.caseSensitive;
    this.reField.checked = query2.regexp;
    this.wordField.checked = query2.wholeWord;
  }
  mount() {
    this.searchField.select();
  }
  get pos() {
    return 80;
  }
  get top() {
    return this.view.state.facet(searchConfigFacet).top;
  }
};
function phrase(view, phrase2) {
  return view.state.phrase(phrase2);
}
var AnnounceMargin = 30;
var Break = /[\s\.,:;?!]/;
function announceMatch(view, { from, to }) {
  let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to;
  let start2 = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
  let text2 = view.state.sliceDoc(start2, end);
  if (start2 != line.from) {
    for (let i2 = 0; i2 < AnnounceMargin; i2++)
      if (!Break.test(text2[i2 + 1]) && Break.test(text2[i2])) {
        text2 = text2.slice(i2);
        break;
      }
  }
  if (end != lineEnd) {
    for (let i2 = text2.length - 1; i2 > text2.length - AnnounceMargin; i2--)
      if (!Break.test(text2[i2 - 1]) && Break.test(text2[i2])) {
        text2 = text2.slice(0, i2);
        break;
      }
  }
  return EditorView.announce.of(`${view.state.phrase("current match")}. ${text2} ${view.state.phrase("on line")} ${line.number}.`);
}
var baseTheme5 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-panel.cm-search": {
    padding: "2px 6px 4px",
    position: "relative",
    "& [name=close]": {
      position: "absolute",
      top: "0",
      right: "4px",
      backgroundColor: "inherit",
      border: "none",
      font: "inherit",
      padding: 0,
      margin: 0
    },
    "& input, & button, & label": {
      margin: ".2em .6em .2em 0"
    },
    "& input[type=checkbox]": {
      marginRight: ".2em"
    },
    "& label": {
      fontSize: "80%",
      whiteSpace: "pre"
    }
  },
  "&light .cm-searchMatch": { backgroundColor: "#ffff0054" },
  "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" },
  "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" },
  "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" }
});
var searchExtensions = [
  searchState,
  /* @__PURE__ */ Prec.low(searchHighlighter),
  baseTheme5
];

// node_modules/web-tree-sitter/tree-sitter.js
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __require2 = /* @__PURE__ */ ((x2) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a, b) => (typeof __require !== "undefined" ? __require : a)[b]
}) : x2)(function(x2) {
  if (typeof __require !== "undefined") return __require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});
var SIZE_OF_SHORT = 2;
var SIZE_OF_INT = 4;
var SIZE_OF_CURSOR = 4 * SIZE_OF_INT;
var SIZE_OF_NODE = 5 * SIZE_OF_INT;
var SIZE_OF_POINT = 2 * SIZE_OF_INT;
var SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT;
var ZERO_POINT = { row: 0, column: 0 };
var INTERNAL = Symbol("INTERNAL");
function assertInternal(x2) {
  if (x2 !== INTERNAL) throw new Error("Illegal constructor");
}
__name(assertInternal, "assertInternal");
function isPoint(point2) {
  return !!point2 && typeof point2.row === "number" && typeof point2.column === "number";
}
__name(isPoint, "isPoint");
function setModule(module2) {
  C2 = module2;
}
__name(setModule, "setModule");
var C2;
var LookaheadIterator = class {
  static {
    __name(this, "LookaheadIterator");
  }
  /** @internal */
  [0] = 0;
  // Internal handle for WASM
  /** @internal */
  language;
  /** @internal */
  constructor(internal, address, language2) {
    assertInternal(internal);
    this[0] = address;
    this.language = language2;
  }
  /** Get the current symbol of the lookahead iterator. */
  get currentTypeId() {
    return C2._ts_lookahead_iterator_current_symbol(this[0]);
  }
  /** Get the current symbol name of the lookahead iterator. */
  get currentType() {
    return this.language.types[this.currentTypeId] || "ERROR";
  }
  /** Delete the lookahead iterator, freeing its resources. */
  delete() {
    C2._ts_lookahead_iterator_delete(this[0]);
    this[0] = 0;
  }
  /**
   * Reset the lookahead iterator.
   *
   * This returns `true` if the language was set successfully and `false`
   * otherwise.
   */
  reset(language2, stateId) {
    if (C2._ts_lookahead_iterator_reset(this[0], language2[0], stateId)) {
      this.language = language2;
      return true;
    }
    return false;
  }
  /**
   * Reset the lookahead iterator to another state.
   *
   * This returns `true` if the iterator was reset to the given state and
   * `false` otherwise.
   */
  resetState(stateId) {
    return Boolean(C2._ts_lookahead_iterator_reset_state(this[0], stateId));
  }
  /**
   * Returns an iterator that iterates over the symbols of the lookahead iterator.
   *
   * The iterator will yield the current symbol name as a string for each step
   * until there are no more symbols to iterate over.
   */
  [Symbol.iterator]() {
    return {
      next: /* @__PURE__ */ __name(() => {
        if (C2._ts_lookahead_iterator_next(this[0])) {
          return { done: false, value: this.currentType };
        }
        return { done: true, value: "" };
      }, "next")
    };
  }
};
function getText(tree, startIndex, endIndex, startPosition) {
  const length = endIndex - startIndex;
  let result = tree.textCallback(startIndex, startPosition);
  if (result) {
    startIndex += result.length;
    while (startIndex < endIndex) {
      const string4 = tree.textCallback(startIndex, startPosition);
      if (string4 && string4.length > 0) {
        startIndex += string4.length;
        result += string4;
      } else {
        break;
      }
    }
    if (startIndex > endIndex) {
      result = result.slice(0, length);
    }
  }
  return result ?? "";
}
__name(getText, "getText");
var Tree2 = class _Tree {
  static {
    __name(this, "Tree");
  }
  /** @internal */
  [0] = 0;
  // Internal handle for WASM
  /** @internal */
  textCallback;
  /** The language that was used to parse the syntax tree. */
  language;
  /** @internal */
  constructor(internal, address, language2, textCallback) {
    assertInternal(internal);
    this[0] = address;
    this.language = language2;
    this.textCallback = textCallback;
  }
  /** Create a shallow copy of the syntax tree. This is very fast. */
  copy() {
    const address = C2._ts_tree_copy(this[0]);
    return new _Tree(INTERNAL, address, this.language, this.textCallback);
  }
  /** Delete the syntax tree, freeing its resources. */
  delete() {
    C2._ts_tree_delete(this[0]);
    this[0] = 0;
  }
  /** Get the root node of the syntax tree. */
  get rootNode() {
    C2._ts_tree_root_node_wasm(this[0]);
    return unmarshalNode(this);
  }
  /**
   * Get the root node of the syntax tree, but with its position shifted
   * forward by the given offset.
   */
  rootNodeWithOffset(offsetBytes, offsetExtent) {
    const address = TRANSFER_BUFFER + SIZE_OF_NODE;
    C2.setValue(address, offsetBytes, "i32");
    marshalPoint(address + SIZE_OF_INT, offsetExtent);
    C2._ts_tree_root_node_with_offset_wasm(this[0]);
    return unmarshalNode(this);
  }
  /**
   * Edit the syntax tree to keep it in sync with source code that has been
   * edited.
   *
   * You must describe the edit both in terms of byte offsets and in terms of
   * row/column coordinates.
   */
  edit(edit) {
    marshalEdit(edit);
    C2._ts_tree_edit_wasm(this[0]);
  }
  /** Create a new {@link TreeCursor} starting from the root of the tree. */
  walk() {
    return this.rootNode.walk();
  }
  /**
   * Compare this old edited syntax tree to a new syntax tree representing
   * the same document, returning a sequence of ranges whose syntactic
   * structure has changed.
   *
   * For this to work correctly, this syntax tree must have been edited such
   * that its ranges match up to the new tree. Generally, you'll want to
   * call this method right after calling one of the [`Parser::parse`]
   * functions. Call it on the old tree that was passed to parse, and
   * pass the new tree that was returned from `parse`.
   */
  getChangedRanges(other) {
    if (!(other instanceof _Tree)) {
      throw new TypeError("Argument must be a Tree");
    }
    C2._ts_tree_get_changed_ranges_wasm(this[0], other[0]);
    const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
    const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const result = new Array(count2);
    if (count2 > 0) {
      let address = buffer;
      for (let i2 = 0; i2 < count2; i2++) {
        result[i2] = unmarshalRange(address);
        address += SIZE_OF_RANGE;
      }
      C2._free(buffer);
    }
    return result;
  }
  /** Get the included ranges that were used to parse the syntax tree. */
  getIncludedRanges() {
    C2._ts_tree_included_ranges_wasm(this[0]);
    const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
    const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const result = new Array(count2);
    if (count2 > 0) {
      let address = buffer;
      for (let i2 = 0; i2 < count2; i2++) {
        result[i2] = unmarshalRange(address);
        address += SIZE_OF_RANGE;
      }
      C2._free(buffer);
    }
    return result;
  }
};
var TreeCursor2 = class _TreeCursor {
  static {
    __name(this, "TreeCursor");
  }
  /** @internal */
  [0] = 0;
  // Internal handle for WASM
  /** @internal */
  [1] = 0;
  // Internal handle for WASM
  /** @internal */
  [2] = 0;
  // Internal handle for WASM
  /** @internal */
  [3] = 0;
  // Internal handle for WASM
  /** @internal */
  tree;
  /** @internal */
  constructor(internal, tree) {
    assertInternal(internal);
    this.tree = tree;
    unmarshalTreeCursor(this);
  }
  /** Creates a deep copy of the tree cursor. This allocates new memory. */
  copy() {
    const copy2 = new _TreeCursor(INTERNAL, this.tree);
    C2._ts_tree_cursor_copy_wasm(this.tree[0]);
    unmarshalTreeCursor(copy2);
    return copy2;
  }
  /** Delete the tree cursor, freeing its resources. */
  delete() {
    marshalTreeCursor(this);
    C2._ts_tree_cursor_delete_wasm(this.tree[0]);
    this[0] = this[1] = this[2] = 0;
  }
  /** Get the tree cursor's current {@link Node}. */
  get currentNode() {
    marshalTreeCursor(this);
    C2._ts_tree_cursor_current_node_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /**
   * Get the numerical field id of this tree cursor's current node.
   *
   * See also {@link TreeCursor#currentFieldName}.
   */
  get currentFieldId() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
  }
  /** Get the field name of this tree cursor's current node. */
  get currentFieldName() {
    return this.tree.language.fields[this.currentFieldId];
  }
  /**
   * Get the depth of the cursor's current node relative to the original
   * node that the cursor was constructed with.
   */
  get currentDepth() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_depth_wasm(this.tree[0]);
  }
  /**
   * Get the index of the cursor's current node out of all of the
   * descendants of the original node that the cursor was constructed with.
   */
  get currentDescendantIndex() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_descendant_index_wasm(this.tree[0]);
  }
  /** Get the type of the cursor's current node. */
  get nodeType() {
    return this.tree.language.types[this.nodeTypeId] || "ERROR";
  }
  /** Get the type id of the cursor's current node. */
  get nodeTypeId() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
  }
  /** Get the state id of the cursor's current node. */
  get nodeStateId() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_node_state_id_wasm(this.tree[0]);
  }
  /** Get the id of the cursor's current node. */
  get nodeId() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
  }
  /**
   * Check if the cursor's current node is *named*.
   *
   * Named nodes correspond to named rules in the grammar, whereas
   * *anonymous* nodes correspond to string literals in the grammar.
   */
  get nodeIsNamed() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]) === 1;
  }
  /**
   * Check if the cursor's current node is *missing*.
   *
   * Missing nodes are inserted by the parser in order to recover from
   * certain kinds of syntax errors.
   */
  get nodeIsMissing() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]) === 1;
  }
  /** Get the string content of the cursor's current node. */
  get nodeText() {
    marshalTreeCursor(this);
    const startIndex = C2._ts_tree_cursor_start_index_wasm(this.tree[0]);
    const endIndex = C2._ts_tree_cursor_end_index_wasm(this.tree[0]);
    C2._ts_tree_cursor_start_position_wasm(this.tree[0]);
    const startPosition = unmarshalPoint(TRANSFER_BUFFER);
    return getText(this.tree, startIndex, endIndex, startPosition);
  }
  /** Get the start position of the cursor's current node. */
  get startPosition() {
    marshalTreeCursor(this);
    C2._ts_tree_cursor_start_position_wasm(this.tree[0]);
    return unmarshalPoint(TRANSFER_BUFFER);
  }
  /** Get the end position of the cursor's current node. */
  get endPosition() {
    marshalTreeCursor(this);
    C2._ts_tree_cursor_end_position_wasm(this.tree[0]);
    return unmarshalPoint(TRANSFER_BUFFER);
  }
  /** Get the start index of the cursor's current node. */
  get startIndex() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_start_index_wasm(this.tree[0]);
  }
  /** Get the end index of the cursor's current node. */
  get endIndex() {
    marshalTreeCursor(this);
    return C2._ts_tree_cursor_end_index_wasm(this.tree[0]);
  }
  /**
   * Move this cursor to the first child of its current node.
   *
   * This returns `true` if the cursor successfully moved, and returns
   * `false` if there were no children.
   */
  gotoFirstChild() {
    marshalTreeCursor(this);
    const result = C2._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
    return result === 1;
  }
  /**
   * Move this cursor to the last child of its current node.
   *
   * This returns `true` if the cursor successfully moved, and returns
   * `false` if there were no children.
   *
   * Note that this function may be slower than
   * {@link TreeCursor#gotoFirstChild} because it needs to
   * iterate through all the children to compute the child's position.
   */
  gotoLastChild() {
    marshalTreeCursor(this);
    const result = C2._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
    return result === 1;
  }
  /**
   * Move this cursor to the parent of its current node.
   *
   * This returns `true` if the cursor successfully moved, and returns
   * `false` if there was no parent node (the cursor was already on the
   * root node).
   *
   * Note that the node the cursor was constructed with is considered the root
   * of the cursor, and the cursor cannot walk outside this node.
   */
  gotoParent() {
    marshalTreeCursor(this);
    const result = C2._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
    return result === 1;
  }
  /**
   * Move this cursor to the next sibling of its current node.
   *
   * This returns `true` if the cursor successfully moved, and returns
   * `false` if there was no next sibling node.
   *
   * Note that the node the cursor was constructed with is considered the root
   * of the cursor, and the cursor cannot walk outside this node.
   */
  gotoNextSibling() {
    marshalTreeCursor(this);
    const result = C2._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
    return result === 1;
  }
  /**
   * Move this cursor to the previous sibling of its current node.
   *
   * This returns `true` if the cursor successfully moved, and returns
   * `false` if there was no previous sibling node.
   *
   * Note that this function may be slower than
   * {@link TreeCursor#gotoNextSibling} due to how node
   * positions are stored. In the worst case, this will need to iterate
   * through all the children up to the previous sibling node to recalculate
   * its position. Also note that the node the cursor was constructed with is
   * considered the root of the cursor, and the cursor cannot walk outside this node.
   */
  gotoPreviousSibling() {
    marshalTreeCursor(this);
    const result = C2._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
    return result === 1;
  }
  /**
   * Move the cursor to the node that is the nth descendant of
   * the original node that the cursor was constructed with, where
   * zero represents the original node itself.
   */
  gotoDescendant(goalDescendantIndex) {
    marshalTreeCursor(this);
    C2._ts_tree_cursor_goto_descendant_wasm(this.tree[0], goalDescendantIndex);
    unmarshalTreeCursor(this);
  }
  /**
   * Move this cursor to the first child of its current node that contains or
   * starts after the given byte offset.
   *
   * This returns `true` if the cursor successfully moved to a child node, and returns
   * `false` if no such child was found.
   */
  gotoFirstChildForIndex(goalIndex) {
    marshalTreeCursor(this);
    C2.setValue(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalIndex, "i32");
    const result = C2._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
    return result === 1;
  }
  /**
   * Move this cursor to the first child of its current node that contains or
   * starts after the given byte offset.
   *
   * This returns the index of the child node if one was found, and returns
   * `null` if no such child was found.
   */
  gotoFirstChildForPosition(goalPosition) {
    marshalTreeCursor(this);
    marshalPoint(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalPosition);
    const result = C2._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
    return result === 1;
  }
  /**
   * Re-initialize this tree cursor to start at the original node that the
   * cursor was constructed with.
   */
  reset(node) {
    marshalNode(node);
    marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
    C2._ts_tree_cursor_reset_wasm(this.tree[0]);
    unmarshalTreeCursor(this);
  }
  /**
   * Re-initialize a tree cursor to the same position as another cursor.
   *
   * Unlike {@link TreeCursor#reset}, this will not lose parent
   * information and allows reusing already created cursors.
   */
  resetTo(cursor) {
    marshalTreeCursor(this, TRANSFER_BUFFER);
    marshalTreeCursor(cursor, TRANSFER_BUFFER + SIZE_OF_CURSOR);
    C2._ts_tree_cursor_reset_to_wasm(this.tree[0], cursor.tree[0]);
    unmarshalTreeCursor(this);
  }
};
var Node3 = class {
  static {
    __name(this, "Node");
  }
  /** @internal */
  [0] = 0;
  // Internal handle for WASM
  /** @internal */
  _children;
  /** @internal */
  _namedChildren;
  /** @internal */
  constructor(internal, {
    id: id3,
    tree,
    startIndex,
    startPosition,
    other
  }) {
    assertInternal(internal);
    this[0] = other;
    this.id = id3;
    this.tree = tree;
    this.startIndex = startIndex;
    this.startPosition = startPosition;
  }
  /**
   * The numeric id for this node that is unique.
   *
   * Within a given syntax tree, no two nodes have the same id. However:
   *
   * * If a new tree is created based on an older tree, and a node from the old tree is reused in
   *   the process, then that node will have the same id in both trees.
   *
   * * A node not marked as having changes does not guarantee it was reused.
   *
   * * If a node is marked as having changed in the old tree, it will not be reused.
   */
  id;
  /** The byte index where this node starts. */
  startIndex;
  /** The position where this node starts. */
  startPosition;
  /** The tree that this node belongs to. */
  tree;
  /** Get this node's type as a numerical id. */
  get typeId() {
    marshalNode(this);
    return C2._ts_node_symbol_wasm(this.tree[0]);
  }
  /**
   * Get the node's type as a numerical id as it appears in the grammar,
   * ignoring aliases.
   */
  get grammarId() {
    marshalNode(this);
    return C2._ts_node_grammar_symbol_wasm(this.tree[0]);
  }
  /** Get this node's type as a string. */
  get type() {
    return this.tree.language.types[this.typeId] || "ERROR";
  }
  /**
   * Get this node's symbol name as it appears in the grammar, ignoring
   * aliases as a string.
   */
  get grammarType() {
    return this.tree.language.types[this.grammarId] || "ERROR";
  }
  /**
   * Check if this node is *named*.
   *
   * Named nodes correspond to named rules in the grammar, whereas
   * *anonymous* nodes correspond to string literals in the grammar.
   */
  get isNamed() {
    marshalNode(this);
    return C2._ts_node_is_named_wasm(this.tree[0]) === 1;
  }
  /**
   * Check if this node is *extra*.
   *
   * Extra nodes represent things like comments, which are not required
   * by the grammar, but can appear anywhere.
   */
  get isExtra() {
    marshalNode(this);
    return C2._ts_node_is_extra_wasm(this.tree[0]) === 1;
  }
  /**
   * Check if this node represents a syntax error.
   *
   * Syntax errors represent parts of the code that could not be incorporated
   * into a valid syntax tree.
   */
  get isError() {
    marshalNode(this);
    return C2._ts_node_is_error_wasm(this.tree[0]) === 1;
  }
  /**
   * Check if this node is *missing*.
   *
   * Missing nodes are inserted by the parser in order to recover from
   * certain kinds of syntax errors.
   */
  get isMissing() {
    marshalNode(this);
    return C2._ts_node_is_missing_wasm(this.tree[0]) === 1;
  }
  /** Check if this node has been edited. */
  get hasChanges() {
    marshalNode(this);
    return C2._ts_node_has_changes_wasm(this.tree[0]) === 1;
  }
  /**
   * Check if this node represents a syntax error or contains any syntax
   * errors anywhere within it.
   */
  get hasError() {
    marshalNode(this);
    return C2._ts_node_has_error_wasm(this.tree[0]) === 1;
  }
  /** Get the byte index where this node ends. */
  get endIndex() {
    marshalNode(this);
    return C2._ts_node_end_index_wasm(this.tree[0]);
  }
  /** Get the position where this node ends. */
  get endPosition() {
    marshalNode(this);
    C2._ts_node_end_point_wasm(this.tree[0]);
    return unmarshalPoint(TRANSFER_BUFFER);
  }
  /** Get the string content of this node. */
  get text() {
    return getText(this.tree, this.startIndex, this.endIndex, this.startPosition);
  }
  /** Get this node's parse state. */
  get parseState() {
    marshalNode(this);
    return C2._ts_node_parse_state_wasm(this.tree[0]);
  }
  /** Get the parse state after this node. */
  get nextParseState() {
    marshalNode(this);
    return C2._ts_node_next_parse_state_wasm(this.tree[0]);
  }
  /** Check if this node is equal to another node. */
  equals(other) {
    return this.tree === other.tree && this.id === other.id;
  }
  /**
   * Get the node's child at the given index, where zero represents the first child.
   *
   * This method is fairly fast, but its cost is technically log(n), so if
   * you might be iterating over a long list of children, you should use
   * {@link Node#children} instead.
   */
  child(index3) {
    marshalNode(this);
    C2._ts_node_child_wasm(this.tree[0], index3);
    return unmarshalNode(this.tree);
  }
  /**
   * Get this node's *named* child at the given index.
   *
   * See also {@link Node#isNamed}.
   * This method is fairly fast, but its cost is technically log(n), so if
   * you might be iterating over a long list of children, you should use
   * {@link Node#namedChildren} instead.
   */
  namedChild(index3) {
    marshalNode(this);
    C2._ts_node_named_child_wasm(this.tree[0], index3);
    return unmarshalNode(this.tree);
  }
  /**
   * Get this node's child with the given numerical field id.
   *
   * See also {@link Node#childForFieldName}. You can
   * convert a field name to an id using {@link Language#fieldIdForName}.
   */
  childForFieldId(fieldId) {
    marshalNode(this);
    C2._ts_node_child_by_field_id_wasm(this.tree[0], fieldId);
    return unmarshalNode(this.tree);
  }
  /**
   * Get the first child with the given field name.
   *
   * If multiple children may have the same field name, access them using
   * {@link Node#childrenForFieldName}.
   */
  childForFieldName(fieldName) {
    const fieldId = this.tree.language.fields.indexOf(fieldName);
    if (fieldId !== -1) return this.childForFieldId(fieldId);
    return null;
  }
  /** Get the field name of this node's child at the given index. */
  fieldNameForChild(index3) {
    marshalNode(this);
    const address = C2._ts_node_field_name_for_child_wasm(this.tree[0], index3);
    if (!address) return null;
    return C2.AsciiToString(address);
  }
  /** Get the field name of this node's named child at the given index. */
  fieldNameForNamedChild(index3) {
    marshalNode(this);
    const address = C2._ts_node_field_name_for_named_child_wasm(this.tree[0], index3);
    if (!address) return null;
    return C2.AsciiToString(address);
  }
  /**
   * Get an array of this node's children with a given field name.
   *
   * See also {@link Node#children}.
   */
  childrenForFieldName(fieldName) {
    const fieldId = this.tree.language.fields.indexOf(fieldName);
    if (fieldId !== -1 && fieldId !== 0) return this.childrenForFieldId(fieldId);
    return [];
  }
  /**
    * Get an array of this node's children with a given field id.
    *
    * See also {@link Node#childrenForFieldName}.
    */
  childrenForFieldId(fieldId) {
    marshalNode(this);
    C2._ts_node_children_by_field_id_wasm(this.tree[0], fieldId);
    const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
    const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const result = new Array(count2);
    if (count2 > 0) {
      let address = buffer;
      for (let i2 = 0; i2 < count2; i2++) {
        result[i2] = unmarshalNode(this.tree, address);
        address += SIZE_OF_NODE;
      }
      C2._free(buffer);
    }
    return result;
  }
  /** Get the node's first child that contains or starts after the given byte offset. */
  firstChildForIndex(index3) {
    marshalNode(this);
    const address = TRANSFER_BUFFER + SIZE_OF_NODE;
    C2.setValue(address, index3, "i32");
    C2._ts_node_first_child_for_byte_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get the node's first named child that contains or starts after the given byte offset. */
  firstNamedChildForIndex(index3) {
    marshalNode(this);
    const address = TRANSFER_BUFFER + SIZE_OF_NODE;
    C2.setValue(address, index3, "i32");
    C2._ts_node_first_named_child_for_byte_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get this node's number of children. */
  get childCount() {
    marshalNode(this);
    return C2._ts_node_child_count_wasm(this.tree[0]);
  }
  /**
   * Get this node's number of *named* children.
   *
   * See also {@link Node#isNamed}.
   */
  get namedChildCount() {
    marshalNode(this);
    return C2._ts_node_named_child_count_wasm(this.tree[0]);
  }
  /** Get this node's first child. */
  get firstChild() {
    return this.child(0);
  }
  /**
   * Get this node's first named child.
   *
   * See also {@link Node#isNamed}.
   */
  get firstNamedChild() {
    return this.namedChild(0);
  }
  /** Get this node's last child. */
  get lastChild() {
    return this.child(this.childCount - 1);
  }
  /**
   * Get this node's last named child.
   *
   * See also {@link Node#isNamed}.
   */
  get lastNamedChild() {
    return this.namedChild(this.namedChildCount - 1);
  }
  /**
   * Iterate over this node's children.
   *
   * If you're walking the tree recursively, you may want to use the
   * {@link TreeCursor} APIs directly instead.
   */
  get children() {
    if (!this._children) {
      marshalNode(this);
      C2._ts_node_children_wasm(this.tree[0]);
      const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
      const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
      this._children = new Array(count2);
      if (count2 > 0) {
        let address = buffer;
        for (let i2 = 0; i2 < count2; i2++) {
          this._children[i2] = unmarshalNode(this.tree, address);
          address += SIZE_OF_NODE;
        }
        C2._free(buffer);
      }
    }
    return this._children;
  }
  /**
   * Iterate over this node's named children.
   *
   * See also {@link Node#children}.
   */
  get namedChildren() {
    if (!this._namedChildren) {
      marshalNode(this);
      C2._ts_node_named_children_wasm(this.tree[0]);
      const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
      const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
      this._namedChildren = new Array(count2);
      if (count2 > 0) {
        let address = buffer;
        for (let i2 = 0; i2 < count2; i2++) {
          this._namedChildren[i2] = unmarshalNode(this.tree, address);
          address += SIZE_OF_NODE;
        }
        C2._free(buffer);
      }
    }
    return this._namedChildren;
  }
  /**
   * Get the descendants of this node that are the given type, or in the given types array.
   *
   * The types array should contain node type strings, which can be retrieved from {@link Language#types}.
   *
   * Additionally, a `startPosition` and `endPosition` can be passed in to restrict the search to a byte range.
   */
  descendantsOfType(types2, startPosition = ZERO_POINT, endPosition = ZERO_POINT) {
    if (!Array.isArray(types2)) types2 = [types2];
    const symbols = [];
    const typesBySymbol = this.tree.language.types;
    for (const node_type of types2) {
      if (node_type == "ERROR") {
        symbols.push(65535);
      }
    }
    for (let i2 = 0, n = typesBySymbol.length; i2 < n; i2++) {
      if (types2.includes(typesBySymbol[i2])) {
        symbols.push(i2);
      }
    }
    const symbolsAddress = C2._malloc(SIZE_OF_INT * symbols.length);
    for (let i2 = 0, n = symbols.length; i2 < n; i2++) {
      C2.setValue(symbolsAddress + i2 * SIZE_OF_INT, symbols[i2], "i32");
    }
    marshalNode(this);
    C2._ts_node_descendants_of_type_wasm(
      this.tree[0],
      symbolsAddress,
      symbols.length,
      startPosition.row,
      startPosition.column,
      endPosition.row,
      endPosition.column
    );
    const descendantCount = C2.getValue(TRANSFER_BUFFER, "i32");
    const descendantAddress = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const result = new Array(descendantCount);
    if (descendantCount > 0) {
      let address = descendantAddress;
      for (let i2 = 0; i2 < descendantCount; i2++) {
        result[i2] = unmarshalNode(this.tree, address);
        address += SIZE_OF_NODE;
      }
    }
    C2._free(descendantAddress);
    C2._free(symbolsAddress);
    return result;
  }
  /** Get this node's next sibling. */
  get nextSibling() {
    marshalNode(this);
    C2._ts_node_next_sibling_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get this node's previous sibling. */
  get previousSibling() {
    marshalNode(this);
    C2._ts_node_prev_sibling_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /**
   * Get this node's next *named* sibling.
   *
   * See also {@link Node#isNamed}.
   */
  get nextNamedSibling() {
    marshalNode(this);
    C2._ts_node_next_named_sibling_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /**
   * Get this node's previous *named* sibling.
   *
   * See also {@link Node#isNamed}.
   */
  get previousNamedSibling() {
    marshalNode(this);
    C2._ts_node_prev_named_sibling_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get the node's number of descendants, including one for the node itself. */
  get descendantCount() {
    marshalNode(this);
    return C2._ts_node_descendant_count_wasm(this.tree[0]);
  }
  /**
   * Get this node's immediate parent.
   * Prefer {@link Node#childWithDescendant} for iterating over this node's ancestors.
   */
  get parent() {
    marshalNode(this);
    C2._ts_node_parent_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /**
   * Get the node that contains `descendant`.
   *
   * Note that this can return `descendant` itself.
   */
  childWithDescendant(descendant) {
    marshalNode(this);
    marshalNode(descendant);
    C2._ts_node_child_with_descendant_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get the smallest node within this node that spans the given byte range. */
  descendantForIndex(start2, end = start2) {
    if (typeof start2 !== "number" || typeof end !== "number") {
      throw new Error("Arguments must be numbers");
    }
    marshalNode(this);
    const address = TRANSFER_BUFFER + SIZE_OF_NODE;
    C2.setValue(address, start2, "i32");
    C2.setValue(address + SIZE_OF_INT, end, "i32");
    C2._ts_node_descendant_for_index_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get the smallest named node within this node that spans the given byte range. */
  namedDescendantForIndex(start2, end = start2) {
    if (typeof start2 !== "number" || typeof end !== "number") {
      throw new Error("Arguments must be numbers");
    }
    marshalNode(this);
    const address = TRANSFER_BUFFER + SIZE_OF_NODE;
    C2.setValue(address, start2, "i32");
    C2.setValue(address + SIZE_OF_INT, end, "i32");
    C2._ts_node_named_descendant_for_index_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get the smallest node within this node that spans the given point range. */
  descendantForPosition(start2, end = start2) {
    if (!isPoint(start2) || !isPoint(end)) {
      throw new Error("Arguments must be {row, column} objects");
    }
    marshalNode(this);
    const address = TRANSFER_BUFFER + SIZE_OF_NODE;
    marshalPoint(address, start2);
    marshalPoint(address + SIZE_OF_POINT, end);
    C2._ts_node_descendant_for_position_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /** Get the smallest named node within this node that spans the given point range. */
  namedDescendantForPosition(start2, end = start2) {
    if (!isPoint(start2) || !isPoint(end)) {
      throw new Error("Arguments must be {row, column} objects");
    }
    marshalNode(this);
    const address = TRANSFER_BUFFER + SIZE_OF_NODE;
    marshalPoint(address, start2);
    marshalPoint(address + SIZE_OF_POINT, end);
    C2._ts_node_named_descendant_for_position_wasm(this.tree[0]);
    return unmarshalNode(this.tree);
  }
  /**
   * Create a new {@link TreeCursor} starting from this node.
   *
   * Note that the given node is considered the root of the cursor,
   * and the cursor cannot walk outside this node.
   */
  walk() {
    marshalNode(this);
    C2._ts_tree_cursor_new_wasm(this.tree[0]);
    return new TreeCursor2(INTERNAL, this.tree);
  }
  /**
   * Edit this node to keep it in-sync with source code that has been edited.
   *
   * This function is only rarely needed. When you edit a syntax tree with
   * the {@link Tree#edit} method, all of the nodes that you retrieve from
   * the tree afterward will already reflect the edit. You only need to
   * use {@link Node#edit} when you have a specific {@link Node} instance that
   * you want to keep and continue to use after an edit.
   */
  edit(edit) {
    if (this.startIndex >= edit.oldEndIndex) {
      this.startIndex = edit.newEndIndex + (this.startIndex - edit.oldEndIndex);
      let subbedPointRow;
      let subbedPointColumn;
      if (this.startPosition.row > edit.oldEndPosition.row) {
        subbedPointRow = this.startPosition.row - edit.oldEndPosition.row;
        subbedPointColumn = this.startPosition.column;
      } else {
        subbedPointRow = 0;
        subbedPointColumn = this.startPosition.column;
        if (this.startPosition.column >= edit.oldEndPosition.column) {
          subbedPointColumn = this.startPosition.column - edit.oldEndPosition.column;
        }
      }
      if (subbedPointRow > 0) {
        this.startPosition.row += subbedPointRow;
        this.startPosition.column = subbedPointColumn;
      } else {
        this.startPosition.column += subbedPointColumn;
      }
    } else if (this.startIndex > edit.startIndex) {
      this.startIndex = edit.newEndIndex;
      this.startPosition.row = edit.newEndPosition.row;
      this.startPosition.column = edit.newEndPosition.column;
    }
  }
  /** Get the S-expression representation of this node. */
  toString() {
    marshalNode(this);
    const address = C2._ts_node_to_string_wasm(this.tree[0]);
    const result = C2.AsciiToString(address);
    C2._free(address);
    return result;
  }
};
function unmarshalCaptures(query2, tree, address, patternIndex, result) {
  for (let i2 = 0, n = result.length; i2 < n; i2++) {
    const captureIndex = C2.getValue(address, "i32");
    address += SIZE_OF_INT;
    const node = unmarshalNode(tree, address);
    address += SIZE_OF_NODE;
    result[i2] = { patternIndex, name: query2.captureNames[captureIndex], node };
  }
  return address;
}
__name(unmarshalCaptures, "unmarshalCaptures");
function marshalNode(node) {
  let address = TRANSFER_BUFFER;
  C2.setValue(address, node.id, "i32");
  address += SIZE_OF_INT;
  C2.setValue(address, node.startIndex, "i32");
  address += SIZE_OF_INT;
  C2.setValue(address, node.startPosition.row, "i32");
  address += SIZE_OF_INT;
  C2.setValue(address, node.startPosition.column, "i32");
  address += SIZE_OF_INT;
  C2.setValue(address, node[0], "i32");
}
__name(marshalNode, "marshalNode");
function unmarshalNode(tree, address = TRANSFER_BUFFER) {
  const id3 = C2.getValue(address, "i32");
  address += SIZE_OF_INT;
  if (id3 === 0) return null;
  const index3 = C2.getValue(address, "i32");
  address += SIZE_OF_INT;
  const row = C2.getValue(address, "i32");
  address += SIZE_OF_INT;
  const column = C2.getValue(address, "i32");
  address += SIZE_OF_INT;
  const other = C2.getValue(address, "i32");
  const result = new Node3(INTERNAL, {
    id: id3,
    tree,
    startIndex: index3,
    startPosition: { row, column },
    other
  });
  return result;
}
__name(unmarshalNode, "unmarshalNode");
function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
  C2.setValue(address + 0 * SIZE_OF_INT, cursor[0], "i32");
  C2.setValue(address + 1 * SIZE_OF_INT, cursor[1], "i32");
  C2.setValue(address + 2 * SIZE_OF_INT, cursor[2], "i32");
  C2.setValue(address + 3 * SIZE_OF_INT, cursor[3], "i32");
}
__name(marshalTreeCursor, "marshalTreeCursor");
function unmarshalTreeCursor(cursor) {
  cursor[0] = C2.getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32");
  cursor[1] = C2.getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32");
  cursor[2] = C2.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
  cursor[3] = C2.getValue(TRANSFER_BUFFER + 3 * SIZE_OF_INT, "i32");
}
__name(unmarshalTreeCursor, "unmarshalTreeCursor");
function marshalPoint(address, point2) {
  C2.setValue(address, point2.row, "i32");
  C2.setValue(address + SIZE_OF_INT, point2.column, "i32");
}
__name(marshalPoint, "marshalPoint");
function unmarshalPoint(address) {
  const result = {
    row: C2.getValue(address, "i32") >>> 0,
    column: C2.getValue(address + SIZE_OF_INT, "i32") >>> 0
  };
  return result;
}
__name(unmarshalPoint, "unmarshalPoint");
function marshalRange(address, range2) {
  marshalPoint(address, range2.startPosition);
  address += SIZE_OF_POINT;
  marshalPoint(address, range2.endPosition);
  address += SIZE_OF_POINT;
  C2.setValue(address, range2.startIndex, "i32");
  address += SIZE_OF_INT;
  C2.setValue(address, range2.endIndex, "i32");
  address += SIZE_OF_INT;
}
__name(marshalRange, "marshalRange");
function unmarshalRange(address) {
  const result = {};
  result.startPosition = unmarshalPoint(address);
  address += SIZE_OF_POINT;
  result.endPosition = unmarshalPoint(address);
  address += SIZE_OF_POINT;
  result.startIndex = C2.getValue(address, "i32") >>> 0;
  address += SIZE_OF_INT;
  result.endIndex = C2.getValue(address, "i32") >>> 0;
  return result;
}
__name(unmarshalRange, "unmarshalRange");
function marshalEdit(edit, address = TRANSFER_BUFFER) {
  marshalPoint(address, edit.startPosition);
  address += SIZE_OF_POINT;
  marshalPoint(address, edit.oldEndPosition);
  address += SIZE_OF_POINT;
  marshalPoint(address, edit.newEndPosition);
  address += SIZE_OF_POINT;
  C2.setValue(address, edit.startIndex, "i32");
  address += SIZE_OF_INT;
  C2.setValue(address, edit.oldEndIndex, "i32");
  address += SIZE_OF_INT;
  C2.setValue(address, edit.newEndIndex, "i32");
  address += SIZE_OF_INT;
}
__name(marshalEdit, "marshalEdit");
function unmarshalLanguageMetadata(address) {
  const result = {};
  result.major_version = C2.getValue(address, "i32");
  address += SIZE_OF_INT;
  result.minor_version = C2.getValue(address, "i32");
  address += SIZE_OF_INT;
  result.field_count = C2.getValue(address, "i32");
  return result;
}
__name(unmarshalLanguageMetadata, "unmarshalLanguageMetadata");
var PREDICATE_STEP_TYPE_CAPTURE = 1;
var PREDICATE_STEP_TYPE_STRING = 2;
var QUERY_WORD_REGEX = /[\w-]+/g;
var CaptureQuantifier = {
  Zero: 0,
  ZeroOrOne: 1,
  ZeroOrMore: 2,
  One: 3,
  OneOrMore: 4
};
var isCaptureStep = /* @__PURE__ */ __name((step) => step.type === "capture", "isCaptureStep");
var isStringStep = /* @__PURE__ */ __name((step) => step.type === "string", "isStringStep");
var QueryErrorKind = {
  Syntax: 1,
  NodeName: 2,
  FieldName: 3,
  CaptureName: 4,
  PatternStructure: 5
};
var QueryError = class _QueryError extends Error {
  constructor(kind, info2, index3, length) {
    super(_QueryError.formatMessage(kind, info2));
    this.kind = kind;
    this.info = info2;
    this.index = index3;
    this.length = length;
    this.name = "QueryError";
  }
  static {
    __name(this, "QueryError");
  }
  /** Formats an error message based on the error kind and info */
  static formatMessage(kind, info2) {
    switch (kind) {
      case QueryErrorKind.NodeName:
        return `Bad node name '${info2.word}'`;
      case QueryErrorKind.FieldName:
        return `Bad field name '${info2.word}'`;
      case QueryErrorKind.CaptureName:
        return `Bad capture name @${info2.word}`;
      case QueryErrorKind.PatternStructure:
        return `Bad pattern structure at offset ${info2.suffix}`;
      case QueryErrorKind.Syntax:
        return `Bad syntax at offset ${info2.suffix}`;
    }
  }
};
function parseAnyPredicate(steps, index3, operator2, textPredicates) {
  if (steps.length !== 3) {
    throw new Error(
      `Wrong number of arguments to \`#${operator2}\` predicate. Expected 2, got ${steps.length - 1}`
    );
  }
  if (!isCaptureStep(steps[1])) {
    throw new Error(
      `First argument of \`#${operator2}\` predicate must be a capture. Got "${steps[1].value}"`
    );
  }
  const isPositive = operator2 === "eq?" || operator2 === "any-eq?";
  const matchAll = !operator2.startsWith("any-");
  if (isCaptureStep(steps[2])) {
    const captureName1 = steps[1].name;
    const captureName2 = steps[2].name;
    textPredicates[index3].push((captures) => {
      const nodes1 = [];
      const nodes2 = [];
      for (const c of captures) {
        if (c.name === captureName1) nodes1.push(c.node);
        if (c.name === captureName2) nodes2.push(c.node);
      }
      const compare2 = /* @__PURE__ */ __name((n1, n2, positive) => {
        return positive ? n1.text === n2.text : n1.text !== n2.text;
      }, "compare");
      return matchAll ? nodes1.every((n1) => nodes2.some((n2) => compare2(n1, n2, isPositive))) : nodes1.some((n1) => nodes2.some((n2) => compare2(n1, n2, isPositive)));
    });
  } else {
    const captureName = steps[1].name;
    const stringValue = steps[2].value;
    const matches = /* @__PURE__ */ __name((n) => n.text === stringValue, "matches");
    const doesNotMatch = /* @__PURE__ */ __name((n) => n.text !== stringValue, "doesNotMatch");
    textPredicates[index3].push((captures) => {
      const nodes = [];
      for (const c of captures) {
        if (c.name === captureName) nodes.push(c.node);
      }
      const test = isPositive ? matches : doesNotMatch;
      return matchAll ? nodes.every(test) : nodes.some(test);
    });
  }
}
__name(parseAnyPredicate, "parseAnyPredicate");
function parseMatchPredicate(steps, index3, operator2, textPredicates) {
  if (steps.length !== 3) {
    throw new Error(
      `Wrong number of arguments to \`#${operator2}\` predicate. Expected 2, got ${steps.length - 1}.`
    );
  }
  if (steps[1].type !== "capture") {
    throw new Error(
      `First argument of \`#${operator2}\` predicate must be a capture. Got "${steps[1].value}".`
    );
  }
  if (steps[2].type !== "string") {
    throw new Error(
      `Second argument of \`#${operator2}\` predicate must be a string. Got @${steps[2].name}.`
    );
  }
  const isPositive = operator2 === "match?" || operator2 === "any-match?";
  const matchAll = !operator2.startsWith("any-");
  const captureName = steps[1].name;
  const regex = new RegExp(steps[2].value);
  textPredicates[index3].push((captures) => {
    const nodes = [];
    for (const c of captures) {
      if (c.name === captureName) nodes.push(c.node.text);
    }
    const test = /* @__PURE__ */ __name((text2, positive) => {
      return positive ? regex.test(text2) : !regex.test(text2);
    }, "test");
    if (nodes.length === 0) return !isPositive;
    return matchAll ? nodes.every((text2) => test(text2, isPositive)) : nodes.some((text2) => test(text2, isPositive));
  });
}
__name(parseMatchPredicate, "parseMatchPredicate");
function parseAnyOfPredicate(steps, index3, operator2, textPredicates) {
  if (steps.length < 2) {
    throw new Error(
      `Wrong number of arguments to \`#${operator2}\` predicate. Expected at least 1. Got ${steps.length - 1}.`
    );
  }
  if (steps[1].type !== "capture") {
    throw new Error(
      `First argument of \`#${operator2}\` predicate must be a capture. Got "${steps[1].value}".`
    );
  }
  const isPositive = operator2 === "any-of?";
  const captureName = steps[1].name;
  const stringSteps = steps.slice(2);
  if (!stringSteps.every(isStringStep)) {
    throw new Error(
      `Arguments to \`#${operator2}\` predicate must be strings.".`
    );
  }
  const values = stringSteps.map((s) => s.value);
  textPredicates[index3].push((captures) => {
    const nodes = [];
    for (const c of captures) {
      if (c.name === captureName) nodes.push(c.node.text);
    }
    if (nodes.length === 0) return !isPositive;
    return nodes.every((text2) => values.includes(text2)) === isPositive;
  });
}
__name(parseAnyOfPredicate, "parseAnyOfPredicate");
function parseIsPredicate(steps, index3, operator2, assertedProperties, refutedProperties) {
  if (steps.length < 2 || steps.length > 3) {
    throw new Error(
      `Wrong number of arguments to \`#${operator2}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
    );
  }
  if (!steps.every(isStringStep)) {
    throw new Error(
      `Arguments to \`#${operator2}\` predicate must be strings.".`
    );
  }
  const properties = operator2 === "is?" ? assertedProperties : refutedProperties;
  if (!properties[index3]) properties[index3] = {};
  properties[index3][steps[1].value] = steps[2]?.value ?? null;
}
__name(parseIsPredicate, "parseIsPredicate");
function parseSetDirective(steps, index3, setProperties) {
  if (steps.length < 2 || steps.length > 3) {
    throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
  }
  if (!steps.every(isStringStep)) {
    throw new Error(`Arguments to \`#set!\` predicate must be strings.".`);
  }
  if (!setProperties[index3]) setProperties[index3] = {};
  setProperties[index3][steps[1].value] = steps[2]?.value ?? null;
}
__name(parseSetDirective, "parseSetDirective");
function parsePattern(index3, stepType, stepValueId, captureNames, stringValues, steps, textPredicates, predicates, setProperties, assertedProperties, refutedProperties) {
  if (stepType === PREDICATE_STEP_TYPE_CAPTURE) {
    const name22 = captureNames[stepValueId];
    steps.push({ type: "capture", name: name22 });
  } else if (stepType === PREDICATE_STEP_TYPE_STRING) {
    steps.push({ type: "string", value: stringValues[stepValueId] });
  } else if (steps.length > 0) {
    if (steps[0].type !== "string") {
      throw new Error("Predicates must begin with a literal value");
    }
    const operator2 = steps[0].value;
    switch (operator2) {
      case "any-not-eq?":
      case "not-eq?":
      case "any-eq?":
      case "eq?":
        parseAnyPredicate(steps, index3, operator2, textPredicates);
        break;
      case "any-not-match?":
      case "not-match?":
      case "any-match?":
      case "match?":
        parseMatchPredicate(steps, index3, operator2, textPredicates);
        break;
      case "not-any-of?":
      case "any-of?":
        parseAnyOfPredicate(steps, index3, operator2, textPredicates);
        break;
      case "is?":
      case "is-not?":
        parseIsPredicate(steps, index3, operator2, assertedProperties, refutedProperties);
        break;
      case "set!":
        parseSetDirective(steps, index3, setProperties);
        break;
      default:
        predicates[index3].push({ operator: operator2, operands: steps.slice(1) });
    }
    steps.length = 0;
  }
}
__name(parsePattern, "parsePattern");
var Query = class {
  static {
    __name(this, "Query");
  }
  /** @internal */
  [0] = 0;
  // Internal handle for WASM
  /** @internal */
  exceededMatchLimit;
  /** @internal */
  textPredicates;
  /** The names of the captures used in the query. */
  captureNames;
  /** The quantifiers of the captures used in the query. */
  captureQuantifiers;
  /**
   * The other user-defined predicates associated with the given index.
   *
   * This includes predicates with operators other than:
   * - `match?`
   * - `eq?` and `not-eq?`
   * - `any-of?` and `not-any-of?`
   * - `is?` and `is-not?`
   * - `set!`
   */
  predicates;
  /** The properties for predicates with the operator `set!`. */
  setProperties;
  /** The properties for predicates with the operator `is?`. */
  assertedProperties;
  /** The properties for predicates with the operator `is-not?`. */
  refutedProperties;
  /** The maximum number of in-progress matches for this cursor. */
  matchLimit;
  /**
   * Create a new query from a string containing one or more S-expression
   * patterns.
   *
   * The query is associated with a particular language, and can only be run
   * on syntax nodes parsed with that language. References to Queries can be
   * shared between multiple threads.
   *
   * @link {@see https://tree-sitter.github.io/tree-sitter/using-parsers/queries}
   */
  constructor(language2, source3) {
    const sourceLength = C2.lengthBytesUTF8(source3);
    const sourceAddress = C2._malloc(sourceLength + 1);
    C2.stringToUTF8(source3, sourceAddress, sourceLength + 1);
    const address = C2._ts_query_new(
      language2[0],
      sourceAddress,
      sourceLength,
      TRANSFER_BUFFER,
      TRANSFER_BUFFER + SIZE_OF_INT
    );
    if (!address) {
      const errorId = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
      const errorByte = C2.getValue(TRANSFER_BUFFER, "i32");
      const errorIndex = C2.UTF8ToString(sourceAddress, errorByte).length;
      const suffix = source3.slice(errorIndex, errorIndex + 100).split("\n")[0];
      const word = suffix.match(QUERY_WORD_REGEX)?.[0] ?? "";
      C2._free(sourceAddress);
      switch (errorId) {
        case QueryErrorKind.Syntax:
          throw new QueryError(QueryErrorKind.Syntax, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
        case QueryErrorKind.NodeName:
          throw new QueryError(errorId, { word }, errorIndex, word.length);
        case QueryErrorKind.FieldName:
          throw new QueryError(errorId, { word }, errorIndex, word.length);
        case QueryErrorKind.CaptureName:
          throw new QueryError(errorId, { word }, errorIndex, word.length);
        case QueryErrorKind.PatternStructure:
          throw new QueryError(errorId, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
      }
    }
    const stringCount = C2._ts_query_string_count(address);
    const captureCount = C2._ts_query_capture_count(address);
    const patternCount = C2._ts_query_pattern_count(address);
    const captureNames = new Array(captureCount);
    const captureQuantifiers = new Array(patternCount);
    const stringValues = new Array(stringCount);
    for (let i2 = 0; i2 < captureCount; i2++) {
      const nameAddress = C2._ts_query_capture_name_for_id(
        address,
        i2,
        TRANSFER_BUFFER
      );
      const nameLength = C2.getValue(TRANSFER_BUFFER, "i32");
      captureNames[i2] = C2.UTF8ToString(nameAddress, nameLength);
    }
    for (let i2 = 0; i2 < patternCount; i2++) {
      const captureQuantifiersArray = new Array(captureCount);
      for (let j = 0; j < captureCount; j++) {
        const quantifier = C2._ts_query_capture_quantifier_for_id(address, i2, j);
        captureQuantifiersArray[j] = quantifier;
      }
      captureQuantifiers[i2] = captureQuantifiersArray;
    }
    for (let i2 = 0; i2 < stringCount; i2++) {
      const valueAddress = C2._ts_query_string_value_for_id(
        address,
        i2,
        TRANSFER_BUFFER
      );
      const nameLength = C2.getValue(TRANSFER_BUFFER, "i32");
      stringValues[i2] = C2.UTF8ToString(valueAddress, nameLength);
    }
    const setProperties = new Array(patternCount);
    const assertedProperties = new Array(patternCount);
    const refutedProperties = new Array(patternCount);
    const predicates = new Array(patternCount);
    const textPredicates = new Array(patternCount);
    for (let i2 = 0; i2 < patternCount; i2++) {
      const predicatesAddress = C2._ts_query_predicates_for_pattern(address, i2, TRANSFER_BUFFER);
      const stepCount = C2.getValue(TRANSFER_BUFFER, "i32");
      predicates[i2] = [];
      textPredicates[i2] = [];
      const steps = new Array();
      let stepAddress = predicatesAddress;
      for (let j = 0; j < stepCount; j++) {
        const stepType = C2.getValue(stepAddress, "i32");
        stepAddress += SIZE_OF_INT;
        const stepValueId = C2.getValue(stepAddress, "i32");
        stepAddress += SIZE_OF_INT;
        parsePattern(
          i2,
          stepType,
          stepValueId,
          captureNames,
          stringValues,
          steps,
          textPredicates,
          predicates,
          setProperties,
          assertedProperties,
          refutedProperties
        );
      }
      Object.freeze(textPredicates[i2]);
      Object.freeze(predicates[i2]);
      Object.freeze(setProperties[i2]);
      Object.freeze(assertedProperties[i2]);
      Object.freeze(refutedProperties[i2]);
    }
    C2._free(sourceAddress);
    this[0] = address;
    this.captureNames = captureNames;
    this.captureQuantifiers = captureQuantifiers;
    this.textPredicates = textPredicates;
    this.predicates = predicates;
    this.setProperties = setProperties;
    this.assertedProperties = assertedProperties;
    this.refutedProperties = refutedProperties;
    this.exceededMatchLimit = false;
  }
  /** Delete the query, freeing its resources. */
  delete() {
    C2._ts_query_delete(this[0]);
    this[0] = 0;
  }
  /**
   * Iterate over all of the matches in the order that they were found.
   *
   * Each match contains the index of the pattern that matched, and a list of
   * captures. Because multiple patterns can match the same set of nodes,
   * one match may contain captures that appear *before* some of the
   * captures from a previous match.
   *
   * @param {Node} node - The node to execute the query on.
   *
   * @param {QueryOptions} options - Options for query execution.
   */
  matches(node, options4 = {}) {
    const startPosition = options4.startPosition ?? ZERO_POINT;
    const endPosition = options4.endPosition ?? ZERO_POINT;
    const startIndex = options4.startIndex ?? 0;
    const endIndex = options4.endIndex ?? 0;
    const matchLimit = options4.matchLimit ?? 4294967295;
    const maxStartDepth = options4.maxStartDepth ?? 4294967295;
    const timeoutMicros = options4.timeoutMicros ?? 0;
    const progressCallback = options4.progressCallback;
    if (typeof matchLimit !== "number") {
      throw new Error("Arguments must be numbers");
    }
    this.matchLimit = matchLimit;
    if (endIndex !== 0 && startIndex > endIndex) {
      throw new Error("`startIndex` cannot be greater than `endIndex`");
    }
    if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
      throw new Error("`startPosition` cannot be greater than `endPosition`");
    }
    if (progressCallback) {
      C2.currentQueryProgressCallback = progressCallback;
    }
    marshalNode(node);
    C2._ts_query_matches_wasm(
      this[0],
      node.tree[0],
      startPosition.row,
      startPosition.column,
      endPosition.row,
      endPosition.column,
      startIndex,
      endIndex,
      matchLimit,
      maxStartDepth,
      timeoutMicros
    );
    const rawCount = C2.getValue(TRANSFER_BUFFER, "i32");
    const startAddress = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const didExceedMatchLimit = C2.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
    const result = new Array(rawCount);
    this.exceededMatchLimit = Boolean(didExceedMatchLimit);
    let filteredCount = 0;
    let address = startAddress;
    for (let i2 = 0; i2 < rawCount; i2++) {
      const patternIndex = C2.getValue(address, "i32");
      address += SIZE_OF_INT;
      const captureCount = C2.getValue(address, "i32");
      address += SIZE_OF_INT;
      const captures = new Array(captureCount);
      address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
      if (this.textPredicates[patternIndex].every((p) => p(captures))) {
        result[filteredCount] = { pattern: patternIndex, patternIndex, captures };
        const setProperties = this.setProperties[patternIndex];
        result[filteredCount].setProperties = setProperties;
        const assertedProperties = this.assertedProperties[patternIndex];
        result[filteredCount].assertedProperties = assertedProperties;
        const refutedProperties = this.refutedProperties[patternIndex];
        result[filteredCount].refutedProperties = refutedProperties;
        filteredCount++;
      }
    }
    result.length = filteredCount;
    C2._free(startAddress);
    C2.currentQueryProgressCallback = null;
    return result;
  }
  /**
   * Iterate over all of the individual captures in the order that they
   * appear.
   *
   * This is useful if you don't care about which pattern matched, and just
   * want a single, ordered sequence of captures.
   *
   * @param {Node} node - The node to execute the query on.
   *
   * @param {QueryOptions} options - Options for query execution.
   */
  captures(node, options4 = {}) {
    const startPosition = options4.startPosition ?? ZERO_POINT;
    const endPosition = options4.endPosition ?? ZERO_POINT;
    const startIndex = options4.startIndex ?? 0;
    const endIndex = options4.endIndex ?? 0;
    const matchLimit = options4.matchLimit ?? 4294967295;
    const maxStartDepth = options4.maxStartDepth ?? 4294967295;
    const timeoutMicros = options4.timeoutMicros ?? 0;
    const progressCallback = options4.progressCallback;
    if (typeof matchLimit !== "number") {
      throw new Error("Arguments must be numbers");
    }
    this.matchLimit = matchLimit;
    if (endIndex !== 0 && startIndex > endIndex) {
      throw new Error("`startIndex` cannot be greater than `endIndex`");
    }
    if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
      throw new Error("`startPosition` cannot be greater than `endPosition`");
    }
    if (progressCallback) {
      C2.currentQueryProgressCallback = progressCallback;
    }
    marshalNode(node);
    C2._ts_query_captures_wasm(
      this[0],
      node.tree[0],
      startPosition.row,
      startPosition.column,
      endPosition.row,
      endPosition.column,
      startIndex,
      endIndex,
      matchLimit,
      maxStartDepth,
      timeoutMicros
    );
    const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
    const startAddress = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const didExceedMatchLimit = C2.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
    const result = new Array();
    this.exceededMatchLimit = Boolean(didExceedMatchLimit);
    const captures = new Array();
    let address = startAddress;
    for (let i2 = 0; i2 < count2; i2++) {
      const patternIndex = C2.getValue(address, "i32");
      address += SIZE_OF_INT;
      const captureCount = C2.getValue(address, "i32");
      address += SIZE_OF_INT;
      const captureIndex = C2.getValue(address, "i32");
      address += SIZE_OF_INT;
      captures.length = captureCount;
      address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
      if (this.textPredicates[patternIndex].every((p) => p(captures))) {
        const capture = captures[captureIndex];
        const setProperties = this.setProperties[patternIndex];
        capture.setProperties = setProperties;
        const assertedProperties = this.assertedProperties[patternIndex];
        capture.assertedProperties = assertedProperties;
        const refutedProperties = this.refutedProperties[patternIndex];
        capture.refutedProperties = refutedProperties;
        result.push(capture);
      }
    }
    C2._free(startAddress);
    C2.currentQueryProgressCallback = null;
    return result;
  }
  /** Get the predicates for a given pattern. */
  predicatesForPattern(patternIndex) {
    return this.predicates[patternIndex];
  }
  /**
   * Disable a certain capture within a query.
   *
   * This prevents the capture from being returned in matches, and also
   * avoids any resource usage associated with recording the capture.
   */
  disableCapture(captureName) {
    const captureNameLength = C2.lengthBytesUTF8(captureName);
    const captureNameAddress = C2._malloc(captureNameLength + 1);
    C2.stringToUTF8(captureName, captureNameAddress, captureNameLength + 1);
    C2._ts_query_disable_capture(this[0], captureNameAddress, captureNameLength);
    C2._free(captureNameAddress);
  }
  /**
   * Disable a certain pattern within a query.
   *
   * This prevents the pattern from matching, and also avoids any resource
   * usage associated with the pattern. This throws an error if the pattern
   * index is out of bounds.
   */
  disablePattern(patternIndex) {
    if (patternIndex >= this.predicates.length) {
      throw new Error(
        `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
      );
    }
    C2._ts_query_disable_pattern(this[0], patternIndex);
  }
  /**
   * Check if, on its last execution, this cursor exceeded its maximum number
   * of in-progress matches.
   */
  didExceedMatchLimit() {
    return this.exceededMatchLimit;
  }
  /** Get the byte offset where the given pattern starts in the query's source. */
  startIndexForPattern(patternIndex) {
    if (patternIndex >= this.predicates.length) {
      throw new Error(
        `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
      );
    }
    return C2._ts_query_start_byte_for_pattern(this[0], patternIndex);
  }
  /** Get the byte offset where the given pattern ends in the query's source. */
  endIndexForPattern(patternIndex) {
    if (patternIndex >= this.predicates.length) {
      throw new Error(
        `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
      );
    }
    return C2._ts_query_end_byte_for_pattern(this[0], patternIndex);
  }
  /** Get the number of patterns in the query. */
  patternCount() {
    return C2._ts_query_pattern_count(this[0]);
  }
  /** Get the index for a given capture name. */
  captureIndexForName(captureName) {
    return this.captureNames.indexOf(captureName);
  }
  /** Check if a given pattern within a query has a single root node. */
  isPatternRooted(patternIndex) {
    return C2._ts_query_is_pattern_rooted(this[0], patternIndex) === 1;
  }
  /** Check if a given pattern within a query has a single root node. */
  isPatternNonLocal(patternIndex) {
    return C2._ts_query_is_pattern_non_local(this[0], patternIndex) === 1;
  }
  /**
   * Check if a given step in a query is 'definite'.
   *
   * A query step is 'definite' if its parent pattern will be guaranteed to
   * match successfully once it reaches the step.
   */
  isPatternGuaranteedAtStep(byteIndex) {
    return C2._ts_query_is_pattern_guaranteed_at_step(this[0], byteIndex) === 1;
  }
};
var LANGUAGE_FUNCTION_REGEX = /^tree_sitter_\w+$/;
var Language2 = class _Language {
  static {
    __name(this, "Language");
  }
  /** @internal */
  [0] = 0;
  // Internal handle for WASM
  /**
   * A list of all node types in the language. The index of each type in this
   * array is its node type id.
   */
  types;
  /**
   * A list of all field names in the language. The index of each field name in
   * this array is its field id.
   */
  fields;
  /** @internal */
  constructor(internal, address) {
    assertInternal(internal);
    this[0] = address;
    this.types = new Array(C2._ts_language_symbol_count(this[0]));
    for (let i2 = 0, n = this.types.length; i2 < n; i2++) {
      if (C2._ts_language_symbol_type(this[0], i2) < 2) {
        this.types[i2] = C2.UTF8ToString(C2._ts_language_symbol_name(this[0], i2));
      }
    }
    this.fields = new Array(C2._ts_language_field_count(this[0]) + 1);
    for (let i2 = 0, n = this.fields.length; i2 < n; i2++) {
      const fieldName = C2._ts_language_field_name_for_id(this[0], i2);
      if (fieldName !== 0) {
        this.fields[i2] = C2.UTF8ToString(fieldName);
      } else {
        this.fields[i2] = null;
      }
    }
  }
  /**
   * Gets the name of the language.
   */
  get name() {
    const ptr = C2._ts_language_name(this[0]);
    if (ptr === 0) return null;
    return C2.UTF8ToString(ptr);
  }
  /**
   * @deprecated since version 0.25.0, use {@link Language#abiVersion} instead
   * Gets the version of the language.
   */
  get version() {
    return C2._ts_language_version(this[0]);
  }
  /**
   * Gets the ABI version of the language.
   */
  get abiVersion() {
    return C2._ts_language_abi_version(this[0]);
  }
  /**
  * Get the metadata for this language. This information is generated by the
  * CLI, and relies on the language author providing the correct metadata in
  * the language's `tree-sitter.json` file.
  */
  get metadata() {
    C2._ts_language_metadata(this[0]);
    const length = C2.getValue(TRANSFER_BUFFER, "i32");
    const address = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    if (length === 0) return null;
    return unmarshalLanguageMetadata(address);
  }
  /**
   * Gets the number of fields in the language.
   */
  get fieldCount() {
    return this.fields.length - 1;
  }
  /**
   * Gets the number of states in the language.
   */
  get stateCount() {
    return C2._ts_language_state_count(this[0]);
  }
  /**
   * Get the field id for a field name.
   */
  fieldIdForName(fieldName) {
    const result = this.fields.indexOf(fieldName);
    return result !== -1 ? result : null;
  }
  /**
   * Get the field name for a field id.
   */
  fieldNameForId(fieldId) {
    return this.fields[fieldId] ?? null;
  }
  /**
   * Get the node type id for a node type name.
   */
  idForNodeType(type, named2) {
    const typeLength = C2.lengthBytesUTF8(type);
    const typeAddress = C2._malloc(typeLength + 1);
    C2.stringToUTF8(type, typeAddress, typeLength + 1);
    const result = C2._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named2 ? 1 : 0);
    C2._free(typeAddress);
    return result || null;
  }
  /**
   * Gets the number of node types in the language.
   */
  get nodeTypeCount() {
    return C2._ts_language_symbol_count(this[0]);
  }
  /**
   * Get the node type name for a node type id.
   */
  nodeTypeForId(typeId) {
    const name22 = C2._ts_language_symbol_name(this[0], typeId);
    return name22 ? C2.UTF8ToString(name22) : null;
  }
  /**
   * Check if a node type is named.
   *
   * @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/2-basic-parsing.html#named-vs-anonymous-nodes}
   */
  nodeTypeIsNamed(typeId) {
    return C2._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
  }
  /**
   * Check if a node type is visible.
   */
  nodeTypeIsVisible(typeId) {
    return C2._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
  }
  /**
   * Get the supertypes ids of this language.
   *
   * @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types.html?highlight=supertype#supertype-nodes}
   */
  get supertypes() {
    C2._ts_language_supertypes_wasm(this[0]);
    const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
    const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const result = new Array(count2);
    if (count2 > 0) {
      let address = buffer;
      for (let i2 = 0; i2 < count2; i2++) {
        result[i2] = C2.getValue(address, "i16");
        address += SIZE_OF_SHORT;
      }
    }
    return result;
  }
  /**
   * Get the subtype ids for a given supertype node id.
   */
  subtypes(supertype) {
    C2._ts_language_subtypes_wasm(this[0], supertype);
    const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
    const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const result = new Array(count2);
    if (count2 > 0) {
      let address = buffer;
      for (let i2 = 0; i2 < count2; i2++) {
        result[i2] = C2.getValue(address, "i16");
        address += SIZE_OF_SHORT;
      }
    }
    return result;
  }
  /**
   * Get the next state id for a given state id and node type id.
   */
  nextState(stateId, typeId) {
    return C2._ts_language_next_state(this[0], stateId, typeId);
  }
  /**
   * Create a new lookahead iterator for this language and parse state.
   *
   * This returns `null` if state is invalid for this language.
   *
   * Iterating {@link LookaheadIterator} will yield valid symbols in the given
   * parse state. Newly created lookahead iterators will return the `ERROR`
   * symbol from {@link LookaheadIterator#currentType}.
   *
   * Lookahead iterators can be useful for generating suggestions and improving
   * syntax error diagnostics. To get symbols valid in an `ERROR` node, use the
   * lookahead iterator on its first leaf node state. For `MISSING` nodes, a
   * lookahead iterator created on the previous non-extra leaf node may be
   * appropriate.
   */
  lookaheadIterator(stateId) {
    const address = C2._ts_lookahead_iterator_new(this[0], stateId);
    if (address) return new LookaheadIterator(INTERNAL, address, this);
    return null;
  }
  /**
   * @deprecated since version 0.25.0, call `new` on a {@link Query} instead
   *
   * Create a new query from a string containing one or more S-expression
   * patterns.
   *
   * The query is associated with a particular language, and can only be run
   * on syntax nodes parsed with that language. References to Queries can be
   * shared between multiple threads.
   *
   * @link {@see https://tree-sitter.github.io/tree-sitter/using-parsers/queries}
   */
  query(source3) {
    console.warn("Language.query is deprecated. Use new Query(language, source) instead.");
    return new Query(this, source3);
  }
  /**
   * Load a language from a WebAssembly module.
   * The module can be provided as a path to a file or as a buffer.
   */
  static async load(input) {
    let bytes;
    if (input instanceof Uint8Array) {
      bytes = Promise.resolve(input);
    } else {
      if (globalThis.process?.versions.node) {
        const fs2 = __require2("fs/promises");
        bytes = fs2.readFile(input);
      } else {
        bytes = fetch(input).then((response) => response.arrayBuffer().then((buffer) => {
          if (response.ok) {
            return new Uint8Array(buffer);
          } else {
            const body2 = new TextDecoder("utf-8").decode(buffer);
            throw new Error(`Language.load failed with status ${response.status}.

${body2}`);
          }
        }));
      }
    }
    const mod = await C2.loadWebAssemblyModule(await bytes, { loadAsync: true });
    const symbolNames = Object.keys(mod);
    const functionName = symbolNames.find((key2) => LANGUAGE_FUNCTION_REGEX.test(key2) && !key2.includes("external_scanner_"));
    if (!functionName) {
      console.log(`Couldn't find language function in WASM file. Symbols:
${JSON.stringify(symbolNames, null, 2)}`);
      throw new Error("Language.load failed: no language function found in WASM file");
    }
    const languageAddress = mod[functionName]();
    return new _Language(INTERNAL, languageAddress);
  }
};
var Module2 = (() => {
  var _scriptName = import.meta.url;
  return async function(moduleArg = {}) {
    var moduleRtn;
    var Module = moduleArg;
    var readyPromiseResolve, readyPromiseReject;
    var readyPromise = new Promise((resolve, reject) => {
      readyPromiseResolve = resolve;
      readyPromiseReject = reject;
    });
    var ENVIRONMENT_IS_WEB = typeof window == "object";
    var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != "undefined";
    var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";
    var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
    if (ENVIRONMENT_IS_NODE) {
      const { createRequire } = await import("module");
      var require = createRequire("/");
    }
    Module.currentQueryProgressCallback = null;
    Module.currentProgressCallback = null;
    Module.currentLogCallback = null;
    Module.currentParseCallback = null;
    var moduleOverrides = Object.assign({}, Module);
    var arguments_ = [];
    var thisProgram = "./this.program";
    var quit_ = /* @__PURE__ */ __name((status, toThrow) => {
      throw toThrow;
    }, "quit_");
    var scriptDirectory = "";
    function locateFile(path2) {
      if (Module["locateFile"]) {
        return Module["locateFile"](path2, scriptDirectory);
      }
      return scriptDirectory + path2;
    }
    __name(locateFile, "locateFile");
    var readAsync, readBinary;
    if (ENVIRONMENT_IS_NODE) {
      var fs = require("fs");
      var nodePath = require("path");
      if (!import.meta.url.startsWith("data:")) {
        scriptDirectory = nodePath.dirname(require("url").fileURLToPath(import.meta.url)) + "/";
      }
      readBinary = /* @__PURE__ */ __name((filename) => {
        filename = isFileURI(filename) ? new URL(filename) : filename;
        var ret = fs.readFileSync(filename);
        return ret;
      }, "readBinary");
      readAsync = /* @__PURE__ */ __name(async (filename, binary2 = true) => {
        filename = isFileURI(filename) ? new URL(filename) : filename;
        var ret = fs.readFileSync(filename, binary2 ? void 0 : "utf8");
        return ret;
      }, "readAsync");
      if (!Module["thisProgram"] && process.argv.length > 1) {
        thisProgram = process.argv[1].replace(/\\/g, "/");
      }
      arguments_ = process.argv.slice(2);
      quit_ = /* @__PURE__ */ __name((status, toThrow) => {
        process.exitCode = status;
        throw toThrow;
      }, "quit_");
    } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
      if (ENVIRONMENT_IS_WORKER) {
        scriptDirectory = self.location.href;
      } else if (typeof document != "undefined" && document.currentScript) {
        scriptDirectory = document.currentScript.src;
      }
      if (_scriptName) {
        scriptDirectory = _scriptName;
      }
      if (scriptDirectory.startsWith("blob:")) {
        scriptDirectory = "";
      } else {
        scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1);
      }
      {
        if (ENVIRONMENT_IS_WORKER) {
          readBinary = /* @__PURE__ */ __name((url) => {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, false);
            xhr.responseType = "arraybuffer";
            xhr.send(null);
            return new Uint8Array(
              /** @type{!ArrayBuffer} */
              xhr.response
            );
          }, "readBinary");
        }
        readAsync = /* @__PURE__ */ __name(async (url) => {
          if (isFileURI(url)) {
            return new Promise((resolve, reject) => {
              var xhr = new XMLHttpRequest();
              xhr.open("GET", url, true);
              xhr.responseType = "arraybuffer";
              xhr.onload = () => {
                if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
                  resolve(xhr.response);
                  return;
                }
                reject(xhr.status);
              };
              xhr.onerror = reject;
              xhr.send(null);
            });
          }
          var response = await fetch(url, {
            credentials: "same-origin"
          });
          if (response.ok) {
            return response.arrayBuffer();
          }
          throw new Error(response.status + " : " + response.url);
        }, "readAsync");
      }
    } else {
    }
    var out = Module["print"] || console.log.bind(console);
    var err = Module["printErr"] || console.error.bind(console);
    Object.assign(Module, moduleOverrides);
    moduleOverrides = null;
    if (Module["arguments"]) arguments_ = Module["arguments"];
    if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
    var dynamicLibraries = Module["dynamicLibraries"] || [];
    var wasmBinary = Module["wasmBinary"];
    var wasmMemory;
    var ABORT = false;
    var EXITSTATUS;
    function assert(condition, text2) {
      if (!condition) {
        abort(text2);
      }
    }
    __name(assert, "assert");
    var HEAP, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64;
    var HEAP_DATA_VIEW;
    var runtimeInitialized = false;
    var dataURIPrefix = "data:application/octet-stream;base64,";
    var isDataURI = /* @__PURE__ */ __name((filename) => filename.startsWith(dataURIPrefix), "isDataURI");
    var isFileURI = /* @__PURE__ */ __name((filename) => filename.startsWith("file://"), "isFileURI");
    function updateMemoryViews() {
      var b = wasmMemory.buffer;
      Module["HEAP_DATA_VIEW"] = HEAP_DATA_VIEW = new DataView(b);
      Module["HEAP8"] = HEAP8 = new Int8Array(b);
      Module["HEAP16"] = HEAP16 = new Int16Array(b);
      Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
      Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
      Module["HEAP32"] = HEAP32 = new Int32Array(b);
      Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
      Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
      Module["HEAPF64"] = HEAPF64 = new Float64Array(b);
      Module["HEAP64"] = HEAP64 = new BigInt64Array(b);
      Module["HEAPU64"] = HEAPU64 = new BigUint64Array(b);
    }
    __name(updateMemoryViews, "updateMemoryViews");
    if (Module["wasmMemory"]) {
      wasmMemory = Module["wasmMemory"];
    } else {
      var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 33554432;
      wasmMemory = new WebAssembly.Memory({
        "initial": INITIAL_MEMORY / 65536,
        // In theory we should not need to emit the maximum if we want "unlimited"
        // or 4GB of memory, but VMs error on that atm, see
        // https://github.com/emscripten-core/emscripten/issues/14130
        // And in the pthreads case we definitely need to emit a maximum. So
        // always emit one.
        "maximum": 32768
      });
    }
    updateMemoryViews();
    var __ATPRERUN__ = [];
    var __ATINIT__ = [];
    var __ATMAIN__ = [];
    var __ATEXIT__ = [];
    var __ATPOSTRUN__ = [];
    var __RELOC_FUNCS__ = [];
    function preRun() {
      if (Module["preRun"]) {
        if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]];
        while (Module["preRun"].length) {
          addOnPreRun(Module["preRun"].shift());
        }
      }
      callRuntimeCallbacks(__ATPRERUN__);
    }
    __name(preRun, "preRun");
    function initRuntime() {
      runtimeInitialized = true;
      callRuntimeCallbacks(__RELOC_FUNCS__);
      callRuntimeCallbacks(__ATINIT__);
    }
    __name(initRuntime, "initRuntime");
    function preMain() {
      callRuntimeCallbacks(__ATMAIN__);
    }
    __name(preMain, "preMain");
    function postRun() {
      if (Module["postRun"]) {
        if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]];
        while (Module["postRun"].length) {
          addOnPostRun(Module["postRun"].shift());
        }
      }
      callRuntimeCallbacks(__ATPOSTRUN__);
    }
    __name(postRun, "postRun");
    function addOnPreRun(cb) {
      __ATPRERUN__.unshift(cb);
    }
    __name(addOnPreRun, "addOnPreRun");
    function addOnInit(cb) {
      __ATINIT__.unshift(cb);
    }
    __name(addOnInit, "addOnInit");
    function addOnPreMain(cb) {
      __ATMAIN__.unshift(cb);
    }
    __name(addOnPreMain, "addOnPreMain");
    function addOnExit(cb) {
    }
    __name(addOnExit, "addOnExit");
    function addOnPostRun(cb) {
      __ATPOSTRUN__.unshift(cb);
    }
    __name(addOnPostRun, "addOnPostRun");
    var runDependencies = 0;
    var dependenciesFulfilled = null;
    function getUniqueRunDependency(id3) {
      return id3;
    }
    __name(getUniqueRunDependency, "getUniqueRunDependency");
    function addRunDependency(id3) {
      runDependencies++;
      Module["monitorRunDependencies"]?.(runDependencies);
    }
    __name(addRunDependency, "addRunDependency");
    function removeRunDependency(id3) {
      runDependencies--;
      Module["monitorRunDependencies"]?.(runDependencies);
      if (runDependencies == 0) {
        if (dependenciesFulfilled) {
          var callback = dependenciesFulfilled;
          dependenciesFulfilled = null;
          callback();
        }
      }
    }
    __name(removeRunDependency, "removeRunDependency");
    function abort(what) {
      Module["onAbort"]?.(what);
      what = "Aborted(" + what + ")";
      err(what);
      ABORT = true;
      what += ". Build with -sASSERTIONS for more info.";
      var e = new WebAssembly.RuntimeError(what);
      readyPromiseReject(e);
      throw e;
    }
    __name(abort, "abort");
    var wasmBinaryFile;
    function findWasmBinary() {
      if (Module["locateFile"]) {
        var f = "tree-sitter.wasm";
        if (!isDataURI(f)) {
          return locateFile(f);
        }
        return f;
      }
      return new URL("tree-sitter.wasm", import.meta.url).href;
    }
    __name(findWasmBinary, "findWasmBinary");
    function getBinarySync(file) {
      if (file == wasmBinaryFile && wasmBinary) {
        return new Uint8Array(wasmBinary);
      }
      if (readBinary) {
        return readBinary(file);
      }
      throw "both async and sync fetching of the wasm failed";
    }
    __name(getBinarySync, "getBinarySync");
    async function getWasmBinary(binaryFile) {
      if (!wasmBinary) {
        try {
          var response = await readAsync(binaryFile);
          return new Uint8Array(response);
        } catch {
        }
      }
      return getBinarySync(binaryFile);
    }
    __name(getWasmBinary, "getWasmBinary");
    async function instantiateArrayBuffer(binaryFile, imports) {
      try {
        var binary2 = await getWasmBinary(binaryFile);
        var instance2 = await WebAssembly.instantiate(binary2, imports);
        return instance2;
      } catch (reason) {
        err(`failed to asynchronously prepare wasm: ${reason}`);
        abort(reason);
      }
    }
    __name(instantiateArrayBuffer, "instantiateArrayBuffer");
    async function instantiateAsync(binary2, binaryFile, imports) {
      if (!binary2 && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {
        try {
          var response = fetch(binaryFile, {
            credentials: "same-origin"
          });
          var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);
          return instantiationResult;
        } catch (reason) {
          err(`wasm streaming compile failed: ${reason}`);
          err("falling back to ArrayBuffer instantiation");
        }
      }
      return instantiateArrayBuffer(binaryFile, imports);
    }
    __name(instantiateAsync, "instantiateAsync");
    function getWasmImports() {
      return {
        "env": wasmImports,
        "wasi_snapshot_preview1": wasmImports,
        "GOT.mem": new Proxy(wasmImports, GOTHandler),
        "GOT.func": new Proxy(wasmImports, GOTHandler)
      };
    }
    __name(getWasmImports, "getWasmImports");
    async function createWasm() {
      function receiveInstance(instance2, module2) {
        wasmExports = instance2.exports;
        wasmExports = relocateExports(wasmExports, 1024);
        var metadata2 = getDylinkMetadata(module2);
        if (metadata2.neededDynlibs) {
          dynamicLibraries = metadata2.neededDynlibs.concat(dynamicLibraries);
        }
        mergeLibSymbols(wasmExports, "main");
        LDSO.init();
        loadDylibs();
        addOnInit(wasmExports["__wasm_call_ctors"]);
        __RELOC_FUNCS__.push(wasmExports["__wasm_apply_data_relocs"]);
        removeRunDependency("wasm-instantiate");
        return wasmExports;
      }
      __name(receiveInstance, "receiveInstance");
      addRunDependency("wasm-instantiate");
      function receiveInstantiationResult(result2) {
        return receiveInstance(result2["instance"], result2["module"]);
      }
      __name(receiveInstantiationResult, "receiveInstantiationResult");
      var info2 = getWasmImports();
      if (Module["instantiateWasm"]) {
        try {
          return Module["instantiateWasm"](info2, receiveInstance);
        } catch (e) {
          err(`Module.instantiateWasm callback failed with error: ${e}`);
          readyPromiseReject(e);
        }
      }
      wasmBinaryFile ??= findWasmBinary();
      try {
        var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info2);
        var exports = receiveInstantiationResult(result);
        return exports;
      } catch (e) {
        readyPromiseReject(e);
        return Promise.reject(e);
      }
    }
    __name(createWasm, "createWasm");
    var ASM_CONSTS = {};
    class ExitStatus {
      static {
        __name(this, "ExitStatus");
      }
      name = "ExitStatus";
      constructor(status) {
        this.message = `Program terminated with exit(${status})`;
        this.status = status;
      }
    }
    var GOT = {};
    var currentModuleWeakSymbols = /* @__PURE__ */ new Set([]);
    var GOTHandler = {
      get(obj, symName) {
        var rtn = GOT[symName];
        if (!rtn) {
          rtn = GOT[symName] = new WebAssembly.Global({
            "value": "i32",
            "mutable": true
          });
        }
        if (!currentModuleWeakSymbols.has(symName)) {
          rtn.required = true;
        }
        return rtn;
      }
    };
    var LE_HEAP_LOAD_F32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat32(byteOffset, true), "LE_HEAP_LOAD_F32");
    var LE_HEAP_LOAD_F64 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat64(byteOffset, true), "LE_HEAP_LOAD_F64");
    var LE_HEAP_LOAD_I16 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt16(byteOffset, true), "LE_HEAP_LOAD_I16");
    var LE_HEAP_LOAD_I32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt32(byteOffset, true), "LE_HEAP_LOAD_I32");
    var LE_HEAP_LOAD_U16 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getUint16(byteOffset, true), "LE_HEAP_LOAD_U16");
    var LE_HEAP_LOAD_U32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getUint32(byteOffset, true), "LE_HEAP_LOAD_U32");
    var LE_HEAP_STORE_F32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat32(byteOffset, value, true), "LE_HEAP_STORE_F32");
    var LE_HEAP_STORE_F64 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat64(byteOffset, value, true), "LE_HEAP_STORE_F64");
    var LE_HEAP_STORE_I16 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt16(byteOffset, value, true), "LE_HEAP_STORE_I16");
    var LE_HEAP_STORE_I32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt32(byteOffset, value, true), "LE_HEAP_STORE_I32");
    var LE_HEAP_STORE_U16 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setUint16(byteOffset, value, true), "LE_HEAP_STORE_U16");
    var LE_HEAP_STORE_U32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setUint32(byteOffset, value, true), "LE_HEAP_STORE_U32");
    var callRuntimeCallbacks = /* @__PURE__ */ __name((callbacks) => {
      while (callbacks.length > 0) {
        callbacks.shift()(Module);
      }
    }, "callRuntimeCallbacks");
    var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
    var UTF8ArrayToString = /* @__PURE__ */ __name((heapOrArray, idx = 0, maxBytesToRead = NaN) => {
      var endIdx = idx + maxBytesToRead;
      var endPtr = idx;
      while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
      if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
        return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
      }
      var str = "";
      while (idx < endPtr) {
        var u0 = heapOrArray[idx++];
        if (!(u0 & 128)) {
          str += String.fromCharCode(u0);
          continue;
        }
        var u1 = heapOrArray[idx++] & 63;
        if ((u0 & 224) == 192) {
          str += String.fromCharCode((u0 & 31) << 6 | u1);
          continue;
        }
        var u2 = heapOrArray[idx++] & 63;
        if ((u0 & 240) == 224) {
          u0 = (u0 & 15) << 12 | u1 << 6 | u2;
        } else {
          u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
        }
        if (u0 < 65536) {
          str += String.fromCharCode(u0);
        } else {
          var ch = u0 - 65536;
          str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
        }
      }
      return str;
    }, "UTF8ArrayToString");
    var getDylinkMetadata = /* @__PURE__ */ __name((binary2) => {
      var offset = 0;
      var end = 0;
      function getU8() {
        return binary2[offset++];
      }
      __name(getU8, "getU8");
      function getLEB() {
        var ret = 0;
        var mul = 1;
        while (1) {
          var byte = binary2[offset++];
          ret += (byte & 127) * mul;
          mul *= 128;
          if (!(byte & 128)) break;
        }
        return ret;
      }
      __name(getLEB, "getLEB");
      function getString() {
        var len = getLEB();
        offset += len;
        return UTF8ArrayToString(binary2, offset - len, len);
      }
      __name(getString, "getString");
      function failIf(condition, message) {
        if (condition) throw new Error(message);
      }
      __name(failIf, "failIf");
      var name22 = "dylink.0";
      if (binary2 instanceof WebAssembly.Module) {
        var dylinkSection = WebAssembly.Module.customSections(binary2, name22);
        if (dylinkSection.length === 0) {
          name22 = "dylink";
          dylinkSection = WebAssembly.Module.customSections(binary2, name22);
        }
        failIf(dylinkSection.length === 0, "need dylink section");
        binary2 = new Uint8Array(dylinkSection[0]);
        end = binary2.length;
      } else {
        var int32View = new Uint32Array(new Uint8Array(binary2.subarray(0, 24)).buffer);
        var magicNumberFound = int32View[0] == 1836278016 || int32View[0] == 6386541;
        failIf(!magicNumberFound, "need to see wasm magic number");
        failIf(binary2[8] !== 0, "need the dylink section to be first");
        offset = 9;
        var section_size = getLEB();
        end = offset + section_size;
        name22 = getString();
      }
      var customSection = {
        neededDynlibs: [],
        tlsExports: /* @__PURE__ */ new Set(),
        weakImports: /* @__PURE__ */ new Set()
      };
      if (name22 == "dylink") {
        customSection.memorySize = getLEB();
        customSection.memoryAlign = getLEB();
        customSection.tableSize = getLEB();
        customSection.tableAlign = getLEB();
        var neededDynlibsCount = getLEB();
        for (var i2 = 0; i2 < neededDynlibsCount; ++i2) {
          var libname = getString();
          customSection.neededDynlibs.push(libname);
        }
      } else {
        failIf(name22 !== "dylink.0");
        var WASM_DYLINK_MEM_INFO = 1;
        var WASM_DYLINK_NEEDED = 2;
        var WASM_DYLINK_EXPORT_INFO = 3;
        var WASM_DYLINK_IMPORT_INFO = 4;
        var WASM_SYMBOL_TLS = 256;
        var WASM_SYMBOL_BINDING_MASK = 3;
        var WASM_SYMBOL_BINDING_WEAK = 1;
        while (offset < end) {
          var subsectionType = getU8();
          var subsectionSize = getLEB();
          if (subsectionType === WASM_DYLINK_MEM_INFO) {
            customSection.memorySize = getLEB();
            customSection.memoryAlign = getLEB();
            customSection.tableSize = getLEB();
            customSection.tableAlign = getLEB();
          } else if (subsectionType === WASM_DYLINK_NEEDED) {
            var neededDynlibsCount = getLEB();
            for (var i2 = 0; i2 < neededDynlibsCount; ++i2) {
              libname = getString();
              customSection.neededDynlibs.push(libname);
            }
          } else if (subsectionType === WASM_DYLINK_EXPORT_INFO) {
            var count2 = getLEB();
            while (count2--) {
              var symname = getString();
              var flags2 = getLEB();
              if (flags2 & WASM_SYMBOL_TLS) {
                customSection.tlsExports.add(symname);
              }
            }
          } else if (subsectionType === WASM_DYLINK_IMPORT_INFO) {
            var count2 = getLEB();
            while (count2--) {
              var modname = getString();
              var symname = getString();
              var flags2 = getLEB();
              if ((flags2 & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK) {
                customSection.weakImports.add(symname);
              }
            }
          } else {
            offset += subsectionSize;
          }
        }
      }
      return customSection;
    }, "getDylinkMetadata");
    function getValue(ptr, type = "i8") {
      if (type.endsWith("*")) type = "*";
      switch (type) {
        case "i1":
          return HEAP8[ptr];
        case "i8":
          return HEAP8[ptr];
        case "i16":
          return LE_HEAP_LOAD_I16((ptr >> 1) * 2);
        case "i32":
          return LE_HEAP_LOAD_I32((ptr >> 2) * 4);
        case "i64":
          return HEAP64[ptr >> 3];
        case "float":
          return LE_HEAP_LOAD_F32((ptr >> 2) * 4);
        case "double":
          return LE_HEAP_LOAD_F64((ptr >> 3) * 8);
        case "*":
          return LE_HEAP_LOAD_U32((ptr >> 2) * 4);
        default:
          abort(`invalid type for getValue: ${type}`);
      }
    }
    __name(getValue, "getValue");
    var newDSO = /* @__PURE__ */ __name((name22, handle2, syms) => {
      var dso = {
        refcount: Infinity,
        name: name22,
        exports: syms,
        global: true
      };
      LDSO.loadedLibsByName[name22] = dso;
      if (handle2 != void 0) {
        LDSO.loadedLibsByHandle[handle2] = dso;
      }
      return dso;
    }, "newDSO");
    var LDSO = {
      loadedLibsByName: {},
      loadedLibsByHandle: {},
      init() {
        newDSO("__main__", 0, wasmImports);
      }
    };
    var ___heap_base = 78224;
    var alignMemory = /* @__PURE__ */ __name((size, alignment) => Math.ceil(size / alignment) * alignment, "alignMemory");
    var getMemory = /* @__PURE__ */ __name((size) => {
      if (runtimeInitialized) {
        return _calloc(size, 1);
      }
      var ret = ___heap_base;
      var end = ret + alignMemory(size, 16);
      ___heap_base = end;
      GOT["__heap_base"].value = end;
      return ret;
    }, "getMemory");
    var isInternalSym = /* @__PURE__ */ __name((symName) => ["__cpp_exception", "__c_longjmp", "__wasm_apply_data_relocs", "__dso_handle", "__tls_size", "__tls_align", "__set_stack_limits", "_emscripten_tls_init", "__wasm_init_tls", "__wasm_call_ctors", "__start_em_asm", "__stop_em_asm", "__start_em_js", "__stop_em_js"].includes(symName) || symName.startsWith("__em_js__"), "isInternalSym");
    var uleb128Encode = /* @__PURE__ */ __name((n, target) => {
      if (n < 128) {
        target.push(n);
      } else {
        target.push(n % 128 | 128, n >> 7);
      }
    }, "uleb128Encode");
    var sigToWasmTypes = /* @__PURE__ */ __name((sig) => {
      var typeNames = {
        "i": "i32",
        "j": "i64",
        "f": "f32",
        "d": "f64",
        "e": "externref",
        "p": "i32"
      };
      var type = {
        parameters: [],
        results: sig[0] == "v" ? [] : [typeNames[sig[0]]]
      };
      for (var i2 = 1; i2 < sig.length; ++i2) {
        type.parameters.push(typeNames[sig[i2]]);
      }
      return type;
    }, "sigToWasmTypes");
    var generateFuncType = /* @__PURE__ */ __name((sig, target) => {
      var sigRet = sig.slice(0, 1);
      var sigParam = sig.slice(1);
      var typeCodes = {
        "i": 127,
        // i32
        "p": 127,
        // i32
        "j": 126,
        // i64
        "f": 125,
        // f32
        "d": 124,
        // f64
        "e": 111
      };
      target.push(96);
      uleb128Encode(sigParam.length, target);
      for (var i2 = 0; i2 < sigParam.length; ++i2) {
        target.push(typeCodes[sigParam[i2]]);
      }
      if (sigRet == "v") {
        target.push(0);
      } else {
        target.push(1, typeCodes[sigRet]);
      }
    }, "generateFuncType");
    var convertJsFunctionToWasm = /* @__PURE__ */ __name((func2, sig) => {
      if (typeof WebAssembly.Function == "function") {
        return new WebAssembly.Function(sigToWasmTypes(sig), func2);
      }
      var typeSectionBody = [1];
      generateFuncType(sig, typeSectionBody);
      var bytes = [
        0,
        97,
        115,
        109,
        // magic ("\0asm")
        1,
        0,
        0,
        0,
        // version: 1
        1
      ];
      uleb128Encode(typeSectionBody.length, bytes);
      bytes.push(...typeSectionBody);
      bytes.push(
        2,
        7,
        // import section
        // (import "e" "f" (func 0 (type 0)))
        1,
        1,
        101,
        1,
        102,
        0,
        0,
        7,
        5,
        // export section
        // (export "f" (func 0 (type 0)))
        1,
        1,
        102,
        0,
        0
      );
      var module2 = new WebAssembly.Module(new Uint8Array(bytes));
      var instance2 = new WebAssembly.Instance(module2, {
        "e": {
          "f": func2
        }
      });
      var wrappedFunc = instance2.exports["f"];
      return wrappedFunc;
    }, "convertJsFunctionToWasm");
    var wasmTableMirror = [];
    var wasmTable = new WebAssembly.Table({
      "initial": 31,
      "element": "anyfunc"
    });
    var getWasmTableEntry = /* @__PURE__ */ __name((funcPtr) => {
      var func2 = wasmTableMirror[funcPtr];
      if (!func2) {
        if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
        wasmTableMirror[funcPtr] = func2 = wasmTable.get(funcPtr);
      }
      return func2;
    }, "getWasmTableEntry");
    var updateTableMap = /* @__PURE__ */ __name((offset, count2) => {
      if (functionsInTableMap) {
        for (var i2 = offset; i2 < offset + count2; i2++) {
          var item = getWasmTableEntry(i2);
          if (item) {
            functionsInTableMap.set(item, i2);
          }
        }
      }
    }, "updateTableMap");
    var functionsInTableMap;
    var getFunctionAddress = /* @__PURE__ */ __name((func2) => {
      if (!functionsInTableMap) {
        functionsInTableMap = /* @__PURE__ */ new WeakMap();
        updateTableMap(0, wasmTable.length);
      }
      return functionsInTableMap.get(func2) || 0;
    }, "getFunctionAddress");
    var freeTableIndexes = [];
    var getEmptyTableSlot = /* @__PURE__ */ __name(() => {
      if (freeTableIndexes.length) {
        return freeTableIndexes.pop();
      }
      try {
        wasmTable.grow(1);
      } catch (err22) {
        if (!(err22 instanceof RangeError)) {
          throw err22;
        }
        throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
      }
      return wasmTable.length - 1;
    }, "getEmptyTableSlot");
    var setWasmTableEntry = /* @__PURE__ */ __name((idx, func2) => {
      wasmTable.set(idx, func2);
      wasmTableMirror[idx] = wasmTable.get(idx);
    }, "setWasmTableEntry");
    var addFunction = /* @__PURE__ */ __name((func2, sig) => {
      var rtn = getFunctionAddress(func2);
      if (rtn) {
        return rtn;
      }
      var ret = getEmptyTableSlot();
      try {
        setWasmTableEntry(ret, func2);
      } catch (err22) {
        if (!(err22 instanceof TypeError)) {
          throw err22;
        }
        var wrapped = convertJsFunctionToWasm(func2, sig);
        setWasmTableEntry(ret, wrapped);
      }
      functionsInTableMap.set(func2, ret);
      return ret;
    }, "addFunction");
    var updateGOT = /* @__PURE__ */ __name((exports, replace2) => {
      for (var symName in exports) {
        if (isInternalSym(symName)) {
          continue;
        }
        var value = exports[symName];
        GOT[symName] ||= new WebAssembly.Global({
          "value": "i32",
          "mutable": true
        });
        if (replace2 || GOT[symName].value == 0) {
          if (typeof value == "function") {
            GOT[symName].value = addFunction(value);
          } else if (typeof value == "number") {
            GOT[symName].value = value;
          } else {
            err(`unhandled export type for '${symName}': ${typeof value}`);
          }
        }
      }
    }, "updateGOT");
    var relocateExports = /* @__PURE__ */ __name((exports, memoryBase2, replace2) => {
      var relocated = {};
      for (var e in exports) {
        var value = exports[e];
        if (typeof value == "object") {
          value = value.value;
        }
        if (typeof value == "number") {
          value += memoryBase2;
        }
        relocated[e] = value;
      }
      updateGOT(relocated, replace2);
      return relocated;
    }, "relocateExports");
    var isSymbolDefined = /* @__PURE__ */ __name((symName) => {
      var existing = wasmImports[symName];
      if (!existing || existing.stub) {
        return false;
      }
      return true;
    }, "isSymbolDefined");
    var dynCall = /* @__PURE__ */ __name((sig, ptr, args2 = []) => {
      var rtn = getWasmTableEntry(ptr)(...args2);
      return rtn;
    }, "dynCall");
    var stackSave = /* @__PURE__ */ __name(() => _emscripten_stack_get_current(), "stackSave");
    var stackRestore = /* @__PURE__ */ __name((val) => __emscripten_stack_restore(val), "stackRestore");
    var createInvokeFunction = /* @__PURE__ */ __name((sig) => (ptr, ...args2) => {
      var sp = stackSave();
      try {
        return dynCall(sig, ptr, args2);
      } catch (e) {
        stackRestore(sp);
        if (e !== e + 0) throw e;
        _setThrew(1, 0);
        if (sig[0] == "j") return 0n;
      }
    }, "createInvokeFunction");
    var resolveGlobalSymbol = /* @__PURE__ */ __name((symName, direct = false) => {
      var sym;
      if (isSymbolDefined(symName)) {
        sym = wasmImports[symName];
      } else if (symName.startsWith("invoke_")) {
        sym = wasmImports[symName] = createInvokeFunction(symName.split("_")[1]);
      }
      return {
        sym,
        name: symName
      };
    }, "resolveGlobalSymbol");
    var UTF8ToString = /* @__PURE__ */ __name((ptr, maxBytesToRead) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "", "UTF8ToString");
    var loadWebAssemblyModule = /* @__PURE__ */ __name((binary, flags, libName, localScope, handle) => {
      var metadata = getDylinkMetadata(binary);
      currentModuleWeakSymbols = metadata.weakImports;
      function loadModule() {
        var firstLoad = !handle || !HEAP8[handle + 8];
        if (firstLoad) {
          var memAlign = Math.pow(2, metadata.memoryAlign);
          var memoryBase = metadata.memorySize ? alignMemory(getMemory(metadata.memorySize + memAlign), memAlign) : 0;
          var tableBase = metadata.tableSize ? wasmTable.length : 0;
          if (handle) {
            HEAP8[handle + 8] = 1;
            LE_HEAP_STORE_U32((handle + 12 >> 2) * 4, memoryBase);
            LE_HEAP_STORE_I32((handle + 16 >> 2) * 4, metadata.memorySize);
            LE_HEAP_STORE_U32((handle + 20 >> 2) * 4, tableBase);
            LE_HEAP_STORE_I32((handle + 24 >> 2) * 4, metadata.tableSize);
          }
        } else {
          memoryBase = LE_HEAP_LOAD_U32((handle + 12 >> 2) * 4);
          tableBase = LE_HEAP_LOAD_U32((handle + 20 >> 2) * 4);
        }
        var tableGrowthNeeded = tableBase + metadata.tableSize - wasmTable.length;
        if (tableGrowthNeeded > 0) {
          wasmTable.grow(tableGrowthNeeded);
        }
        var moduleExports;
        function resolveSymbol(sym) {
          var resolved = resolveGlobalSymbol(sym).sym;
          if (!resolved && localScope) {
            resolved = localScope[sym];
          }
          if (!resolved) {
            resolved = moduleExports[sym];
          }
          return resolved;
        }
        __name(resolveSymbol, "resolveSymbol");
        var proxyHandler = {
          get(stubs, prop2) {
            switch (prop2) {
              case "__memory_base":
                return memoryBase;
              case "__table_base":
                return tableBase;
            }
            if (prop2 in wasmImports && !wasmImports[prop2].stub) {
              return wasmImports[prop2];
            }
            if (!(prop2 in stubs)) {
              var resolved;
              stubs[prop2] = (...args2) => {
                resolved ||= resolveSymbol(prop2);
                return resolved(...args2);
              };
            }
            return stubs[prop2];
          }
        };
        var proxy = new Proxy({}, proxyHandler);
        var info = {
          "GOT.mem": new Proxy({}, GOTHandler),
          "GOT.func": new Proxy({}, GOTHandler),
          "env": proxy,
          "wasi_snapshot_preview1": proxy
        };
        function postInstantiation(module, instance) {
          updateTableMap(tableBase, metadata.tableSize);
          moduleExports = relocateExports(instance.exports, memoryBase);
          if (!flags.allowUndefined) {
            reportUndefinedSymbols();
          }
          function addEmAsm(addr, body) {
            var args = [];
            var arity = 0;
            for (; arity < 16; arity++) {
              if (body.indexOf("$" + arity) != -1) {
                args.push("$" + arity);
              } else {
                break;
              }
            }
            args = args.join(",");
            var func = `(${args}) => { ${body} };`;
            ASM_CONSTS[start] = eval(func);
          }
          __name(addEmAsm, "addEmAsm");
          if ("__start_em_asm" in moduleExports) {
            var start = moduleExports["__start_em_asm"];
            var stop = moduleExports["__stop_em_asm"];
            while (start < stop) {
              var jsString = UTF8ToString(start);
              addEmAsm(start, jsString);
              start = HEAPU8.indexOf(0, start) + 1;
            }
          }
          function addEmJs(name, cSig, body) {
            var jsArgs = [];
            cSig = cSig.slice(1, -1);
            if (cSig != "void") {
              cSig = cSig.split(",");
              for (var i in cSig) {
                var jsArg = cSig[i].split(" ").pop();
                jsArgs.push(jsArg.replace("*", ""));
              }
            }
            var func = `(${jsArgs}) => ${body};`;
            moduleExports[name] = eval(func);
          }
          __name(addEmJs, "addEmJs");
          for (var name in moduleExports) {
            if (name.startsWith("__em_js__")) {
              var start = moduleExports[name];
              var jsString = UTF8ToString(start);
              var parts = jsString.split("<::>");
              addEmJs(name.replace("__em_js__", ""), parts[0], parts[1]);
              delete moduleExports[name];
            }
          }
          var applyRelocs = moduleExports["__wasm_apply_data_relocs"];
          if (applyRelocs) {
            if (runtimeInitialized) {
              applyRelocs();
            } else {
              __RELOC_FUNCS__.push(applyRelocs);
            }
          }
          var init = moduleExports["__wasm_call_ctors"];
          if (init) {
            if (runtimeInitialized) {
              init();
            } else {
              __ATINIT__.push(init);
            }
          }
          return moduleExports;
        }
        __name(postInstantiation, "postInstantiation");
        if (flags.loadAsync) {
          if (binary instanceof WebAssembly.Module) {
            var instance = new WebAssembly.Instance(binary, info);
            return Promise.resolve(postInstantiation(binary, instance));
          }
          return WebAssembly.instantiate(binary, info).then((result) => postInstantiation(result.module, result.instance));
        }
        var module = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary);
        var instance = new WebAssembly.Instance(module, info);
        return postInstantiation(module, instance);
      }
      __name(loadModule, "loadModule");
      if (flags.loadAsync) {
        return metadata.neededDynlibs.reduce((chain, dynNeeded) => chain.then(() => loadDynamicLibrary(dynNeeded, flags, localScope)), Promise.resolve()).then(loadModule);
      }
      metadata.neededDynlibs.forEach((needed) => loadDynamicLibrary(needed, flags, localScope));
      return loadModule();
    }, "loadWebAssemblyModule");
    var mergeLibSymbols = /* @__PURE__ */ __name((exports, libName2) => {
      for (var [sym, exp] of Object.entries(exports)) {
        const setImport = /* @__PURE__ */ __name((target) => {
          if (!isSymbolDefined(target)) {
            wasmImports[target] = exp;
          }
        }, "setImport");
        setImport(sym);
        const main_alias = "__main_argc_argv";
        if (sym == "main") {
          setImport(main_alias);
        }
        if (sym == main_alias) {
          setImport("main");
        }
      }
    }, "mergeLibSymbols");
    var asyncLoad = /* @__PURE__ */ __name(async (url) => {
      var arrayBuffer = await readAsync(url);
      return new Uint8Array(arrayBuffer);
    }, "asyncLoad");
    function loadDynamicLibrary(libName2, flags2 = {
      global: true,
      nodelete: true
    }, localScope2, handle2) {
      var dso = LDSO.loadedLibsByName[libName2];
      if (dso) {
        if (!flags2.global) {
          if (localScope2) {
            Object.assign(localScope2, dso.exports);
          }
        } else if (!dso.global) {
          dso.global = true;
          mergeLibSymbols(dso.exports, libName2);
        }
        if (flags2.nodelete && dso.refcount !== Infinity) {
          dso.refcount = Infinity;
        }
        dso.refcount++;
        if (handle2) {
          LDSO.loadedLibsByHandle[handle2] = dso;
        }
        return flags2.loadAsync ? Promise.resolve(true) : true;
      }
      dso = newDSO(libName2, handle2, "loading");
      dso.refcount = flags2.nodelete ? Infinity : 1;
      dso.global = flags2.global;
      function loadLibData() {
        if (handle2) {
          var data = LE_HEAP_LOAD_U32((handle2 + 28 >> 2) * 4);
          var dataSize = LE_HEAP_LOAD_U32((handle2 + 32 >> 2) * 4);
          if (data && dataSize) {
            var libData = HEAP8.slice(data, data + dataSize);
            return flags2.loadAsync ? Promise.resolve(libData) : libData;
          }
        }
        var libFile = locateFile(libName2);
        if (flags2.loadAsync) {
          return asyncLoad(libFile);
        }
        if (!readBinary) {
          throw new Error(`${libFile}: file not found, and synchronous loading of external files is not available`);
        }
        return readBinary(libFile);
      }
      __name(loadLibData, "loadLibData");
      function getExports() {
        if (flags2.loadAsync) {
          return loadLibData().then((libData) => loadWebAssemblyModule(libData, flags2, libName2, localScope2, handle2));
        }
        return loadWebAssemblyModule(loadLibData(), flags2, libName2, localScope2, handle2);
      }
      __name(getExports, "getExports");
      function moduleLoaded(exports) {
        if (dso.global) {
          mergeLibSymbols(exports, libName2);
        } else if (localScope2) {
          Object.assign(localScope2, exports);
        }
        dso.exports = exports;
      }
      __name(moduleLoaded, "moduleLoaded");
      if (flags2.loadAsync) {
        return getExports().then((exports) => {
          moduleLoaded(exports);
          return true;
        });
      }
      moduleLoaded(getExports());
      return true;
    }
    __name(loadDynamicLibrary, "loadDynamicLibrary");
    var reportUndefinedSymbols = /* @__PURE__ */ __name(() => {
      for (var [symName, entry] of Object.entries(GOT)) {
        if (entry.value == 0) {
          var value = resolveGlobalSymbol(symName, true).sym;
          if (!value && !entry.required) {
            continue;
          }
          if (typeof value == "function") {
            entry.value = addFunction(value, value.sig);
          } else if (typeof value == "number") {
            entry.value = value;
          } else {
            throw new Error(`bad export type for '${symName}': ${typeof value}`);
          }
        }
      }
    }, "reportUndefinedSymbols");
    var loadDylibs = /* @__PURE__ */ __name(() => {
      if (!dynamicLibraries.length) {
        reportUndefinedSymbols();
        return;
      }
      addRunDependency("loadDylibs");
      dynamicLibraries.reduce((chain, lib) => chain.then(() => loadDynamicLibrary(lib, {
        loadAsync: true,
        global: true,
        nodelete: true,
        allowUndefined: true
      })), Promise.resolve()).then(() => {
        reportUndefinedSymbols();
        removeRunDependency("loadDylibs");
      });
    }, "loadDylibs");
    var noExitRuntime = Module["noExitRuntime"] || true;
    function setValue(ptr, value, type = "i8") {
      if (type.endsWith("*")) type = "*";
      switch (type) {
        case "i1":
          HEAP8[ptr] = value;
          break;
        case "i8":
          HEAP8[ptr] = value;
          break;
        case "i16":
          LE_HEAP_STORE_I16((ptr >> 1) * 2, value);
          break;
        case "i32":
          LE_HEAP_STORE_I32((ptr >> 2) * 4, value);
          break;
        case "i64":
          HEAP64[ptr >> 3] = BigInt(value);
          break;
        case "float":
          LE_HEAP_STORE_F32((ptr >> 2) * 4, value);
          break;
        case "double":
          LE_HEAP_STORE_F64((ptr >> 3) * 8, value);
          break;
        case "*":
          LE_HEAP_STORE_U32((ptr >> 2) * 4, value);
          break;
        default:
          abort(`invalid type for setValue: ${type}`);
      }
    }
    __name(setValue, "setValue");
    var ___memory_base = new WebAssembly.Global({
      "value": "i32",
      "mutable": false
    }, 1024);
    var ___stack_pointer = new WebAssembly.Global({
      "value": "i32",
      "mutable": true
    }, 78224);
    var ___table_base = new WebAssembly.Global({
      "value": "i32",
      "mutable": false
    }, 1);
    var __abort_js = /* @__PURE__ */ __name(() => abort(""), "__abort_js");
    __abort_js.sig = "v";
    var _emscripten_get_now = /* @__PURE__ */ __name(() => performance.now(), "_emscripten_get_now");
    _emscripten_get_now.sig = "d";
    var _emscripten_date_now = /* @__PURE__ */ __name(() => Date.now(), "_emscripten_date_now");
    _emscripten_date_now.sig = "d";
    var nowIsMonotonic = 1;
    var checkWasiClock = /* @__PURE__ */ __name((clock_id) => clock_id >= 0 && clock_id <= 3, "checkWasiClock");
    var INT53_MAX = 9007199254740992;
    var INT53_MIN = -9007199254740992;
    var bigintToI53Checked = /* @__PURE__ */ __name((num2) => num2 < INT53_MIN || num2 > INT53_MAX ? NaN : Number(num2), "bigintToI53Checked");
    function _clock_time_get(clk_id, ignored_precision, ptime) {
      ignored_precision = bigintToI53Checked(ignored_precision);
      if (!checkWasiClock(clk_id)) {
        return 28;
      }
      var now;
      if (clk_id === 0) {
        now = _emscripten_date_now();
      } else if (nowIsMonotonic) {
        now = _emscripten_get_now();
      } else {
        return 52;
      }
      var nsec = Math.round(now * 1e3 * 1e3);
      HEAP64[ptime >> 3] = BigInt(nsec);
      return 0;
    }
    __name(_clock_time_get, "_clock_time_get");
    _clock_time_get.sig = "iijp";
    var getHeapMax = /* @__PURE__ */ __name(() => (
      // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
      // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
      // for any code that deals with heap sizes, which would require special
      // casing all heap size related code to treat 0 specially.
      2147483648
    ), "getHeapMax");
    var growMemory = /* @__PURE__ */ __name((size) => {
      var b = wasmMemory.buffer;
      var pages = (size - b.byteLength + 65535) / 65536 | 0;
      try {
        wasmMemory.grow(pages);
        updateMemoryViews();
        return 1;
      } catch (e) {
      }
    }, "growMemory");
    var _emscripten_resize_heap = /* @__PURE__ */ __name((requestedSize) => {
      var oldSize = HEAPU8.length;
      requestedSize >>>= 0;
      var maxHeapSize = getHeapMax();
      if (requestedSize > maxHeapSize) {
        return false;
      }
      for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
        var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
        overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
        var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
        var replacement = growMemory(newSize);
        if (replacement) {
          return true;
        }
      }
      return false;
    }, "_emscripten_resize_heap");
    _emscripten_resize_heap.sig = "ip";
    var _fd_close = /* @__PURE__ */ __name((fd) => 52, "_fd_close");
    _fd_close.sig = "ii";
    function _fd_seek(fd, offset, whence, newOffset) {
      offset = bigintToI53Checked(offset);
      return 70;
    }
    __name(_fd_seek, "_fd_seek");
    _fd_seek.sig = "iijip";
    var printCharBuffers = [null, [], []];
    var printChar = /* @__PURE__ */ __name((stream, curr) => {
      var buffer = printCharBuffers[stream];
      if (curr === 0 || curr === 10) {
        (stream === 1 ? out : err)(UTF8ArrayToString(buffer));
        buffer.length = 0;
      } else {
        buffer.push(curr);
      }
    }, "printChar");
    var flush_NO_FILESYSTEM = /* @__PURE__ */ __name(() => {
      if (printCharBuffers[1].length) printChar(1, 10);
      if (printCharBuffers[2].length) printChar(2, 10);
    }, "flush_NO_FILESYSTEM");
    var SYSCALLS = {
      varargs: void 0,
      getStr(ptr) {
        var ret = UTF8ToString(ptr);
        return ret;
      }
    };
    var _fd_write = /* @__PURE__ */ __name((fd, iov, iovcnt, pnum) => {
      var num2 = 0;
      for (var i2 = 0; i2 < iovcnt; i2++) {
        var ptr = LE_HEAP_LOAD_U32((iov >> 2) * 4);
        var len = LE_HEAP_LOAD_U32((iov + 4 >> 2) * 4);
        iov += 8;
        for (var j = 0; j < len; j++) {
          printChar(fd, HEAPU8[ptr + j]);
        }
        num2 += len;
      }
      LE_HEAP_STORE_U32((pnum >> 2) * 4, num2);
      return 0;
    }, "_fd_write");
    _fd_write.sig = "iippp";
    function _tree_sitter_log_callback(isLexMessage, messageAddress) {
      if (Module.currentLogCallback) {
        const message = UTF8ToString(messageAddress);
        Module.currentLogCallback(message, isLexMessage !== 0);
      }
    }
    __name(_tree_sitter_log_callback, "_tree_sitter_log_callback");
    function _tree_sitter_parse_callback(inputBufferAddress, index3, row, column, lengthAddress) {
      const INPUT_BUFFER_SIZE = 10 * 1024;
      const string4 = Module.currentParseCallback(index3, {
        row,
        column
      });
      if (typeof string4 === "string") {
        setValue(lengthAddress, string4.length, "i32");
        stringToUTF16(string4, inputBufferAddress, INPUT_BUFFER_SIZE);
      } else {
        setValue(lengthAddress, 0, "i32");
      }
    }
    __name(_tree_sitter_parse_callback, "_tree_sitter_parse_callback");
    function _tree_sitter_progress_callback(currentOffset, hasError) {
      if (Module.currentProgressCallback) {
        return Module.currentProgressCallback({
          currentOffset,
          hasError
        });
      }
      return false;
    }
    __name(_tree_sitter_progress_callback, "_tree_sitter_progress_callback");
    function _tree_sitter_query_progress_callback(currentOffset) {
      if (Module.currentQueryProgressCallback) {
        return Module.currentQueryProgressCallback({
          currentOffset
        });
      }
      return false;
    }
    __name(_tree_sitter_query_progress_callback, "_tree_sitter_query_progress_callback");
    var runtimeKeepaliveCounter = 0;
    var keepRuntimeAlive = /* @__PURE__ */ __name(() => noExitRuntime || runtimeKeepaliveCounter > 0, "keepRuntimeAlive");
    var _proc_exit = /* @__PURE__ */ __name((code) => {
      EXITSTATUS = code;
      if (!keepRuntimeAlive()) {
        Module["onExit"]?.(code);
        ABORT = true;
      }
      quit_(code, new ExitStatus(code));
    }, "_proc_exit");
    _proc_exit.sig = "vi";
    var exitJS = /* @__PURE__ */ __name((status, implicit2) => {
      EXITSTATUS = status;
      _proc_exit(status);
    }, "exitJS");
    var handleException = /* @__PURE__ */ __name((e) => {
      if (e instanceof ExitStatus || e == "unwind") {
        return EXITSTATUS;
      }
      quit_(1, e);
    }, "handleException");
    var lengthBytesUTF8 = /* @__PURE__ */ __name((str) => {
      var len = 0;
      for (var i2 = 0; i2 < str.length; ++i2) {
        var c = str.charCodeAt(i2);
        if (c <= 127) {
          len++;
        } else if (c <= 2047) {
          len += 2;
        } else if (c >= 55296 && c <= 57343) {
          len += 4;
          ++i2;
        } else {
          len += 3;
        }
      }
      return len;
    }, "lengthBytesUTF8");
    var stringToUTF8Array = /* @__PURE__ */ __name((str, heap, outIdx, maxBytesToWrite) => {
      if (!(maxBytesToWrite > 0)) return 0;
      var startIdx = outIdx;
      var endIdx = outIdx + maxBytesToWrite - 1;
      for (var i2 = 0; i2 < str.length; ++i2) {
        var u = str.charCodeAt(i2);
        if (u >= 55296 && u <= 57343) {
          var u1 = str.charCodeAt(++i2);
          u = 65536 + ((u & 1023) << 10) | u1 & 1023;
        }
        if (u <= 127) {
          if (outIdx >= endIdx) break;
          heap[outIdx++] = u;
        } else if (u <= 2047) {
          if (outIdx + 1 >= endIdx) break;
          heap[outIdx++] = 192 | u >> 6;
          heap[outIdx++] = 128 | u & 63;
        } else if (u <= 65535) {
          if (outIdx + 2 >= endIdx) break;
          heap[outIdx++] = 224 | u >> 12;
          heap[outIdx++] = 128 | u >> 6 & 63;
          heap[outIdx++] = 128 | u & 63;
        } else {
          if (outIdx + 3 >= endIdx) break;
          heap[outIdx++] = 240 | u >> 18;
          heap[outIdx++] = 128 | u >> 12 & 63;
          heap[outIdx++] = 128 | u >> 6 & 63;
          heap[outIdx++] = 128 | u & 63;
        }
      }
      heap[outIdx] = 0;
      return outIdx - startIdx;
    }, "stringToUTF8Array");
    var stringToUTF8 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite), "stringToUTF8");
    var stackAlloc = /* @__PURE__ */ __name((sz) => __emscripten_stack_alloc(sz), "stackAlloc");
    var stringToUTF8OnStack = /* @__PURE__ */ __name((str) => {
      var size = lengthBytesUTF8(str) + 1;
      var ret = stackAlloc(size);
      stringToUTF8(str, ret, size);
      return ret;
    }, "stringToUTF8OnStack");
    var AsciiToString = /* @__PURE__ */ __name((ptr) => {
      var str = "";
      while (1) {
        var ch = HEAPU8[ptr++];
        if (!ch) return str;
        str += String.fromCharCode(ch);
      }
    }, "AsciiToString");
    var stringToUTF16 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite) => {
      maxBytesToWrite ??= 2147483647;
      if (maxBytesToWrite < 2) return 0;
      maxBytesToWrite -= 2;
      var startPtr = outPtr;
      var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
      for (var i2 = 0; i2 < numCharsToWrite; ++i2) {
        var codeUnit = str.charCodeAt(i2);
        LE_HEAP_STORE_I16((outPtr >> 1) * 2, codeUnit);
        outPtr += 2;
      }
      LE_HEAP_STORE_I16((outPtr >> 1) * 2, 0);
      return outPtr - startPtr;
    }, "stringToUTF16");
    var wasmImports = {
      /** @export */
      __heap_base: ___heap_base,
      /** @export */
      __indirect_function_table: wasmTable,
      /** @export */
      __memory_base: ___memory_base,
      /** @export */
      __stack_pointer: ___stack_pointer,
      /** @export */
      __table_base: ___table_base,
      /** @export */
      _abort_js: __abort_js,
      /** @export */
      clock_time_get: _clock_time_get,
      /** @export */
      emscripten_resize_heap: _emscripten_resize_heap,
      /** @export */
      fd_close: _fd_close,
      /** @export */
      fd_seek: _fd_seek,
      /** @export */
      fd_write: _fd_write,
      /** @export */
      memory: wasmMemory,
      /** @export */
      tree_sitter_log_callback: _tree_sitter_log_callback,
      /** @export */
      tree_sitter_parse_callback: _tree_sitter_parse_callback,
      /** @export */
      tree_sitter_progress_callback: _tree_sitter_progress_callback,
      /** @export */
      tree_sitter_query_progress_callback: _tree_sitter_query_progress_callback
    };
    var wasmExports = await createWasm();
    var ___wasm_call_ctors = wasmExports["__wasm_call_ctors"];
    var _malloc = Module["_malloc"] = wasmExports["malloc"];
    var _calloc = Module["_calloc"] = wasmExports["calloc"];
    var _realloc = Module["_realloc"] = wasmExports["realloc"];
    var _free = Module["_free"] = wasmExports["free"];
    var _memcmp = Module["_memcmp"] = wasmExports["memcmp"];
    var _ts_language_symbol_count = Module["_ts_language_symbol_count"] = wasmExports["ts_language_symbol_count"];
    var _ts_language_state_count = Module["_ts_language_state_count"] = wasmExports["ts_language_state_count"];
    var _ts_language_version = Module["_ts_language_version"] = wasmExports["ts_language_version"];
    var _ts_language_abi_version = Module["_ts_language_abi_version"] = wasmExports["ts_language_abi_version"];
    var _ts_language_metadata = Module["_ts_language_metadata"] = wasmExports["ts_language_metadata"];
    var _ts_language_name = Module["_ts_language_name"] = wasmExports["ts_language_name"];
    var _ts_language_field_count = Module["_ts_language_field_count"] = wasmExports["ts_language_field_count"];
    var _ts_language_next_state = Module["_ts_language_next_state"] = wasmExports["ts_language_next_state"];
    var _ts_language_symbol_name = Module["_ts_language_symbol_name"] = wasmExports["ts_language_symbol_name"];
    var _ts_language_symbol_for_name = Module["_ts_language_symbol_for_name"] = wasmExports["ts_language_symbol_for_name"];
    var _strncmp = Module["_strncmp"] = wasmExports["strncmp"];
    var _ts_language_symbol_type = Module["_ts_language_symbol_type"] = wasmExports["ts_language_symbol_type"];
    var _ts_language_field_name_for_id = Module["_ts_language_field_name_for_id"] = wasmExports["ts_language_field_name_for_id"];
    var _ts_lookahead_iterator_new = Module["_ts_lookahead_iterator_new"] = wasmExports["ts_lookahead_iterator_new"];
    var _ts_lookahead_iterator_delete = Module["_ts_lookahead_iterator_delete"] = wasmExports["ts_lookahead_iterator_delete"];
    var _ts_lookahead_iterator_reset_state = Module["_ts_lookahead_iterator_reset_state"] = wasmExports["ts_lookahead_iterator_reset_state"];
    var _ts_lookahead_iterator_reset = Module["_ts_lookahead_iterator_reset"] = wasmExports["ts_lookahead_iterator_reset"];
    var _ts_lookahead_iterator_next = Module["_ts_lookahead_iterator_next"] = wasmExports["ts_lookahead_iterator_next"];
    var _ts_lookahead_iterator_current_symbol = Module["_ts_lookahead_iterator_current_symbol"] = wasmExports["ts_lookahead_iterator_current_symbol"];
    var _ts_parser_delete = Module["_ts_parser_delete"] = wasmExports["ts_parser_delete"];
    var _ts_parser_reset = Module["_ts_parser_reset"] = wasmExports["ts_parser_reset"];
    var _ts_parser_set_language = Module["_ts_parser_set_language"] = wasmExports["ts_parser_set_language"];
    var _ts_parser_timeout_micros = Module["_ts_parser_timeout_micros"] = wasmExports["ts_parser_timeout_micros"];
    var _ts_parser_set_timeout_micros = Module["_ts_parser_set_timeout_micros"] = wasmExports["ts_parser_set_timeout_micros"];
    var _ts_parser_set_included_ranges = Module["_ts_parser_set_included_ranges"] = wasmExports["ts_parser_set_included_ranges"];
    var _ts_query_new = Module["_ts_query_new"] = wasmExports["ts_query_new"];
    var _ts_query_delete = Module["_ts_query_delete"] = wasmExports["ts_query_delete"];
    var _iswspace = Module["_iswspace"] = wasmExports["iswspace"];
    var _iswalnum = Module["_iswalnum"] = wasmExports["iswalnum"];
    var _ts_query_pattern_count = Module["_ts_query_pattern_count"] = wasmExports["ts_query_pattern_count"];
    var _ts_query_capture_count = Module["_ts_query_capture_count"] = wasmExports["ts_query_capture_count"];
    var _ts_query_string_count = Module["_ts_query_string_count"] = wasmExports["ts_query_string_count"];
    var _ts_query_capture_name_for_id = Module["_ts_query_capture_name_for_id"] = wasmExports["ts_query_capture_name_for_id"];
    var _ts_query_capture_quantifier_for_id = Module["_ts_query_capture_quantifier_for_id"] = wasmExports["ts_query_capture_quantifier_for_id"];
    var _ts_query_string_value_for_id = Module["_ts_query_string_value_for_id"] = wasmExports["ts_query_string_value_for_id"];
    var _ts_query_predicates_for_pattern = Module["_ts_query_predicates_for_pattern"] = wasmExports["ts_query_predicates_for_pattern"];
    var _ts_query_start_byte_for_pattern = Module["_ts_query_start_byte_for_pattern"] = wasmExports["ts_query_start_byte_for_pattern"];
    var _ts_query_end_byte_for_pattern = Module["_ts_query_end_byte_for_pattern"] = wasmExports["ts_query_end_byte_for_pattern"];
    var _ts_query_is_pattern_rooted = Module["_ts_query_is_pattern_rooted"] = wasmExports["ts_query_is_pattern_rooted"];
    var _ts_query_is_pattern_non_local = Module["_ts_query_is_pattern_non_local"] = wasmExports["ts_query_is_pattern_non_local"];
    var _ts_query_is_pattern_guaranteed_at_step = Module["_ts_query_is_pattern_guaranteed_at_step"] = wasmExports["ts_query_is_pattern_guaranteed_at_step"];
    var _ts_query_disable_capture = Module["_ts_query_disable_capture"] = wasmExports["ts_query_disable_capture"];
    var _ts_query_disable_pattern = Module["_ts_query_disable_pattern"] = wasmExports["ts_query_disable_pattern"];
    var _ts_tree_copy = Module["_ts_tree_copy"] = wasmExports["ts_tree_copy"];
    var _ts_tree_delete = Module["_ts_tree_delete"] = wasmExports["ts_tree_delete"];
    var _ts_init = Module["_ts_init"] = wasmExports["ts_init"];
    var _ts_parser_new_wasm = Module["_ts_parser_new_wasm"] = wasmExports["ts_parser_new_wasm"];
    var _ts_parser_enable_logger_wasm = Module["_ts_parser_enable_logger_wasm"] = wasmExports["ts_parser_enable_logger_wasm"];
    var _ts_parser_parse_wasm = Module["_ts_parser_parse_wasm"] = wasmExports["ts_parser_parse_wasm"];
    var _ts_parser_included_ranges_wasm = Module["_ts_parser_included_ranges_wasm"] = wasmExports["ts_parser_included_ranges_wasm"];
    var _ts_language_type_is_named_wasm = Module["_ts_language_type_is_named_wasm"] = wasmExports["ts_language_type_is_named_wasm"];
    var _ts_language_type_is_visible_wasm = Module["_ts_language_type_is_visible_wasm"] = wasmExports["ts_language_type_is_visible_wasm"];
    var _ts_language_supertypes_wasm = Module["_ts_language_supertypes_wasm"] = wasmExports["ts_language_supertypes_wasm"];
    var _ts_language_subtypes_wasm = Module["_ts_language_subtypes_wasm"] = wasmExports["ts_language_subtypes_wasm"];
    var _ts_tree_root_node_wasm = Module["_ts_tree_root_node_wasm"] = wasmExports["ts_tree_root_node_wasm"];
    var _ts_tree_root_node_with_offset_wasm = Module["_ts_tree_root_node_with_offset_wasm"] = wasmExports["ts_tree_root_node_with_offset_wasm"];
    var _ts_tree_edit_wasm = Module["_ts_tree_edit_wasm"] = wasmExports["ts_tree_edit_wasm"];
    var _ts_tree_included_ranges_wasm = Module["_ts_tree_included_ranges_wasm"] = wasmExports["ts_tree_included_ranges_wasm"];
    var _ts_tree_get_changed_ranges_wasm = Module["_ts_tree_get_changed_ranges_wasm"] = wasmExports["ts_tree_get_changed_ranges_wasm"];
    var _ts_tree_cursor_new_wasm = Module["_ts_tree_cursor_new_wasm"] = wasmExports["ts_tree_cursor_new_wasm"];
    var _ts_tree_cursor_copy_wasm = Module["_ts_tree_cursor_copy_wasm"] = wasmExports["ts_tree_cursor_copy_wasm"];
    var _ts_tree_cursor_delete_wasm = Module["_ts_tree_cursor_delete_wasm"] = wasmExports["ts_tree_cursor_delete_wasm"];
    var _ts_tree_cursor_reset_wasm = Module["_ts_tree_cursor_reset_wasm"] = wasmExports["ts_tree_cursor_reset_wasm"];
    var _ts_tree_cursor_reset_to_wasm = Module["_ts_tree_cursor_reset_to_wasm"] = wasmExports["ts_tree_cursor_reset_to_wasm"];
    var _ts_tree_cursor_goto_first_child_wasm = Module["_ts_tree_cursor_goto_first_child_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_wasm"];
    var _ts_tree_cursor_goto_last_child_wasm = Module["_ts_tree_cursor_goto_last_child_wasm"] = wasmExports["ts_tree_cursor_goto_last_child_wasm"];
    var _ts_tree_cursor_goto_first_child_for_index_wasm = Module["_ts_tree_cursor_goto_first_child_for_index_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_for_index_wasm"];
    var _ts_tree_cursor_goto_first_child_for_position_wasm = Module["_ts_tree_cursor_goto_first_child_for_position_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_for_position_wasm"];
    var _ts_tree_cursor_goto_next_sibling_wasm = Module["_ts_tree_cursor_goto_next_sibling_wasm"] = wasmExports["ts_tree_cursor_goto_next_sibling_wasm"];
    var _ts_tree_cursor_goto_previous_sibling_wasm = Module["_ts_tree_cursor_goto_previous_sibling_wasm"] = wasmExports["ts_tree_cursor_goto_previous_sibling_wasm"];
    var _ts_tree_cursor_goto_descendant_wasm = Module["_ts_tree_cursor_goto_descendant_wasm"] = wasmExports["ts_tree_cursor_goto_descendant_wasm"];
    var _ts_tree_cursor_goto_parent_wasm = Module["_ts_tree_cursor_goto_parent_wasm"] = wasmExports["ts_tree_cursor_goto_parent_wasm"];
    var _ts_tree_cursor_current_node_type_id_wasm = Module["_ts_tree_cursor_current_node_type_id_wasm"] = wasmExports["ts_tree_cursor_current_node_type_id_wasm"];
    var _ts_tree_cursor_current_node_state_id_wasm = Module["_ts_tree_cursor_current_node_state_id_wasm"] = wasmExports["ts_tree_cursor_current_node_state_id_wasm"];
    var _ts_tree_cursor_current_node_is_named_wasm = Module["_ts_tree_cursor_current_node_is_named_wasm"] = wasmExports["ts_tree_cursor_current_node_is_named_wasm"];
    var _ts_tree_cursor_current_node_is_missing_wasm = Module["_ts_tree_cursor_current_node_is_missing_wasm"] = wasmExports["ts_tree_cursor_current_node_is_missing_wasm"];
    var _ts_tree_cursor_current_node_id_wasm = Module["_ts_tree_cursor_current_node_id_wasm"] = wasmExports["ts_tree_cursor_current_node_id_wasm"];
    var _ts_tree_cursor_start_position_wasm = Module["_ts_tree_cursor_start_position_wasm"] = wasmExports["ts_tree_cursor_start_position_wasm"];
    var _ts_tree_cursor_end_position_wasm = Module["_ts_tree_cursor_end_position_wasm"] = wasmExports["ts_tree_cursor_end_position_wasm"];
    var _ts_tree_cursor_start_index_wasm = Module["_ts_tree_cursor_start_index_wasm"] = wasmExports["ts_tree_cursor_start_index_wasm"];
    var _ts_tree_cursor_end_index_wasm = Module["_ts_tree_cursor_end_index_wasm"] = wasmExports["ts_tree_cursor_end_index_wasm"];
    var _ts_tree_cursor_current_field_id_wasm = Module["_ts_tree_cursor_current_field_id_wasm"] = wasmExports["ts_tree_cursor_current_field_id_wasm"];
    var _ts_tree_cursor_current_depth_wasm = Module["_ts_tree_cursor_current_depth_wasm"] = wasmExports["ts_tree_cursor_current_depth_wasm"];
    var _ts_tree_cursor_current_descendant_index_wasm = Module["_ts_tree_cursor_current_descendant_index_wasm"] = wasmExports["ts_tree_cursor_current_descendant_index_wasm"];
    var _ts_tree_cursor_current_node_wasm = Module["_ts_tree_cursor_current_node_wasm"] = wasmExports["ts_tree_cursor_current_node_wasm"];
    var _ts_node_symbol_wasm = Module["_ts_node_symbol_wasm"] = wasmExports["ts_node_symbol_wasm"];
    var _ts_node_field_name_for_child_wasm = Module["_ts_node_field_name_for_child_wasm"] = wasmExports["ts_node_field_name_for_child_wasm"];
    var _ts_node_field_name_for_named_child_wasm = Module["_ts_node_field_name_for_named_child_wasm"] = wasmExports["ts_node_field_name_for_named_child_wasm"];
    var _ts_node_children_by_field_id_wasm = Module["_ts_node_children_by_field_id_wasm"] = wasmExports["ts_node_children_by_field_id_wasm"];
    var _ts_node_first_child_for_byte_wasm = Module["_ts_node_first_child_for_byte_wasm"] = wasmExports["ts_node_first_child_for_byte_wasm"];
    var _ts_node_first_named_child_for_byte_wasm = Module["_ts_node_first_named_child_for_byte_wasm"] = wasmExports["ts_node_first_named_child_for_byte_wasm"];
    var _ts_node_grammar_symbol_wasm = Module["_ts_node_grammar_symbol_wasm"] = wasmExports["ts_node_grammar_symbol_wasm"];
    var _ts_node_child_count_wasm = Module["_ts_node_child_count_wasm"] = wasmExports["ts_node_child_count_wasm"];
    var _ts_node_named_child_count_wasm = Module["_ts_node_named_child_count_wasm"] = wasmExports["ts_node_named_child_count_wasm"];
    var _ts_node_child_wasm = Module["_ts_node_child_wasm"] = wasmExports["ts_node_child_wasm"];
    var _ts_node_named_child_wasm = Module["_ts_node_named_child_wasm"] = wasmExports["ts_node_named_child_wasm"];
    var _ts_node_child_by_field_id_wasm = Module["_ts_node_child_by_field_id_wasm"] = wasmExports["ts_node_child_by_field_id_wasm"];
    var _ts_node_next_sibling_wasm = Module["_ts_node_next_sibling_wasm"] = wasmExports["ts_node_next_sibling_wasm"];
    var _ts_node_prev_sibling_wasm = Module["_ts_node_prev_sibling_wasm"] = wasmExports["ts_node_prev_sibling_wasm"];
    var _ts_node_next_named_sibling_wasm = Module["_ts_node_next_named_sibling_wasm"] = wasmExports["ts_node_next_named_sibling_wasm"];
    var _ts_node_prev_named_sibling_wasm = Module["_ts_node_prev_named_sibling_wasm"] = wasmExports["ts_node_prev_named_sibling_wasm"];
    var _ts_node_descendant_count_wasm = Module["_ts_node_descendant_count_wasm"] = wasmExports["ts_node_descendant_count_wasm"];
    var _ts_node_parent_wasm = Module["_ts_node_parent_wasm"] = wasmExports["ts_node_parent_wasm"];
    var _ts_node_child_with_descendant_wasm = Module["_ts_node_child_with_descendant_wasm"] = wasmExports["ts_node_child_with_descendant_wasm"];
    var _ts_node_descendant_for_index_wasm = Module["_ts_node_descendant_for_index_wasm"] = wasmExports["ts_node_descendant_for_index_wasm"];
    var _ts_node_named_descendant_for_index_wasm = Module["_ts_node_named_descendant_for_index_wasm"] = wasmExports["ts_node_named_descendant_for_index_wasm"];
    var _ts_node_descendant_for_position_wasm = Module["_ts_node_descendant_for_position_wasm"] = wasmExports["ts_node_descendant_for_position_wasm"];
    var _ts_node_named_descendant_for_position_wasm = Module["_ts_node_named_descendant_for_position_wasm"] = wasmExports["ts_node_named_descendant_for_position_wasm"];
    var _ts_node_start_point_wasm = Module["_ts_node_start_point_wasm"] = wasmExports["ts_node_start_point_wasm"];
    var _ts_node_end_point_wasm = Module["_ts_node_end_point_wasm"] = wasmExports["ts_node_end_point_wasm"];
    var _ts_node_start_index_wasm = Module["_ts_node_start_index_wasm"] = wasmExports["ts_node_start_index_wasm"];
    var _ts_node_end_index_wasm = Module["_ts_node_end_index_wasm"] = wasmExports["ts_node_end_index_wasm"];
    var _ts_node_to_string_wasm = Module["_ts_node_to_string_wasm"] = wasmExports["ts_node_to_string_wasm"];
    var _ts_node_children_wasm = Module["_ts_node_children_wasm"] = wasmExports["ts_node_children_wasm"];
    var _ts_node_named_children_wasm = Module["_ts_node_named_children_wasm"] = wasmExports["ts_node_named_children_wasm"];
    var _ts_node_descendants_of_type_wasm = Module["_ts_node_descendants_of_type_wasm"] = wasmExports["ts_node_descendants_of_type_wasm"];
    var _ts_node_is_named_wasm = Module["_ts_node_is_named_wasm"] = wasmExports["ts_node_is_named_wasm"];
    var _ts_node_has_changes_wasm = Module["_ts_node_has_changes_wasm"] = wasmExports["ts_node_has_changes_wasm"];
    var _ts_node_has_error_wasm = Module["_ts_node_has_error_wasm"] = wasmExports["ts_node_has_error_wasm"];
    var _ts_node_is_error_wasm = Module["_ts_node_is_error_wasm"] = wasmExports["ts_node_is_error_wasm"];
    var _ts_node_is_missing_wasm = Module["_ts_node_is_missing_wasm"] = wasmExports["ts_node_is_missing_wasm"];
    var _ts_node_is_extra_wasm = Module["_ts_node_is_extra_wasm"] = wasmExports["ts_node_is_extra_wasm"];
    var _ts_node_parse_state_wasm = Module["_ts_node_parse_state_wasm"] = wasmExports["ts_node_parse_state_wasm"];
    var _ts_node_next_parse_state_wasm = Module["_ts_node_next_parse_state_wasm"] = wasmExports["ts_node_next_parse_state_wasm"];
    var _ts_query_matches_wasm = Module["_ts_query_matches_wasm"] = wasmExports["ts_query_matches_wasm"];
    var _ts_query_captures_wasm = Module["_ts_query_captures_wasm"] = wasmExports["ts_query_captures_wasm"];
    var _memset = Module["_memset"] = wasmExports["memset"];
    var _memcpy = Module["_memcpy"] = wasmExports["memcpy"];
    var _memmove = Module["_memmove"] = wasmExports["memmove"];
    var _iswalpha = Module["_iswalpha"] = wasmExports["iswalpha"];
    var _iswblank = Module["_iswblank"] = wasmExports["iswblank"];
    var _iswdigit = Module["_iswdigit"] = wasmExports["iswdigit"];
    var _iswlower = Module["_iswlower"] = wasmExports["iswlower"];
    var _iswupper = Module["_iswupper"] = wasmExports["iswupper"];
    var _iswxdigit = Module["_iswxdigit"] = wasmExports["iswxdigit"];
    var _memchr = Module["_memchr"] = wasmExports["memchr"];
    var _strlen = Module["_strlen"] = wasmExports["strlen"];
    var _strcmp = Module["_strcmp"] = wasmExports["strcmp"];
    var _strncat = Module["_strncat"] = wasmExports["strncat"];
    var _strncpy = Module["_strncpy"] = wasmExports["strncpy"];
    var _towlower = Module["_towlower"] = wasmExports["towlower"];
    var _towupper = Module["_towupper"] = wasmExports["towupper"];
    var _setThrew = wasmExports["setThrew"];
    var __emscripten_stack_restore = wasmExports["_emscripten_stack_restore"];
    var __emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"];
    var _emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"];
    var ___wasm_apply_data_relocs = wasmExports["__wasm_apply_data_relocs"];
    Module["setValue"] = setValue;
    Module["getValue"] = getValue;
    Module["UTF8ToString"] = UTF8ToString;
    Module["stringToUTF8"] = stringToUTF8;
    Module["lengthBytesUTF8"] = lengthBytesUTF8;
    Module["AsciiToString"] = AsciiToString;
    Module["stringToUTF16"] = stringToUTF16;
    Module["loadWebAssemblyModule"] = loadWebAssemblyModule;
    function callMain(args2 = []) {
      var entryFunction = resolveGlobalSymbol("main").sym;
      if (!entryFunction) return;
      args2.unshift(thisProgram);
      var argc = args2.length;
      var argv = stackAlloc((argc + 1) * 4);
      var argv_ptr = argv;
      args2.forEach((arg) => {
        LE_HEAP_STORE_U32((argv_ptr >> 2) * 4, stringToUTF8OnStack(arg));
        argv_ptr += 4;
      });
      LE_HEAP_STORE_U32((argv_ptr >> 2) * 4, 0);
      try {
        var ret = entryFunction(argc, argv);
        exitJS(
          ret,
          /* implicit = */
          true
        );
        return ret;
      } catch (e) {
        return handleException(e);
      }
    }
    __name(callMain, "callMain");
    function run(args2 = arguments_) {
      if (runDependencies > 0) {
        dependenciesFulfilled = run;
        return;
      }
      preRun();
      if (runDependencies > 0) {
        dependenciesFulfilled = run;
        return;
      }
      function doRun() {
        Module["calledRun"] = true;
        if (ABORT) return;
        initRuntime();
        preMain();
        readyPromiseResolve(Module);
        Module["onRuntimeInitialized"]?.();
        var noInitialRun = Module["noInitialRun"];
        if (!noInitialRun) callMain(args2);
        postRun();
      }
      __name(doRun, "doRun");
      if (Module["setStatus"]) {
        Module["setStatus"]("Running...");
        setTimeout(() => {
          setTimeout(() => Module["setStatus"](""), 1);
          doRun();
        }, 1);
      } else {
        doRun();
      }
    }
    __name(run, "run");
    if (Module["preInit"]) {
      if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];
      while (Module["preInit"].length > 0) {
        Module["preInit"].pop()();
      }
    }
    run();
    moduleRtn = readyPromise;
    return moduleRtn;
  };
})();
var tree_sitter_default = Module2;
var Module3 = null;
async function initializeBinding(moduleOptions) {
  if (!Module3) {
    Module3 = await tree_sitter_default(moduleOptions);
  }
  return Module3;
}
__name(initializeBinding, "initializeBinding");
function checkModule() {
  return !!Module3;
}
__name(checkModule, "checkModule");
var TRANSFER_BUFFER;
var LANGUAGE_VERSION;
var MIN_COMPATIBLE_VERSION;
var Parser2 = class {
  static {
    __name(this, "Parser");
  }
  /** @internal */
  [0] = 0;
  // Internal handle for WASM
  /** @internal */
  [1] = 0;
  // Internal handle for WASM
  /** @internal */
  logCallback = null;
  /** The parser's current language. */
  language = null;
  /**
   * This must always be called before creating a Parser.
   *
   * You can optionally pass in options to configure the WASM module, the most common
   * one being `locateFile` to help the module find the `.wasm` file.
   */
  static async init(moduleOptions) {
    setModule(await initializeBinding(moduleOptions));
    TRANSFER_BUFFER = C2._ts_init();
    LANGUAGE_VERSION = C2.getValue(TRANSFER_BUFFER, "i32");
    MIN_COMPATIBLE_VERSION = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
  }
  /**
   * Create a new parser.
   */
  constructor() {
    this.initialize();
  }
  /** @internal */
  initialize() {
    if (!checkModule()) {
      throw new Error("cannot construct a Parser before calling `init()`");
    }
    C2._ts_parser_new_wasm();
    this[0] = C2.getValue(TRANSFER_BUFFER, "i32");
    this[1] = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
  }
  /** Delete the parser, freeing its resources. */
  delete() {
    C2._ts_parser_delete(this[0]);
    C2._free(this[1]);
    this[0] = 0;
    this[1] = 0;
  }
  /**
   * Set the language that the parser should use for parsing.
   *
   * If the language was not successfully assigned, an error will be thrown.
   * This happens if the language was generated with an incompatible
   * version of the Tree-sitter CLI. Check the language's version using
   * {@link Language#version} and compare it to this library's
   * {@link LANGUAGE_VERSION} and {@link MIN_COMPATIBLE_VERSION} constants.
   */
  setLanguage(language2) {
    let address;
    if (!language2) {
      address = 0;
      this.language = null;
    } else if (language2.constructor === Language2) {
      address = language2[0];
      const version = C2._ts_language_version(address);
      if (version < MIN_COMPATIBLE_VERSION || LANGUAGE_VERSION < version) {
        throw new Error(
          `Incompatible language version ${version}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${LANGUAGE_VERSION}.`
        );
      }
      this.language = language2;
    } else {
      throw new Error("Argument must be a Language");
    }
    C2._ts_parser_set_language(this[0], address);
    return this;
  }
  /**
   * Parse a slice of UTF8 text.
   *
   * @param {string | ParseCallback} callback - The UTF8-encoded text to parse or a callback function.
   *
   * @param {Tree | null} [oldTree] - A previous syntax tree parsed from the same document. If the text of the
   *   document has changed since `oldTree` was created, then you must edit `oldTree` to match
   *   the new text using {@link Tree#edit}.
   *
   * @param {ParseOptions} [options] - Options for parsing the text.
   *  This can be used to set the included ranges, or a progress callback.
   *
   * @returns {Tree | null} A {@link Tree} if parsing succeeded, or `null` if:
   *  - The parser has not yet had a language assigned with {@link Parser#setLanguage}.
   *  - The progress callback returned true.
   */
  parse(callback, oldTree, options4) {
    if (typeof callback === "string") {
      C2.currentParseCallback = (index3) => callback.slice(index3);
    } else if (typeof callback === "function") {
      C2.currentParseCallback = callback;
    } else {
      throw new Error("Argument must be a string or a function");
    }
    if (options4?.progressCallback) {
      C2.currentProgressCallback = options4.progressCallback;
    } else {
      C2.currentProgressCallback = null;
    }
    if (this.logCallback) {
      C2.currentLogCallback = this.logCallback;
      C2._ts_parser_enable_logger_wasm(this[0], 1);
    } else {
      C2.currentLogCallback = null;
      C2._ts_parser_enable_logger_wasm(this[0], 0);
    }
    let rangeCount = 0;
    let rangeAddress = 0;
    if (options4?.includedRanges) {
      rangeCount = options4.includedRanges.length;
      rangeAddress = C2._calloc(rangeCount, SIZE_OF_RANGE);
      let address = rangeAddress;
      for (let i2 = 0; i2 < rangeCount; i2++) {
        marshalRange(address, options4.includedRanges[i2]);
        address += SIZE_OF_RANGE;
      }
    }
    const treeAddress = C2._ts_parser_parse_wasm(
      this[0],
      this[1],
      oldTree ? oldTree[0] : 0,
      rangeAddress,
      rangeCount
    );
    if (!treeAddress) {
      C2.currentParseCallback = null;
      C2.currentLogCallback = null;
      C2.currentProgressCallback = null;
      return null;
    }
    if (!this.language) {
      throw new Error("Parser must have a language to parse");
    }
    const result = new Tree2(INTERNAL, treeAddress, this.language, C2.currentParseCallback);
    C2.currentParseCallback = null;
    C2.currentLogCallback = null;
    C2.currentProgressCallback = null;
    return result;
  }
  /**
   * Instruct the parser to start the next parse from the beginning.
   *
   * If the parser previously failed because of a timeout, cancellation,
   * or callback, then by default, it will resume where it left off on the
   * next call to {@link Parser#parse} or other parsing functions.
   * If you don't want to resume, and instead intend to use this parser to
   * parse some other document, you must call `reset` first.
   */
  reset() {
    C2._ts_parser_reset(this[0]);
  }
  /** Get the ranges of text that the parser will include when parsing. */
  getIncludedRanges() {
    C2._ts_parser_included_ranges_wasm(this[0]);
    const count2 = C2.getValue(TRANSFER_BUFFER, "i32");
    const buffer = C2.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
    const result = new Array(count2);
    if (count2 > 0) {
      let address = buffer;
      for (let i2 = 0; i2 < count2; i2++) {
        result[i2] = unmarshalRange(address);
        address += SIZE_OF_RANGE;
      }
      C2._free(buffer);
    }
    return result;
  }
  /**
   * @deprecated since version 0.25.0, prefer passing a progress callback to {@link Parser#parse}
   *
   * Get the duration in microseconds that parsing is allowed to take.
   *
   * This is set via {@link Parser#setTimeoutMicros}.
   */
  getTimeoutMicros() {
    return C2._ts_parser_timeout_micros(this[0]);
  }
  /**
   * @deprecated since version 0.25.0, prefer passing a progress callback to {@link Parser#parse}
   *
   * Set the maximum duration in microseconds that parsing should be allowed
   * to take before halting.
   *
   * If parsing takes longer than this, it will halt early, returning `null`.
   * See {@link Parser#parse} for more information.
   */
  setTimeoutMicros(timeout) {
    C2._ts_parser_set_timeout_micros(this[0], 0, timeout);
  }
  /** Set the logging callback that a parser should use during parsing. */
  setLogger(callback) {
    if (!callback) {
      this.logCallback = null;
    } else if (typeof callback !== "function") {
      throw new Error("Logger callback must be a function");
    } else {
      this.logCallback = callback;
    }
    return this;
  }
  /** Get the parser's current logger. */
  getLogger() {
    return this.logCallback;
  }
};

// node_modules/web-tree-sitter/tree-sitter.wasm
var tree_sitter_default2 = "./tree-sitter-PDIAFXZF.wasm";

// src/codemirror/beancount-snippets.ts
var beancountSnippets = () => {
  const today = todayAsString();
  return [
    snippetCompletion(
      `${today} #{*} "#{}" "#{}"
  #{Account:A}  #{Amount}
  #{Account:B}`,
      {
        label: `${today} * transaction`
      }
    )
  ];
};

// src/codemirror/beancount-autocomplete.ts
var undatedDirectives = ["option", "plugin", "include"];
var datedDirectives = [
  "*",
  "open",
  "close",
  "custom",
  "commodity",
  "balance",
  "pad",
  "note",
  "document",
  "price",
  "event",
  "query"
];
var opts = (s) => s.map((label) => ({ label }));
var res = (s, from) => ({
  options: opts(s),
  from
});
var beancountCompletion = (context2) => {
  const tag = context2.matchBefore(/#[A-Za-z0-9\-_/.]*/);
  if (tag) {
    return {
      options: opts(get2(tags)),
      from: tag.from + 1,
      validFor: /\S+/
    };
  }
  const link2 = context2.matchBefore(/\^[A-Za-z0-9\-_/.]*/);
  if (link2) {
    return {
      options: opts(get2(links)),
      from: link2.from + 1,
      validFor: /\S+/
    };
  }
  const indented = context2.matchBefore(/^\s+[A-Z]\S*/);
  if (indented) {
    const indentation = indented.text.length - indented.text.trimStart().length;
    return {
      options: opts(get2(accounts)),
      from: indented.from + indentation,
      validFor: /\S+/
    };
  }
  const line = context2.state.doc.lineAt(context2.pos);
  if (context2.matchBefore(/\d+/)) {
    return { options: beancountSnippets(), from: line.from };
  }
  const currentWord = context2.matchBefore(/\S*/);
  if (currentWord?.from === line.from && line.length > 0) {
    return {
      options: opts(undatedDirectives),
      from: line.from,
      validFor: /\S+/
    };
  }
  const tree = syntaxTree(context2.state);
  const before = tree.resolve(context2.pos, -1);
  const nodeTypesBefore = [
    before.name,
    before.prevSibling?.name,
    before.prevSibling?.prevSibling?.name,
    before.prevSibling?.prevSibling?.prevSibling?.name
  ];
  const match = (...types2) => types2.every((t4, i2) => {
    const nodeType = nodeTypesBefore[i2];
    return typeof t4 === "string" ? nodeType === t4 : t4.some((n) => nodeType === n);
  });
  if (match("string", "flag")) {
    return res(get2(payees), before.from + 1);
  }
  if (match("keyword", "date")) {
    return res(datedDirectives, before.from);
  }
  if (
    // account directly after one of these directives:
    match(
      ["ERROR", "account"],
      ["BALANCE", "CLOSE", "OPEN", "PAD", "NOTE", "DOCUMENT"],
      "date"
    ) || // padding account
    match(["ERROR", "account"], "account", "PAD", "date")
  ) {
    return res(get2(accounts), before.from);
  }
  if (
    // complete currencies after a number.
    match("ERROR", "number") || // account currency
    match(["ERROR", "currency"], "account", "OPEN", "date") || // price or commodity currency
    match(["ERROR", "currency"], ["COMMODITY", "PRICE"], "date")
  ) {
    return res(get2(currencies), before.from);
  }
  return null;
};

// src/codemirror/beancount-fold.ts
var MAXDEPTH = 100;
function headerLevel(line) {
  const match = /^\*+/.exec(line);
  return match?.[0]?.length ?? MAXDEPTH;
}
var beancountFold = foldService.of(({ doc: doc2 }, lineStart, lineEnd) => {
  const startLine = doc2.lineAt(lineStart);
  const totalLines = doc2.lines;
  const level = headerLevel(startLine.text);
  if (level === MAXDEPTH) {
    return null;
  }
  let lineNo = startLine.number;
  let end = startLine.to;
  while (lineNo < totalLines) {
    lineNo += 1;
    const line = doc2.line(lineNo);
    if (headerLevel(line.text) <= level) {
      break;
    }
    end = line.to;
  }
  return { from: lineEnd, to: end };
});

// src/codemirror/editor-transactions.ts
function replaceContents(state2, value) {
  return {
    changes: { from: 0, to: state2.doc.length, insert: value }
  };
}
function scrollToLine(state2, line) {
  if (line < 1 || line > state2.doc.lines) {
    return {};
  }
  const linePos = state2.doc.line(line);
  return {
    selection: { anchor: linePos.from },
    scrollIntoView: true
  };
}
function setErrors(state2, errors3) {
  const { doc: doc2 } = state2;
  const diagnostics = errors3.map(({ source: source3, message }) => {
    const lineno = Math.min(Math.max(source3?.lineno ?? 1, 1), doc2.lines);
    const line = doc2.line(lineno);
    return {
      from: line.from,
      to: line.to,
      severity: "error",
      message
    };
  });
  return setDiagnostics(state2, diagnostics);
}

// src/codemirror/beancount-format.ts
var beancountFormat = (cm) => {
  put("format_source", { source: cm.state.sliceDoc() }).then(
    (data) => {
      cm.dispatch(replaceContents(cm.state, data));
    },
    (error2) => {
      notify_err(error2, (err3) => `Formatting source failed: ${err3.message}`);
    }
  );
  return true;
};

// src/codemirror/beancount-highlight.ts
var beancountEditorHighlight = HighlightStyle.define([
  {
    // Dates
    tag: tags2.special(tags2.number),
    color: "var(--editor-date)"
  },
  {
    // Accounts
    tag: tags2.className,
    color: "var(--editor-account)"
  },
  {
    // Plain comments
    tag: tags2.comment,
    color: "var(--editor-comment)"
  },
  {
    // Sections
    tag: tags2.special(tags2.lineComment),
    color: "var(--editor-comment)",
    border: "solid 1px var(--editor-comment)",
    borderRadius: "2px",
    paddingRight: "10px",
    fontWeight: "500"
  },
  {
    // Currencies
    tag: tags2.unit,
    color: "var(--editor-currencies)"
  },
  {
    // Directives
    tag: tags2.keyword,
    fontWeight: "500",
    color: "var(--editor-directive)"
  },
  {
    // Option name
    tag: tags2.standard(tags2.string),
    color: "var(--editor-class)"
  },
  {
    // Tag, link
    tag: tags2.labelName,
    color: "var(--editor-label-name)"
  },
  {
    // Currency value
    tag: tags2.number,
    color: "var(--editor-number)"
  },
  {
    // Payee, Narration
    tag: tags2.string,
    color: "var(--editor-string)"
  },
  {
    // Invalid token
    tag: tags2.invalid,
    color: "var(--editor-invalid)",
    backgroundColor: "var(--editor-invalid-background)"
  }
]);
var beancountQueryHighlight = HighlightStyle.define([
  {
    // Keywords: Select, Where, And
    tag: tags2.keyword,
    color: "var(--bql-keywords)"
  },
  {
    // Values
    tag: [
      tags2.typeName,
      tags2.className,
      tags2.number,
      tags2.changed,
      tags2.annotation,
      tags2.modifier,
      tags2.self,
      tags2.namespace
    ],
    color: "var(--bql-values)"
  },
  {
    // Strings
    tag: [tags2.processingInstruction, tags2.string, tags2.inserted],
    color: "var(--bql-string)"
  },
  {
    // Errors
    tag: [
      tags2.name,
      tags2.deleted,
      tags2.character,
      tags2.propertyName,
      tags2.macroName
    ],
    color: "var(--bql-errors)"
  }
]);

// src/codemirror/beancount-indent.ts
var beancountIndent = indentService.of((context2, pos) => {
  const textAfterPos = context2.textAfterPos(pos);
  if (/^\s*\d\d\d\d/.exec(textAfterPos)) {
    return 0;
  }
  const line = context2.state.doc.lineAt(pos);
  if (/^\s+\S+/.exec(line.text) ?? /^\d\d\d\d/.exec(line.text)) {
    return context2.unit;
  }
  return 0;
});

// src/codemirror/tree-sitter-beancount.wasm
var tree_sitter_beancount_default = "./tree-sitter-beancount-35RNAN4Q.wasm";

// src/lib/array.ts
function is_non_empty(array3) {
  return array3.length > 0;
}
function last_element(array3) {
  return array3[array3.length - 1];
}
function move2(array3, from, to) {
  const moved = array3[from];
  if (moved != null) {
    const updated = array3.toSpliced(from, 1);
    updated.splice(to, 0, moved);
    return updated;
  } else {
    return array3;
  }
}

// src/codemirror/tree-sitter-parser.ts
var error = NodeType.define({
  id: 65535,
  name: "ERROR",
  error: true,
  props: [styleTags({ ERROR: tags2.invalid })]
});
var dummyPosition = Object.freeze({ row: 0, column: 0 });
function ts_edit(startIndex, oldEndIndex, newEndIndex) {
  return {
    startIndex,
    oldEndIndex,
    newEndIndex,
    startPosition: dummyPosition,
    oldEndPosition: dummyPosition,
    newEndPosition: dummyPosition
  };
}
var TSTreeProp = new NodeProp({ perNode: true });
var TSParserError = class extends Error {
};
var InvalidRangeError = class extends TSParserError {
  constructor() {
    super("Only one range spanning the whole document is supported.");
  }
};
var MissingLanguageError = class extends TSParserError {
  constructor() {
    super("Parser is missing language.");
  }
};
function input_edit_for_fragments(fragments, input_length) {
  const [fragment] = fragments;
  const { tree } = fragment;
  if (!fragments.every((f) => f.tree === tree)) {
    log_error("expect fragments to all have the same tree", fragments);
    return null;
  }
  if (fragments.length === 1) {
    return fragment.offset === 0 ? ts_edit(fragment.to - 1, tree.length, input_length) : ts_edit(0, fragment.from + fragment.offset + 1, fragment.from + 1);
  }
  const before = [...fragments].reverse().find((f) => !f.openStart && f.openEnd) ?? fragment;
  const after = fragments.find((f) => f.openStart && !f.openEnd) ?? last_element(fragments);
  const from = before.to;
  const { offset } = after;
  const newEndIndex = after.from;
  const oldEndIndex = newEndIndex + offset;
  return ts_edit(from - 1, oldEndIndex + 1, newEndIndex + 1);
}
var PARSE_CACHE = /* @__PURE__ */ new WeakMap();
var Parse2 = class _Parse {
  constructor(ts_parser, node_types, input, fragments, ranges) {
    this.ts_parser = ts_parser;
    this.node_types = node_types;
    this.input = input;
    this.fragments = fragments;
    this.ranges = ranges;
    if (ranges.length !== 1 || ranges[0]?.from !== 0 || ranges[0]?.to !== input.length) {
      throw new InvalidRangeError();
    }
  }
  stoppedAt = null;
  parsedPos = 0;
  /** Walk over the given node and its children, recursively creating Trees. */
  get_tree_for_ts_cursor(ts_cursor) {
    const { nodeTypeId, startIndex, endIndex } = ts_cursor;
    const node_type = this.node_types[nodeTypeId] ?? error;
    const children2 = [];
    const positions = [];
    if (ts_cursor.gotoFirstChild()) {
      do {
        positions.push(ts_cursor.startIndex - startIndex);
        children2.push(this.get_tree_for_ts_cursor(ts_cursor));
      } while (ts_cursor.gotoNextSibling());
      ts_cursor.gotoParent();
    }
    return new Tree(node_type, children2, positions, endIndex - startIndex);
  }
  /**
   * Walk over the given node and its children, recursively creating Trees.
   *
   * Tries to reuse parts of an old tree.
   */
  get_tree_for_ts_cursor_reuse(ts_cursor, edit, old_tree) {
    const { nodeTypeId, startIndex, endIndex } = ts_cursor;
    const node_type = this.node_types[nodeTypeId] ?? error;
    const children2 = [];
    const positions = [];
    if (ts_cursor.gotoFirstChild()) {
      let ended = false;
      const old_children = old_tree.children;
      let child_index = 0;
      while (!ended && ts_cursor.endIndex < edit.startIndex) {
        positions.push(ts_cursor.startIndex - startIndex);
        children2.push(old_children[child_index]);
        child_index += 1;
        ended = !ts_cursor.gotoNextSibling();
      }
      if (ts_cursor.startIndex < edit.startIndex && edit.newEndIndex < ts_cursor.endIndex) {
        const old_child = old_children[child_index];
        if (old_child) {
          positions.push(ts_cursor.startIndex - startIndex);
          children2.push(
            this.get_tree_for_ts_cursor_reuse(ts_cursor, edit, old_child)
          );
          ended = !ts_cursor.gotoNextSibling();
        }
      }
      while (!ended && ts_cursor.startIndex < edit.newEndIndex) {
        positions.push(ts_cursor.startIndex - startIndex);
        children2.push(this.get_tree_for_ts_cursor(ts_cursor));
        ended = !ts_cursor.gotoNextSibling();
      }
      let children_after_edit = 0;
      while (!ended) {
        positions.push(ts_cursor.startIndex - startIndex);
        children_after_edit += 1;
        ended = !ts_cursor.gotoNextSibling();
      }
      if (children_after_edit > 0) {
        children2.push(...old_children.slice(-children_after_edit));
      }
      ts_cursor.gotoParent();
    }
    return new Tree(node_type, children2, positions, endIndex - startIndex);
  }
  /** Convert the tree-sitter Tree to a Lezer tree, possibly reusing parts of an old one. */
  convert_tree(ts_tree, change) {
    const ts_tree_cursor = ts_tree.rootNode.walk();
    const tree = change ? this.get_tree_for_ts_cursor_reuse(
      ts_tree_cursor,
      change.edit,
      change.old_tree
    ) : this.get_tree_for_ts_cursor(ts_tree_cursor);
    const tree_with_ts_tree_prop = new Tree(
      tree.type,
      tree.children,
      tree.positions,
      tree.length,
      [[TSTreeProp, ts_tree]]
    );
    return tree_with_ts_tree_prop;
  }
  /** Gather information about the changes from a previous parse. */
  static change_details(fragments, input_length) {
    if (!is_non_empty(fragments)) {
      return null;
    }
    const edit = input_edit_for_fragments(fragments, input_length);
    const old_tree = fragments[0].tree;
    const edited_old_ts_tree = old_tree.prop(TSTreeProp)?.copy();
    if (edit) {
      if (!edited_old_ts_tree) {
        log_error("expected old tree when there is an edit");
        return null;
      }
      assert2(
        input_length - old_tree.length === edit.newEndIndex - edit.oldEndIndex,
        "expect offset to match change in text length"
      );
      edited_old_ts_tree.edit(edit);
      assert2(
        edited_old_ts_tree.rootNode.endIndex === input_length,
        "expect edited old tree to match text length"
      );
      return { edit, old_tree, edited_old_ts_tree };
    }
    return null;
  }
  /**
   * Extend the changed range using the TS getChangedRanges function.
   *
   * Outside this extended range, nodes from the old tree can be reused since they
   * will have the exact same stack of containing nodes (possibly offset after the edit).
   */
  static extend_change(change, ts_tree) {
    const { edit, edited_old_ts_tree } = change;
    const changed_ranges = edited_old_ts_tree.getChangedRanges(ts_tree);
    if (!is_non_empty(changed_ranges)) {
      return change;
    }
    const newEndIndex = Math.max(
      edit.newEndIndex,
      last_element(changed_ranges).endIndex
    );
    const extended_edit = ts_edit(
      Math.min(edit.startIndex, changed_ranges[0].startIndex),
      newEndIndex + (edit.oldEndIndex - edit.newEndIndex),
      newEndIndex
    );
    return {
      edit: extended_edit,
      old_tree: change.old_tree
    };
  }
  advance() {
    const { fragments, input, stoppedAt, ts_parser } = this;
    const text2 = input.read(0, stoppedAt ?? input.length);
    const input_length = text2.length;
    const cm_text = input instanceof DocInput ? input.doc : null;
    if (cm_text) {
      const cached = PARSE_CACHE.get(cm_text);
      if (cached) {
        return cached;
      }
    }
    const change = _Parse.change_details(fragments, input_length);
    let ts_tree = ts_parser.parse(text2, change?.edited_old_ts_tree);
    if (ts_tree?.rootNode.endIndex !== input_length) {
      log_error(
        "Mismatch between tree (%s) and document (%s) lengths; reparsing",
        ts_tree?.rootNode.endIndex,
        input_length
      );
      ts_tree = ts_parser.parse(text2);
    }
    if (ts_tree == null) {
      return null;
    }
    const extended_change = change ? _Parse.extend_change(change, ts_tree) : null;
    const tree = this.convert_tree(ts_tree, extended_change);
    this.parsedPos = input_length;
    if (cm_text) {
      PARSE_CACHE.set(cm_text, tree);
    }
    return tree;
  }
  stopAt(pos) {
    this.stoppedAt = pos;
  }
};
var LezerTSParser = class extends Parser {
  constructor(ts_parser, props2, top_node) {
    super();
    this.ts_parser = ts_parser;
    const { language: language2 } = ts_parser;
    if (language2 == null) {
      throw new MissingLanguageError();
    }
    this.node_types = language2.types.map(
      (name3, id3) => NodeType.define({ id: id3, name: name3, props: props2, top: name3 === top_node })
    );
  }
  /** The Lezer NodeTypes - all node types from the TS grammar with props assigned. */
  node_types;
  createParse(input, fragments, ranges) {
    return new Parse2(this.ts_parser, this.node_types, input, fragments, ranges);
  }
};

// src/codemirror/beancount.ts
async function loadBeancountParser() {
  const ts = import.meta.resolve(tree_sitter_default2);
  const ts_beancount = import.meta.resolve(tree_sitter_beancount_default);
  await Parser2.init({ locateFile: () => ts });
  const lang = await Language2.load(ts_beancount);
  const parser = new Parser2();
  parser.setLanguage(lang);
  return parser;
}
var beancountLanguageFacet = defineLanguageFacet();
var beancountLanguageSupportExtensions = [
  beancountFold,
  syntaxHighlighting(beancountEditorHighlight),
  beancountIndent,
  keymap.of([{ key: "Control-d", mac: "Meta-d", run: beancountFormat }]),
  beancountLanguageFacet.of({
    autocomplete: beancountCompletion,
    commentTokens: { line: ";" },
    indentOnInput: /^\s+\d\d\d\d/
  }),
  highlightTrailingWhitespace()
];
var props = [
  styleTags({
    account: tags2.className,
    currency: tags2.unit,
    date: tags2.special(tags2.number),
    string: tags2.string,
    "BALANCE CLOSE COMMODITY CUSTOM DOCUMENT EVENT NOTE OPEN PAD PRICE TRANSACTION QUERY": tags2.keyword,
    "tag link": tags2.labelName,
    number: tags2.number,
    key: tags2.propertyName,
    bool: tags2.bool,
    "PUSHTAG POPTAG PUSHMETA POPMETA OPTION PLUGIN INCLUDE": tags2.standard(
      tags2.string
    )
  }),
  languageDataProp.add(
    (type) => type.isTop ? beancountLanguageFacet : void 0
  )
];
var load_parser = null;
async function getBeancountLanguageSupport() {
  load_parser ??= loadBeancountParser();
  const ts_parser = await load_parser;
  return new LanguageSupport(
    new Language(
      beancountLanguageFacet,
      new LezerTSParser(ts_parser, props, "beancount_file"),
      [],
      "beancount"
    ),
    beancountLanguageSupportExtensions
  );
}

// src/codemirror/bql-grammar.ts
var bql_grammar_default = {
  columns: [
    "account",
    "amount",
    "balance",
    "close",
    "comment",
    "cost_currency",
    "cost_date",
    "cost_label",
    "cost_number",
    "currency",
    "date",
    "day",
    "description",
    "discrepancy",
    "entry",
    "filename",
    "flag",
    "id",
    "lineno",
    "links",
    "location",
    "meta",
    "month",
    "name",
    "narration",
    "number",
    "open",
    "other_accounts",
    "payee",
    "position",
    "posting_flag",
    "price",
    "tags",
    "tolerance",
    "type",
    "weight",
    "year"
  ],
  functions: [
    "abs",
    "account_sortkey",
    "any_meta",
    "bool",
    "close_date",
    "commodity",
    "commodity_meta",
    "convert",
    "cost",
    "count",
    "currency",
    "currency_meta",
    "date",
    "date_add",
    "date_diff",
    "date_part",
    "date_trunc",
    "day",
    "decimal",
    "empty",
    "entry_meta",
    "filter_currency",
    "findfirst",
    "first",
    "getitem",
    "getprice",
    "grep",
    "grepn",
    "has_account",
    "int",
    "interval",
    "joinstr",
    "last",
    "leaf",
    "length",
    "lower",
    "max",
    "maxwidth",
    "meta",
    "min",
    "month",
    "neg",
    "number",
    "only",
    "open_date",
    "open_meta",
    "parent",
    "parse_date",
    "possign",
    "quarter",
    "repr",
    "root",
    "round",
    "safediv",
    "splitcomp",
    "str",
    "subst",
    "substr",
    "sum",
    "today",
    "units",
    "upper",
    "value",
    "weekday",
    "year",
    "yearmonth"
  ],
  keywords: [
    "and",
    "as",
    "asc",
    "balances",
    "by",
    "desc",
    "distinct",
    "false",
    "from",
    "group",
    "having",
    "in",
    "is",
    "journal",
    "limit",
    "not",
    "or",
    "order",
    "pivot",
    "print",
    "select",
    "true",
    "where"
  ]
};

// src/codemirror/bql-autocomplete.ts
var { columns, functions, keywords } = bql_grammar_default;
var completions = [...columns, ...functions.map((f) => `${f}(`), ...keywords];
var allCompletionOptions = completions.map((label) => ({ label }));
var commands = [
  "balances",
  "errors",
  "explain",
  "help",
  "lex",
  "parse",
  "print",
  "runcustom",
  "select",
  "tokenize"
];
var firstWordCompletions = commands.map((label) => ({ label }));
var bqlCompletion = (context2) => {
  const token = context2.matchBefore(/\w+/);
  if (!token) {
    return null;
  }
  if (token.from === 0) {
    return { from: token.from, options: firstWordCompletions };
  }
  return { from: token.from, options: allCompletionOptions };
};

// src/codemirror/bql-stream-parser.ts
var keywords2 = new Set(bql_grammar_default.keywords);
var columns2 = new Set(bql_grammar_default.columns);
var functions2 = new Set(bql_grammar_default.functions);
var string3 = /^("[^"]*"|'[^']*')/;
var date2 = /^(?:#(?:"[^"]*"|'[^']*')|\d\d\d\d-\d\d-\d\d)/;
var decimal = /^[-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)/;
var integer = /^[-+]?[0-9]+/;
var m = (s, p) => {
  const match = s.match(p);
  return match != null && match !== false;
};
var bqlStreamParser = {
  token(stream) {
    if (stream.eatSpace() || stream.eol()) {
      return null;
    }
    if (m(stream, string3)) {
      return "string";
    }
    if (m(stream, date2) || m(stream, decimal) || m(stream, integer)) {
      return "number";
    }
    if (m(stream, /\w+/)) {
      const word = stream.current().toLowerCase();
      if (keywords2.has(word)) {
        return "keyword";
      }
      if (columns2.has(word)) {
        return "typeName";
      }
      if (functions2.has(word) && stream.peek() === "(") {
        return "macroName";
      }
      return "name";
    }
    const char = stream.next();
    if (char === "*") {
      return "typeName";
    }
    return null;
  }
};

// src/codemirror/bql.ts
var bqlLanguage = StreamLanguage.define(bqlStreamParser);
var bql = new LanguageSupport(
  bqlLanguage,
  bqlLanguage.data.of({
    autocomplete: bqlCompletion
  })
);

// src/codemirror/ruler.ts
var rulerPlugin = (column) => ViewPlugin.define((view) => {
  const ruler = view.dom.appendChild(document.createElement("div"));
  ruler.style.position = "absolute";
  ruler.style.borderRight = "1px dotted black";
  ruler.style.height = "100%";
  ruler.style.opacity = "0.5";
  ruler.style.pointerEvents = "none";
  const updatePosition = () => {
    const firstLine = view.contentDOM.querySelector(".cm-line");
    if (firstLine) {
      const { paddingLeft } = getComputedStyle(firstLine);
      const domRect = view.dom.getBoundingClientRect();
      const contentDOMRect = view.contentDOM.getBoundingClientRect();
      const gutterWidth = contentDOMRect.x - domRect.x;
      const offset = column * view.defaultCharacterWidth + gutterWidth;
      ruler.style.width = paddingLeft;
      ruler.style.left = `${offset.toString()}px`;
    }
  };
  view.requestMeasure({ read: updatePosition });
  return {
    update(update3) {
      if (update3.viewportChanged || update3.geometryChanged) {
        view.requestMeasure({ read: updatePosition });
      }
    },
    destroy() {
      ruler.remove();
    }
  };
});

// src/codemirror/setup.ts
var baseExtensions = [
  lineNumbers(),
  highlightSpecialChars(),
  history(),
  foldGutter(),
  drawSelection(),
  EditorState.allowMultipleSelections.of(true),
  indentOnInput(),
  bracketMatching(),
  closeBrackets(),
  autocompletion(),
  rectangularSelection(),
  highlightActiveLine(),
  highlightSelectionMatches(),
  lintGutter(),
  keymap.of([
    ...closeBracketsKeymap,
    ...defaultKeymap,
    ...searchKeymap,
    ...historyKeymap,
    ...foldKeymap,
    ...completionKeymap,
    ...lintKeymap,
    indentWithTab
  ])
];
function setup(value, extensions3) {
  const view = new EditorView({
    state: EditorState.create({ doc: value, extensions: extensions3 })
  });
  return {
    editor: view,
    renderEditor: (el) => {
      el.appendChild(view.dom);
    }
  };
}
function initDocumentPreviewEditor(value) {
  return setup(value, [
    baseExtensions,
    EditorState.readOnly.of(true),
    placeholder("Loading...")
  ]);
}
var BeancountTextarea = class extends HTMLTextAreaElement {
  constructor() {
    super();
    getBeancountLanguageSupport().then((beancount) => {
      const { editor: editor2 } = setup(this.value, [
        beancount,
        syntaxHighlighting(defaultHighlightStyle),
        EditorView.editable.of(false)
      ]);
      this.parentNode?.insertBefore(editor2.dom, this);
      this.style.display = "none";
    }).catch(log_error);
  }
};
function initBeancountEditor(value, onDocChanges, commands2, beancount) {
  const { indent, currency_column } = get2(fava_options);
  return setup(value, [
    beancount,
    indentUnit.of(" ".repeat(indent)),
    ...currency_column ? [rulerPlugin(currency_column - 1)] : [],
    keymap.of(commands2),
    EditorView.updateListener.of((update3) => {
      if (update3.docChanged) {
        onDocChanges(update3.state);
      }
    }),
    baseExtensions,
    syntaxHighlighting(beancountEditorHighlight)
  ]);
}
function initReadonlyQueryEditor(value) {
  return setup(value, [
    bql,
    syntaxHighlighting(beancountQueryHighlight),
    EditorView.editable.of(false)
  ]);
}
function initQueryEditor(value, onDocChanges, _placeholder, submit) {
  return setup(value, [
    bql,
    EditorView.updateListener.of((update3) => {
      if (update3.docChanged) {
        onDocChanges(update3.state);
      }
    }),
    keymap.of([
      {
        key: "Control-Enter",
        mac: "Meta-Enter",
        run: () => {
          submit();
          return true;
        }
      }
    ]),
    placeholder(_placeholder),
    baseExtensions,
    syntaxHighlighting(beancountQueryHighlight)
  ]);
}

// src/extensions.ts
var ExtensionApi = class {
  constructor(name3) {
    this.name = name3;
  }
  /** Send a request to an extension endpoint. */
  async request(endpoint, method, params, body2, output = "json") {
    const $urlForRaw = get2(urlForRaw);
    const url = $urlForRaw(`extension/${this.name}/${endpoint}`, params);
    let opts2 = {};
    if (body2 != null) {
      opts2 = body2 instanceof FormData ? { body: body2 } : {
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body2)
      };
    }
    const response = await fetch2(url, { method, ...opts2 });
    if (output === "json") {
      return response.json();
    }
    if (output === "string") {
      return response.text();
    }
    return response;
  }
  /** GET an endpoint with parameters and return JSON. */
  async get(endpoint, params) {
    return this.request(endpoint, "GET", params, void 0);
  }
  /** GET an endpoint with a body and return JSON. */
  async put(endpoint, body2) {
    return this.request(endpoint, "PUT", void 0, body2);
  }
  /** POST to an endpoint with a body and return JSON. */
  async post(endpoint, body2) {
    return this.request(endpoint, "POST", void 0, body2);
  }
  /** DELETE an endpoint and return JSON. */
  async delete(endpoint) {
    return this.request(endpoint, "DELETE");
  }
};
var ExtensionData = class {
  constructor(extension, context2) {
    this.extension = extension;
    this.context = context2;
  }
  async init() {
    await this.extension.init?.(this.context);
  }
  onPageLoad() {
    this.extension.onPageLoad?.(this.context);
  }
  onExtensionPageLoad() {
    this.extension.onExtensionPageLoad?.(this.context);
  }
};
async function loadExtensionModule(name3) {
  const $urlForRaw = get2(urlForRaw);
  const url = $urlForRaw(`extension_js_module/${name3}.js`);
  const mod = await import(url);
  if (typeof mod.default === "object") {
    return new ExtensionData(mod.default, { api: new ExtensionApi(name3) });
  }
  throw new Error(
    `Error importing module for extension ${name3}: module must export "default" object`
  );
}
var loaded_extensions = /* @__PURE__ */ new Map();
async function getOrInitExtension(name3) {
  const loaded_ext = loaded_extensions.get(name3);
  if (loaded_ext) {
    return loaded_ext;
  }
  const ext_promise = loadExtensionModule(name3);
  loaded_extensions.set(name3, ext_promise);
  await (await ext_promise).init();
  return ext_promise;
}
function handleExtensionPageLoad() {
  const exts = get2(extensions).filter((e) => e.has_js_module);
  for (const { name: name3 } of exts) {
    getOrInitExtension(name3).then((m2) => {
      m2.onPageLoad();
    }).catch(log_error);
  }
  const path2 = getUrlPath(window.location) ?? "";
  if (path2.startsWith("extension/")) {
    for (const { name: name3 } of exts) {
      if (path2.startsWith(`extension/${name3}`)) {
        getOrInitExtension(name3).then((m2) => {
          m2.onExtensionPageLoad();
        }).catch(log_error);
      }
    }
  }
}

// node_modules/svelte/src/version.js
var PUBLIC_VERSION = "5";

// node_modules/svelte/src/internal/disclose-version.js
if (typeof window !== "undefined") {
  ((window.__svelte ??= {}).v ??= /* @__PURE__ */ new Set()).add(PUBLIC_VERSION);
}

// src/keyboard-shortcuts.ts
function showTooltip2(target, description) {
  const { hidden } = target;
  if (hidden) {
    target.hidden = false;
  }
  const tooltip2 = document.createElement("div");
  tooltip2.className = "keyboard-tooltip";
  tooltip2.textContent = description;
  document.body.appendChild(tooltip2);
  const targetRect = target.getBoundingClientRect();
  const left2 = targetRect.left + Math.min((target.offsetWidth - tooltip2.offsetWidth) / 2, 10);
  const top3 = targetRect.top + (target.offsetHeight - tooltip2.offsetHeight) / 2;
  tooltip2.style.left = `${left2.toString()}px`;
  tooltip2.style.top = `${(top3 + window.scrollY).toString()}px`;
  return () => {
    tooltip2.remove();
    if (hidden) {
      target.hidden = true;
    }
  };
}
function showTooltips() {
  const removes = [];
  document.querySelectorAll("[data-key]").forEach((el) => {
    const key2 = el.getAttribute("data-key");
    if (el instanceof HTMLElement && key2 !== null) {
      removes.push(showTooltip2(el, key2));
    }
  });
  return () => {
    removes.forEach((r2) => {
      r2();
    });
  };
}
function isEditableElement(element2) {
  return element2 instanceof HTMLElement && (element2 instanceof HTMLInputElement || element2 instanceof HTMLSelectElement || element2 instanceof HTMLTextAreaElement || element2.isContentEditable);
}
var keyboardShortcuts = /* @__PURE__ */ new Map();
var lastChar = "";
function keydown(event2) {
  if (isEditableElement(event2.target)) {
    return;
  }
  let eventKey = event2.key;
  if (event2.metaKey) {
    eventKey = `Meta+${eventKey}`;
  }
  if (event2.altKey) {
    eventKey = `Alt+${eventKey}`;
  }
  if (event2.ctrlKey) {
    eventKey = `Control+${eventKey}`;
  }
  const lastTwoKeys = `${lastChar} ${eventKey}`;
  const handler = keyboardShortcuts.get(lastTwoKeys) ?? keyboardShortcuts.get(eventKey);
  if (handler) {
    if (handler instanceof HTMLInputElement) {
      event2.preventDefault();
      handler.focus();
    } else if (handler instanceof HTMLElement) {
      event2.preventDefault();
      handler.click();
    } else {
      handler(event2);
    }
  }
  if (event2.key !== "Alt" && event2.key !== "Control" && event2.key !== "Shift") {
    lastChar = eventKey;
  }
}
document.addEventListener("keydown", keydown);
var isMac = (
  // This still seems to be the least bad way to check whether we are running on macOS or iOS
  // eslint-disable-next-line @typescript-eslint/no-deprecated
  navigator.platform.startsWith("Mac") || navigator.platform === "iPhone"
);
var modKey = isMac ? "Cmd" : "Ctrl";
function getKeySpecKey(spec) {
  if (typeof spec === "string") {
    return spec;
  }
  return isMac ? spec.mac ?? spec.key : spec.key;
}
function getKeySpecDescription(spec) {
  if (typeof spec === "string") {
    return spec;
  }
  const key2 = isMac ? spec.mac ?? spec.key : spec.key;
  return spec.note != null ? `${key2} - ${spec.note}` : key2;
}
function bindKey(spec, handler) {
  const key2 = getKeySpecKey(spec);
  const sequence = key2.split(" ");
  if (sequence.length > 2) {
    console.error("Only key sequences of length <=2 are supported: ", key2);
  }
  if (keyboardShortcuts.has(key2)) {
    console.warn("Duplicate keyboard shortcut: ", key2, handler);
  }
  keyboardShortcuts.set(key2, handler);
  return () => {
    keyboardShortcuts.delete(key2);
  };
}
var keyboardShortcut = (node, spec) => {
  const setup2 = (s) => {
    if (s != null) {
      node.setAttribute("data-key", getKeySpecDescription(s));
      const unbind = bindKey(s, node);
      return () => {
        unbind();
        node.removeAttribute("data-key");
      };
    }
    return () => {
    };
  };
  let destroy = setup2(spec);
  return {
    destroy,
    update(new_spec) {
      destroy();
      tick().then(() => {
        destroy = setup2(new_spec);
      }).catch(log_error);
    }
  };
};
function initGlobalKeyboardShortcuts() {
  bindKey("?", () => {
    const hide2 = showTooltips();
    const once2 = () => {
      hide2();
      document.removeEventListener("mousedown", once2);
      document.removeEventListener("keydown", once2);
      document.removeEventListener("scroll", once2);
    };
    document.addEventListener("mousedown", once2);
    document.addEventListener("keydown", once2);
    document.addEventListener("scroll", once2);
  });
}

// src/journal/JournalFilters.svelte
var toggleText = _("Toggle %(type)s entries");
var buttons = [
  ["open", "Open", null, "s o"],
  ["close", "Close", null, "s c"],
  ["transaction", "Transaction", null, "s t"],
  [
    "cleared",
    "*",
    _("Cleared transactions"),
    "t c",
    "transaction"
  ],
  [
    "pending",
    "!",
    _("Pending transactions"),
    "t p",
    "transaction"
  ],
  [
    "other",
    "x",
    _("Other transactions"),
    "t o",
    "transaction"
  ],
  ["balance", "Balance", null, "s b"],
  ["note", "Note", null, "s n"],
  ["document", "Document", null, "s d"],
  [
    "discovered",
    "D",
    _("Documents with a #discovered tag"),
    "d d",
    "document"
  ],
  [
    "linked",
    "L",
    _("Documents with a #linked tag"),
    "d l",
    "document"
  ],
  ["pad", "Pad", null, "s p"],
  ["query", "Query", null, "s q"],
  ["custom", "Custom", null, "s C"],
  [
    "budget",
    "B",
    _("Budget entries"),
    "s B",
    "custom"
  ],
  [
    "metadata",
    _("Metadata"),
    _("Toggle metadata"),
    "m"
  ],
  [
    "postings",
    _("Postings"),
    _("Toggle postings"),
    "p"
  ]
];
var on_click = (__1, toggle2, type) => {
  toggle2(type());
};
var root_1 = template(`<button type="button"> </button>`);
var root = template(`<form class="flex-row svelte-h52b2r"></form>`);
function JournalFilters($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $journalShow = () => store_get(journalShow, "$journalShow", $$stores);
  let shownSet = user_derived(() => new Set($journalShow()));
  function toggle2(type) {
    journalShow.update((show) => {
      const set4 = new Set(show);
      const toggle_func = set4.has(type) ? set4.delete.bind(set4) : set4.add.bind(set4);
      toggle_func(type);
      buttons.filter((b) => b[4] === type).forEach((b) => toggle_func(b[0]));
      return [...set4].sort();
    });
  }
  let active = user_derived(() => (type, supertype) => supertype != null ? get(shownSet).has(type) && get(shownSet).has(supertype) : get(shownSet).has(type));
  var form = root();
  each(form, 21, () => buttons, index, ($$anchor2, $$item) => {
    let type = () => get($$item)[0];
    let button_text = () => get($$item)[1];
    let title = () => get($$item)[2];
    let shortcut = () => get($$item)[3];
    let supertype = () => get($$item)[4];
    var button = root_1();
    button.__click = [on_click, toggle2, type];
    let classes;
    var text2 = child(button, true);
    reset(button);
    action(button, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), shortcut);
    template_effect(
      ($0, $1) => {
        set_attribute(button, "title", $0);
        classes = set_class(button, 1, "", null, classes, $1);
        set_text(text2, button_text());
      },
      [
        () => title() ?? format(toggleText, { type: button_text() }),
        () => ({
          inactive: !get(active)(type(), supertype())
        })
      ]
    );
    append($$anchor2, button);
  });
  reset(form);
  append($$anchor, form);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/journal/index.ts
function escape(value) {
  return value.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
}
function addFilter(value) {
  fql_filter.update(
    (fql_filter_val) => fql_filter_val ? `${fql_filter_val} ${value}` : value
  );
}
function handleClick({ target }) {
  if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
    return;
  }
  if (target.className === "tag" || target.className === "link") {
    addFilter(target.innerText);
  } else if (target.className === "payee") {
    addFilter(`payee:"^${escape(target.innerText)}$"`);
  } else if (target.tagName === "DT") {
    const expr = `${target.innerText}""`;
    if (target.closest(".postings")) {
      addFilter(`any(${expr})`);
    } else {
      addFilter(expr);
    }
  } else if (target.tagName === "DD") {
    const key2 = target.previousElementSibling.innerText;
    const value = `"^${escape(target.innerText)}$"`;
    const expr = `${key2}${value}`;
    if (target.closest(".postings")) {
      addFilter(`any(${expr})`);
    } else {
      addFilter(expr);
    }
  } else if (target.closest(".indicators")) {
    const entry = target.closest(".journal > li");
    if (entry) {
      entry.classList.toggle("show-full-entry");
    }
  }
}
var FavaJournal = class extends HTMLElement {
  /** Unmount the Svelte component. */
  unmount;
  /** Unsubscribe store listener. */
  unsubscribe;
  connectedCallback() {
    const ol = this.querySelector("ol");
    if (!ol) {
      throw new Error("fava-journal is missing its <ol>");
    }
    this.unsubscribe = journalShow.subscribe((show) => {
      const classes = [...show].map((s) => `show-${s}`).join(" ");
      ol.className = `flex-table journal ${classes}`;
    });
    const component2 = mount(JournalFilters, { target: this, anchor: ol });
    this.unmount = () => {
      void unmount(component2);
    };
    sortableJournal(ol);
    delegate2(this, "click", "li", handleClick);
  }
  disconnectedCallback() {
    this.unsubscribe?.();
    this.unmount?.();
  }
};

// src/reports/ReportLoadError.svelte
var root2 = template(`<h2> </h2> <pre class="svelte-1y86mi2"> </pre>`, 1);
function ReportLoadError($$anchor, $$props) {
  push($$props, true);
  var fragment = root2();
  var h2 = first_child(fragment);
  var text2 = child(h2);
  reset(h2);
  var pre = sibling(h2, 2);
  var text_1 = child(pre, true);
  reset(pre);
  template_effect(
    ($0) => {
      set_text(text2, `Loading ${$$props.title ?? ""} failed with error:`);
      set_text(text_1, $0);
    },
    [() => errorWithCauses($$props.error)]
  );
  append($$anchor, fragment);
  pop();
}

// src/reports/route.svelte.ts
function updateable_props(raw_props) {
  const props2 = proxy2(raw_props);
  return [
    props2,
    (new_props) => {
      Object.assign(props2, new_props);
    }
  ];
}

// src/reports/route.ts
var Route = class {
  /**
   * Create a new frontend-rendered route.
   * @param report URL slug of this report.
   * @param Component the component to render for this report.
   * @param load function to load the necessary data.
   * @param get_title function to get the page title.
   */
  constructor(report, Component, load, get_title) {
    this.report = report;
    this.Component = Component;
    this.load = load;
    this.get_title = get_title;
  }
  /** The currently rendered instance - if loading failed, we render an error component. */
  instance;
  /** The currently rendered URL. */
  url;
  /** The title of this report. */
  get title() {
    return this.get_title(this);
  }
  /** Destroy any components that might be rendered by this route. */
  destroy() {
    if (this.instance) {
      void unmount(this.instance.component);
    }
    this.instance = void 0;
  }
  /** Load data and render the component for this route to the given target. */
  async render(target, url, previous) {
    if (previous !== this) {
      previous?.destroy();
    }
    try {
      const raw_props = await this.load(url);
      if (previous === this && this.instance?.error === false) {
        this.instance.update_props(raw_props);
      } else {
        this.destroy();
        target.innerHTML = "";
        const [props2, update_props] = updateable_props(raw_props);
        this.instance = {
          error: false,
          component: mount(this.Component, { target, props: props2 }),
          update_props
        };
      }
    } catch (error2) {
      log_error(error2);
      if (error2 instanceof Error) {
        this.destroy();
        target.innerHTML = "";
        this.instance = {
          error: true,
          component: mount(ReportLoadError, {
            target,
            props: { title: this.title, error: error2 }
          })
        };
      }
    } finally {
      this.url = url;
    }
  }
};
var noload = () => ({});
var DatalessRoute = class extends Route {
  constructor(report, Component, get_title) {
    super(report, Component, noload, get_title);
  }
};

// node_modules/d3-shape/src/constant.js
function constant_default2(x2) {
  return function constant2() {
    return x2;
  };
}

// node_modules/d3-shape/src/math.js
var abs = Math.abs;
var atan2 = Math.atan2;
var cos = Math.cos;
var max2 = Math.max;
var min2 = Math.min;
var sin = Math.sin;
var sqrt = Math.sqrt;
var epsilon = 1e-12;
var pi = Math.PI;
var halfPi = pi / 2;
var tau = 2 * pi;
function acos(x2) {
  return x2 > 1 ? 0 : x2 < -1 ? pi : Math.acos(x2);
}
function asin(x2) {
  return x2 >= 1 ? halfPi : x2 <= -1 ? -halfPi : Math.asin(x2);
}

// node_modules/d3-path/src/path.js
var pi2 = Math.PI;
var tau2 = 2 * pi2;
var epsilon2 = 1e-6;
var tauEpsilon = tau2 - epsilon2;
function append2(strings) {
  this._ += strings[0];
  for (let i2 = 1, n = strings.length; i2 < n; ++i2) {
    this._ += arguments[i2] + strings[i2];
  }
}
function appendRound(digits) {
  let d = Math.floor(digits);
  if (!(d >= 0)) throw new Error(`invalid digits: ${digits}`);
  if (d > 15) return append2;
  const k = 10 ** d;
  return function(strings) {
    this._ += strings[0];
    for (let i2 = 1, n = strings.length; i2 < n; ++i2) {
      this._ += Math.round(arguments[i2] * k) / k + strings[i2];
    }
  };
}
var Path = class {
  constructor(digits) {
    this._x0 = this._y0 = // start of current subpath
    this._x1 = this._y1 = null;
    this._ = "";
    this._append = digits == null ? append2 : appendRound(digits);
  }
  moveTo(x2, y2) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}`;
  }
  closePath() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._append`Z`;
    }
  }
  lineTo(x2, y2) {
    this._append`L${this._x1 = +x2},${this._y1 = +y2}`;
  }
  quadraticCurveTo(x1, y1, x2, y2) {
    this._append`Q${+x1},${+y1},${this._x1 = +x2},${this._y1 = +y2}`;
  }
  bezierCurveTo(x1, y1, x2, y2, x3, y3) {
    this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x3},${this._y1 = +y3}`;
  }
  arcTo(x1, y1, x2, y2, r2) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r2 = +r2;
    if (r2 < 0) throw new Error(`negative radius: ${r2}`);
    let x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01;
    if (this._x1 === null) {
      this._append`M${this._x1 = x1},${this._y1 = y1}`;
    } else if (!(l01_2 > epsilon2)) ;
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon2) || !r2) {
      this._append`L${this._x1 = x1},${this._y1 = y1}`;
    } else {
      let x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r2 * Math.tan((pi2 - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21;
      if (Math.abs(t01 - 1) > epsilon2) {
        this._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;
      }
      this._append`A${r2},${r2},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;
    }
  }
  arc(x2, y2, r2, a0, a1, ccw) {
    x2 = +x2, y2 = +y2, r2 = +r2, ccw = !!ccw;
    if (r2 < 0) throw new Error(`negative radius: ${r2}`);
    let dx = r2 * Math.cos(a0), dy = r2 * Math.sin(a0), x0 = x2 + dx, y0 = y2 + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
    if (this._x1 === null) {
      this._append`M${x0},${y0}`;
    } else if (Math.abs(this._x1 - x0) > epsilon2 || Math.abs(this._y1 - y0) > epsilon2) {
      this._append`L${x0},${y0}`;
    }
    if (!r2) return;
    if (da < 0) da = da % tau2 + tau2;
    if (da > tauEpsilon) {
      this._append`A${r2},${r2},0,1,${cw},${x2 - dx},${y2 - dy}A${r2},${r2},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`;
    } else if (da > epsilon2) {
      this._append`A${r2},${r2},0,${+(da >= pi2)},${cw},${this._x1 = x2 + r2 * Math.cos(a1)},${this._y1 = y2 + r2 * Math.sin(a1)}`;
    }
  }
  rect(x2, y2, w, h) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}h${w = +w}v${+h}h${-w}Z`;
  }
  toString() {
    return this._;
  }
};
function path() {
  return new Path();
}
path.prototype = Path.prototype;

// node_modules/d3-shape/src/path.js
function withPath(shape) {
  let digits = 3;
  shape.digits = function(_2) {
    if (!arguments.length) return digits;
    if (_2 == null) {
      digits = null;
    } else {
      const d = Math.floor(_2);
      if (!(d >= 0)) throw new RangeError(`invalid digits: ${_2}`);
      digits = d;
    }
    return shape;
  };
  return () => new Path(digits);
}

// node_modules/d3-shape/src/arc.js
function arcInnerRadius(d) {
  return d.innerRadius;
}
function arcOuterRadius(d) {
  return d.outerRadius;
}
function arcStartAngle(d) {
  return d.startAngle;
}
function arcEndAngle(d) {
  return d.endAngle;
}
function arcPadAngle(d) {
  return d && d.padAngle;
}
function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t4 = y32 * x10 - x32 * y10;
  if (t4 * t4 < epsilon) return;
  t4 = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t4;
  return [x0 + t4 * x10, y0 + t4 * y10];
}
function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  var x01 = x0 - x1, y01 = y0 - y1, lo = (cw ? rc : -rc) / sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r2 = r1 - rc, D = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * sqrt(max2(0, r2 * r2 * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00;
  if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
  return {
    cx: cx0,
    cy: cy0,
    x01: -ox,
    y01: -oy,
    x11: cx0 * (r1 / r2 - 1),
    y11: cy0 * (r1 / r2 - 1)
  };
}
function arc_default() {
  var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant_default2(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context2 = null, path2 = withPath(arc);
  function arc() {
    var buffer, r2, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi, a1 = endAngle.apply(this, arguments) - halfPi, da = abs(a1 - a0), cw = a1 > a0;
    if (!context2) context2 = buffer = path2();
    if (r1 < r0) r2 = r1, r1 = r0, r0 = r2;
    if (!(r1 > epsilon)) context2.moveTo(0, 0);
    else if (da > tau - epsilon) {
      context2.moveTo(r1 * cos(a0), r1 * sin(a0));
      context2.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > epsilon) {
        context2.moveTo(r0 * cos(a1), r0 * sin(a1));
        context2.arc(0, 0, r0, a1, a0, cw);
      }
    } else {
      var a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da, da1 = da, ap = padAngle.apply(this, arguments) / 2, rp = ap > epsilon && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)), rc = min2(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t03, t13;
      if (rp > epsilon) {
        var p0 = asin(rp / r0 * sin(ap)), p1 = asin(rp / r1 * sin(ap));
        if ((da0 -= p0 * 2) > epsilon) p0 *= cw ? 1 : -1, a00 += p0, a10 -= p0;
        else da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > epsilon) p1 *= cw ? 1 : -1, a01 += p1, a11 -= p1;
        else da1 = 0, a01 = a11 = (a0 + a1) / 2;
      }
      var x01 = r1 * cos(a01), y01 = r1 * sin(a01), x10 = r0 * cos(a10), y10 = r0 * sin(a10);
      if (rc > epsilon) {
        var x11 = r1 * cos(a11), y11 = r1 * sin(a11), x00 = r0 * cos(a00), y00 = r0 * sin(a00), oc;
        if (da < pi) {
          if (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10)) {
            var ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2), lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
            rc0 = min2(rc, (r0 - lc) / (kc - 1));
            rc1 = min2(rc, (r1 - lc) / (kc + 1));
          } else {
            rc0 = rc1 = 0;
          }
        }
      }
      if (!(da1 > epsilon)) context2.moveTo(x01, y01);
      else if (rc1 > epsilon) {
        t03 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t13 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
        context2.moveTo(t03.cx + t03.x01, t03.cy + t03.y01);
        if (rc1 < rc) context2.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
        else {
          context2.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
          context2.arc(0, 0, r1, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), !cw);
          context2.arc(t13.cx, t13.cy, rc1, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
        }
      } else context2.moveTo(x01, y01), context2.arc(0, 0, r1, a01, a11, !cw);
      if (!(r0 > epsilon) || !(da0 > epsilon)) context2.lineTo(x10, y10);
      else if (rc0 > epsilon) {
        t03 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t13 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
        context2.lineTo(t03.cx + t03.x01, t03.cy + t03.y01);
        if (rc0 < rc) context2.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
        else {
          context2.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
          context2.arc(0, 0, r0, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), cw);
          context2.arc(t13.cx, t13.cy, rc0, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
        }
      } else context2.arc(0, 0, r0, a10, a00, cw);
    }
    context2.closePath();
    if (buffer) return context2 = null, buffer + "" || null;
  }
  arc.centroid = function() {
    var r2 = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;
    return [cos(a) * r2, sin(a) * r2];
  };
  arc.innerRadius = function(_2) {
    return arguments.length ? (innerRadius = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : innerRadius;
  };
  arc.outerRadius = function(_2) {
    return arguments.length ? (outerRadius = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : outerRadius;
  };
  arc.cornerRadius = function(_2) {
    return arguments.length ? (cornerRadius = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : cornerRadius;
  };
  arc.padRadius = function(_2) {
    return arguments.length ? (padRadius = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : padRadius;
  };
  arc.startAngle = function(_2) {
    return arguments.length ? (startAngle = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : startAngle;
  };
  arc.endAngle = function(_2) {
    return arguments.length ? (endAngle = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : endAngle;
  };
  arc.padAngle = function(_2) {
    return arguments.length ? (padAngle = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : padAngle;
  };
  arc.context = function(_2) {
    return arguments.length ? (context2 = _2 == null ? null : _2, arc) : context2;
  };
  return arc;
}

// node_modules/d3-shape/src/array.js
var slice = Array.prototype.slice;
function array_default(x2) {
  return typeof x2 === "object" && "length" in x2 ? x2 : Array.from(x2);
}

// node_modules/d3-shape/src/curve/linear.js
function Linear(context2) {
  this._context = context2;
}
Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
      // falls through
      default:
        this._context.lineTo(x2, y2);
        break;
    }
  }
};
function linear_default(context2) {
  return new Linear(context2);
}

// node_modules/d3-shape/src/point.js
function x(p) {
  return p[0];
}
function y(p) {
  return p[1];
}

// node_modules/d3-shape/src/line.js
function line_default(x2, y2) {
  var defined = constant_default2(true), context2 = null, curve = linear_default, output = null, path2 = withPath(line);
  x2 = typeof x2 === "function" ? x2 : x2 === void 0 ? x : constant_default2(x2);
  y2 = typeof y2 === "function" ? y2 : y2 === void 0 ? y : constant_default2(y2);
  function line(data) {
    var i2, n = (data = array_default(data)).length, d, defined0 = false, buffer;
    if (context2 == null) output = curve(buffer = path2());
    for (i2 = 0; i2 <= n; ++i2) {
      if (!(i2 < n && defined(d = data[i2], i2, data)) === defined0) {
        if (defined0 = !defined0) output.lineStart();
        else output.lineEnd();
      }
      if (defined0) output.point(+x2(d, i2, data), +y2(d, i2, data));
    }
    if (buffer) return output = null, buffer + "" || null;
  }
  line.x = function(_2) {
    return arguments.length ? (x2 = typeof _2 === "function" ? _2 : constant_default2(+_2), line) : x2;
  };
  line.y = function(_2) {
    return arguments.length ? (y2 = typeof _2 === "function" ? _2 : constant_default2(+_2), line) : y2;
  };
  line.defined = function(_2) {
    return arguments.length ? (defined = typeof _2 === "function" ? _2 : constant_default2(!!_2), line) : defined;
  };
  line.curve = function(_2) {
    return arguments.length ? (curve = _2, context2 != null && (output = curve(context2)), line) : curve;
  };
  line.context = function(_2) {
    return arguments.length ? (_2 == null ? context2 = output = null : output = curve(context2 = _2), line) : context2;
  };
  return line;
}

// node_modules/d3-shape/src/area.js
function area_default(x0, y0, y1) {
  var x1 = null, defined = constant_default2(true), context2 = null, curve = linear_default, output = null, path2 = withPath(area);
  x0 = typeof x0 === "function" ? x0 : x0 === void 0 ? x : constant_default2(+x0);
  y0 = typeof y0 === "function" ? y0 : y0 === void 0 ? constant_default2(0) : constant_default2(+y0);
  y1 = typeof y1 === "function" ? y1 : y1 === void 0 ? y : constant_default2(+y1);
  function area(data) {
    var i2, j, k, n = (data = array_default(data)).length, d, defined0 = false, buffer, x0z = new Array(n), y0z = new Array(n);
    if (context2 == null) output = curve(buffer = path2());
    for (i2 = 0; i2 <= n; ++i2) {
      if (!(i2 < n && defined(d = data[i2], i2, data)) === defined0) {
        if (defined0 = !defined0) {
          j = i2;
          output.areaStart();
          output.lineStart();
        } else {
          output.lineEnd();
          output.lineStart();
          for (k = i2 - 1; k >= j; --k) {
            output.point(x0z[k], y0z[k]);
          }
          output.lineEnd();
          output.areaEnd();
        }
      }
      if (defined0) {
        x0z[i2] = +x0(d, i2, data), y0z[i2] = +y0(d, i2, data);
        output.point(x1 ? +x1(d, i2, data) : x0z[i2], y1 ? +y1(d, i2, data) : y0z[i2]);
      }
    }
    if (buffer) return output = null, buffer + "" || null;
  }
  function arealine() {
    return line_default().defined(defined).curve(curve).context(context2);
  }
  area.x = function(_2) {
    return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default2(+_2), x1 = null, area) : x0;
  };
  area.x0 = function(_2) {
    return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default2(+_2), area) : x0;
  };
  area.x1 = function(_2) {
    return arguments.length ? (x1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default2(+_2), area) : x1;
  };
  area.y = function(_2) {
    return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default2(+_2), y1 = null, area) : y0;
  };
  area.y0 = function(_2) {
    return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default2(+_2), area) : y0;
  };
  area.y1 = function(_2) {
    return arguments.length ? (y1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default2(+_2), area) : y1;
  };
  area.lineX0 = area.lineY0 = function() {
    return arealine().x(x0).y(y0);
  };
  area.lineY1 = function() {
    return arealine().x(x0).y(y1);
  };
  area.lineX1 = function() {
    return arealine().x(x1).y(y0);
  };
  area.defined = function(_2) {
    return arguments.length ? (defined = typeof _2 === "function" ? _2 : constant_default2(!!_2), area) : defined;
  };
  area.curve = function(_2) {
    return arguments.length ? (curve = _2, context2 != null && (output = curve(context2)), area) : curve;
  };
  area.context = function(_2) {
    return arguments.length ? (_2 == null ? context2 = output = null : output = curve(context2 = _2), area) : context2;
  };
  return area;
}

// node_modules/d3-shape/src/curve/step.js
function Step(context2, t4) {
  this._context = context2;
  this._t = t4;
}
Step.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = this._y = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
      // falls through
      default: {
        if (this._t <= 0) {
          this._context.lineTo(this._x, y2);
          this._context.lineTo(x2, y2);
        } else {
          var x1 = this._x * (1 - this._t) + x2 * this._t;
          this._context.lineTo(x1, this._y);
          this._context.lineTo(x1, y2);
        }
        break;
      }
    }
    this._x = x2, this._y = y2;
  }
};
function stepAfter(context2) {
  return new Step(context2, 1);
}

// node_modules/d3-shape/src/offset/none.js
function none_default(series, order) {
  if (!((n = series.length) > 1)) return;
  for (var i2 = 1, j, s0, s1 = series[order[0]], n, m2 = s1.length; i2 < n; ++i2) {
    s0 = s1, s1 = series[order[i2]];
    for (j = 0; j < m2; ++j) {
      s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
    }
  }
}

// node_modules/d3-shape/src/order/none.js
function none_default2(series) {
  var n = series.length, o = new Array(n);
  while (--n >= 0) o[n] = n;
  return o;
}

// node_modules/d3-shape/src/stack.js
function stackValue(d, key2) {
  return d[key2];
}
function stackSeries(key2) {
  const series = [];
  series.key = key2;
  return series;
}
function stack_default() {
  var keys = constant_default2([]), order = none_default2, offset = none_default, value = stackValue;
  function stack2(data) {
    var sz = Array.from(keys.apply(this, arguments), stackSeries), i2, n = sz.length, j = -1, oz;
    for (const d of data) {
      for (i2 = 0, ++j; i2 < n; ++i2) {
        (sz[i2][j] = [0, +value(d, sz[i2].key, j, data)]).data = d;
      }
    }
    for (i2 = 0, oz = array_default(order(sz)); i2 < n; ++i2) {
      sz[oz[i2]].index = i2;
    }
    offset(sz, oz);
    return sz;
  }
  stack2.keys = function(_2) {
    return arguments.length ? (keys = typeof _2 === "function" ? _2 : constant_default2(Array.from(_2)), stack2) : keys;
  };
  stack2.value = function(_2) {
    return arguments.length ? (value = typeof _2 === "function" ? _2 : constant_default2(+_2), stack2) : value;
  };
  stack2.order = function(_2) {
    return arguments.length ? (order = _2 == null ? none_default2 : typeof _2 === "function" ? _2 : constant_default2(Array.from(_2)), stack2) : order;
  };
  stack2.offset = function(_2) {
    return arguments.length ? (offset = _2 == null ? none_default : _2, stack2) : offset;
  };
  return stack2;
}

// node_modules/d3-shape/src/offset/diverging.js
function diverging_default(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var i2, j = 0, d, dy, yp, yn, n, m2 = series[order[0]].length; j < m2; ++j) {
    for (yp = yn = 0, i2 = 0; i2 < n; ++i2) {
      if ((dy = (d = series[order[i2]][j])[1] - d[0]) > 0) {
        d[0] = yp, d[1] = yp += dy;
      } else if (dy < 0) {
        d[1] = yn, d[0] = yn += dy;
      } else {
        d[0] = 0, d[1] = dy;
      }
    }
  }
}

// node_modules/d3-selection/src/namespaces.js
var xhtml = "http://www.w3.org/1999/xhtml";
var namespaces_default = {
  svg: "http://www.w3.org/2000/svg",
  xhtml,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};

// node_modules/d3-selection/src/namespace.js
function namespace_default(name3) {
  var prefix = name3 += "", i2 = prefix.indexOf(":");
  if (i2 >= 0 && (prefix = name3.slice(0, i2)) !== "xmlns") name3 = name3.slice(i2 + 1);
  return namespaces_default.hasOwnProperty(prefix) ? { space: namespaces_default[prefix], local: name3 } : name3;
}

// node_modules/d3-selection/src/creator.js
function creatorInherit(name3) {
  return function() {
    var document2 = this.ownerDocument, uri = this.namespaceURI;
    return uri === xhtml && document2.documentElement.namespaceURI === xhtml ? document2.createElement(name3) : document2.createElementNS(uri, name3);
  };
}
function creatorFixed(fullname) {
  return function() {
    return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  };
}
function creator_default(name3) {
  var fullname = namespace_default(name3);
  return (fullname.local ? creatorFixed : creatorInherit)(fullname);
}

// node_modules/d3-selection/src/selector.js
function none4() {
}
function selector_default(selector) {
  return selector == null ? none4 : function() {
    return this.querySelector(selector);
  };
}

// node_modules/d3-selection/src/selection/select.js
function select_default(select) {
  if (typeof select !== "function") select = selector_default(select);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group2 = groups2[j], n = group2.length, subgroup = subgroups[j] = new Array(n), node, subnode, i2 = 0; i2 < n; ++i2) {
      if ((node = group2[i2]) && (subnode = select.call(node, node.__data__, i2, group2))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i2] = subnode;
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/array.js
function array2(x2) {
  return x2 == null ? [] : Array.isArray(x2) ? x2 : Array.from(x2);
}

// node_modules/d3-selection/src/selectorAll.js
function empty2() {
  return [];
}
function selectorAll_default(selector) {
  return selector == null ? empty2 : function() {
    return this.querySelectorAll(selector);
  };
}

// node_modules/d3-selection/src/selection/selectAll.js
function arrayAll(select) {
  return function() {
    return array2(select.apply(this, arguments));
  };
}
function selectAll_default(select) {
  if (typeof select === "function") select = arrayAll(select);
  else select = selectorAll_default(select);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = [], parents = [], j = 0; j < m2; ++j) {
    for (var group2 = groups2[j], n = group2.length, node, i2 = 0; i2 < n; ++i2) {
      if (node = group2[i2]) {
        subgroups.push(select.call(node, node.__data__, i2, group2));
        parents.push(node);
      }
    }
  }
  return new Selection(subgroups, parents);
}

// node_modules/d3-selection/src/matcher.js
function matcher_default(selector) {
  return function() {
    return this.matches(selector);
  };
}
function childMatcher(selector) {
  return function(node) {
    return node.matches(selector);
  };
}

// node_modules/d3-selection/src/selection/selectChild.js
var find2 = Array.prototype.find;
function childFind(match) {
  return function() {
    return find2.call(this.children, match);
  };
}
function childFirst() {
  return this.firstElementChild;
}
function selectChild_default(match) {
  return this.select(match == null ? childFirst : childFind(typeof match === "function" ? match : childMatcher(match)));
}

// node_modules/d3-selection/src/selection/selectChildren.js
var filter = Array.prototype.filter;
function children() {
  return Array.from(this.children);
}
function childrenFilter(match) {
  return function() {
    return filter.call(this.children, match);
  };
}
function selectChildren_default(match) {
  return this.selectAll(match == null ? children : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
}

// node_modules/d3-selection/src/selection/filter.js
function filter_default(match) {
  if (typeof match !== "function") match = matcher_default(match);
  for (var groups2 = this._groups, m2 = groups2.length, subgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group2 = groups2[j], n = group2.length, subgroup = subgroups[j] = [], node, i2 = 0; i2 < n; ++i2) {
      if ((node = group2[i2]) && match.call(node, node.__data__, i2, group2)) {
        subgroup.push(node);
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/selection/sparse.js
function sparse_default(update3) {
  return new Array(update3.length);
}

// node_modules/d3-selection/src/selection/enter.js
function enter_default() {
  return new Selection(this._enter || this._groups.map(sparse_default), this._parents);
}
function EnterNode(parent2, datum2) {
  this.ownerDocument = parent2.ownerDocument;
  this.namespaceURI = parent2.namespaceURI;
  this._next = null;
  this._parent = parent2;
  this.__data__ = datum2;
}
EnterNode.prototype = {
  constructor: EnterNode,
  appendChild: function(child2) {
    return this._parent.insertBefore(child2, this._next);
  },
  insertBefore: function(child2, next2) {
    return this._parent.insertBefore(child2, next2);
  },
  querySelector: function(selector) {
    return this._parent.querySelector(selector);
  },
  querySelectorAll: function(selector) {
    return this._parent.querySelectorAll(selector);
  }
};

// node_modules/d3-selection/src/constant.js
function constant_default3(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-selection/src/selection/data.js
function bindIndex(parent2, group2, enter, update3, exit, data) {
  var i2 = 0, node, groupLength = group2.length, dataLength = data.length;
  for (; i2 < dataLength; ++i2) {
    if (node = group2[i2]) {
      node.__data__ = data[i2];
      update3[i2] = node;
    } else {
      enter[i2] = new EnterNode(parent2, data[i2]);
    }
  }
  for (; i2 < groupLength; ++i2) {
    if (node = group2[i2]) {
      exit[i2] = node;
    }
  }
}
function bindKey2(parent2, group2, enter, update3, exit, data, key2) {
  var i2, node, nodeByKeyValue = /* @__PURE__ */ new Map(), groupLength = group2.length, dataLength = data.length, keyValues = new Array(groupLength), keyValue;
  for (i2 = 0; i2 < groupLength; ++i2) {
    if (node = group2[i2]) {
      keyValues[i2] = keyValue = key2.call(node, node.__data__, i2, group2) + "";
      if (nodeByKeyValue.has(keyValue)) {
        exit[i2] = node;
      } else {
        nodeByKeyValue.set(keyValue, node);
      }
    }
  }
  for (i2 = 0; i2 < dataLength; ++i2) {
    keyValue = key2.call(parent2, data[i2], i2, data) + "";
    if (node = nodeByKeyValue.get(keyValue)) {
      update3[i2] = node;
      node.__data__ = data[i2];
      nodeByKeyValue.delete(keyValue);
    } else {
      enter[i2] = new EnterNode(parent2, data[i2]);
    }
  }
  for (i2 = 0; i2 < groupLength; ++i2) {
    if ((node = group2[i2]) && nodeByKeyValue.get(keyValues[i2]) === node) {
      exit[i2] = node;
    }
  }
}
function datum(node) {
  return node.__data__;
}
function data_default(value, key2) {
  if (!arguments.length) return Array.from(this, datum);
  var bind = key2 ? bindKey2 : bindIndex, parents = this._parents, groups2 = this._groups;
  if (typeof value !== "function") value = constant_default3(value);
  for (var m2 = groups2.length, update3 = new Array(m2), enter = new Array(m2), exit = new Array(m2), j = 0; j < m2; ++j) {
    var parent2 = parents[j], group2 = groups2[j], groupLength = group2.length, data = arraylike(value.call(parent2, parent2 && parent2.__data__, j, parents)), dataLength = data.length, enterGroup = enter[j] = new Array(dataLength), updateGroup = update3[j] = new Array(dataLength), exitGroup = exit[j] = new Array(groupLength);
    bind(parent2, group2, enterGroup, updateGroup, exitGroup, data, key2);
    for (var i0 = 0, i1 = 0, previous, next2; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1) i1 = i0 + 1;
        while (!(next2 = updateGroup[i1]) && ++i1 < dataLength) ;
        previous._next = next2 || null;
      }
    }
  }
  update3 = new Selection(update3, parents);
  update3._enter = enter;
  update3._exit = exit;
  return update3;
}
function arraylike(data) {
  return typeof data === "object" && "length" in data ? data : Array.from(data);
}

// node_modules/d3-selection/src/selection/exit.js
function exit_default() {
  return new Selection(this._exit || this._groups.map(sparse_default), this._parents);
}

// node_modules/d3-selection/src/selection/join.js
function join_default(onenter, onupdate, onexit) {
  var enter = this.enter(), update3 = this, exit = this.exit();
  if (typeof onenter === "function") {
    enter = onenter(enter);
    if (enter) enter = enter.selection();
  } else {
    enter = enter.append(onenter + "");
  }
  if (onupdate != null) {
    update3 = onupdate(update3);
    if (update3) update3 = update3.selection();
  }
  if (onexit == null) exit.remove();
  else onexit(exit);
  return enter && update3 ? enter.merge(update3).order() : update3;
}

// node_modules/d3-selection/src/selection/merge.js
function merge_default(context2) {
  var selection2 = context2.selection ? context2.selection() : context2;
  for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m2; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i2 = 0; i2 < n; ++i2) {
      if (node = group0[i2] || group1[i2]) {
        merge[i2] = node;
      }
    }
  }
  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }
  return new Selection(merges, this._parents);
}

// node_modules/d3-selection/src/selection/order.js
function order_default() {
  for (var groups2 = this._groups, j = -1, m2 = groups2.length; ++j < m2; ) {
    for (var group2 = groups2[j], i2 = group2.length - 1, next2 = group2[i2], node; --i2 >= 0; ) {
      if (node = group2[i2]) {
        if (next2 && node.compareDocumentPosition(next2) ^ 4) next2.parentNode.insertBefore(node, next2);
        next2 = node;
      }
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/sort.js
function sort_default2(compare2) {
  if (!compare2) compare2 = ascending2;
  function compareNode(a, b) {
    return a && b ? compare2(a.__data__, b.__data__) : !a - !b;
  }
  for (var groups2 = this._groups, m2 = groups2.length, sortgroups = new Array(m2), j = 0; j < m2; ++j) {
    for (var group2 = groups2[j], n = group2.length, sortgroup = sortgroups[j] = new Array(n), node, i2 = 0; i2 < n; ++i2) {
      if (node = group2[i2]) {
        sortgroup[i2] = node;
      }
    }
    sortgroup.sort(compareNode);
  }
  return new Selection(sortgroups, this._parents).order();
}
function ascending2(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-selection/src/selection/call.js
function call_default() {
  var callback = arguments[0];
  arguments[0] = this;
  callback.apply(null, arguments);
  return this;
}

// node_modules/d3-selection/src/selection/nodes.js
function nodes_default() {
  return Array.from(this);
}

// node_modules/d3-selection/src/selection/node.js
function node_default() {
  for (var groups2 = this._groups, j = 0, m2 = groups2.length; j < m2; ++j) {
    for (var group2 = groups2[j], i2 = 0, n = group2.length; i2 < n; ++i2) {
      var node = group2[i2];
      if (node) return node;
    }
  }
  return null;
}

// node_modules/d3-selection/src/selection/size.js
function size_default() {
  let size = 0;
  for (const node of this) ++size;
  return size;
}

// node_modules/d3-selection/src/selection/empty.js
function empty_default() {
  return !this.node();
}

// node_modules/d3-selection/src/selection/each.js
function each_default2(callback) {
  for (var groups2 = this._groups, j = 0, m2 = groups2.length; j < m2; ++j) {
    for (var group2 = groups2[j], i2 = 0, n = group2.length, node; i2 < n; ++i2) {
      if (node = group2[i2]) callback.call(node, node.__data__, i2, group2);
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/attr.js
function attrRemove(name3) {
  return function() {
    this.removeAttribute(name3);
  };
}
function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant(name3, value) {
  return function() {
    this.setAttribute(name3, value);
  };
}
function attrConstantNS(fullname, value) {
  return function() {
    this.setAttributeNS(fullname.space, fullname.local, value);
  };
}
function attrFunction(name3, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttribute(name3);
    else this.setAttribute(name3, v);
  };
}
function attrFunctionNS(fullname, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
    else this.setAttributeNS(fullname.space, fullname.local, v);
  };
}
function attr_default(name3, value) {
  var fullname = namespace_default(name3);
  if (arguments.length < 2) {
    var node = this.node();
    return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
  }
  return this.each((value == null ? fullname.local ? attrRemoveNS : attrRemove : typeof value === "function" ? fullname.local ? attrFunctionNS : attrFunction : fullname.local ? attrConstantNS : attrConstant)(fullname, value));
}

// node_modules/d3-selection/src/window.js
function window_default(node) {
  return node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView;
}

// node_modules/d3-selection/src/selection/style.js
function styleRemove(name3) {
  return function() {
    this.style.removeProperty(name3);
  };
}
function styleConstant(name3, value, priority) {
  return function() {
    this.style.setProperty(name3, value, priority);
  };
}
function styleFunction(name3, value, priority) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.style.removeProperty(name3);
    else this.style.setProperty(name3, v, priority);
  };
}
function style_default(name3, value, priority) {
  return arguments.length > 1 ? this.each((value == null ? styleRemove : typeof value === "function" ? styleFunction : styleConstant)(name3, value, priority == null ? "" : priority)) : styleValue(this.node(), name3);
}
function styleValue(node, name3) {
  return node.style.getPropertyValue(name3) || window_default(node).getComputedStyle(node, null).getPropertyValue(name3);
}

// node_modules/d3-selection/src/selection/property.js
function propertyRemove(name3) {
  return function() {
    delete this[name3];
  };
}
function propertyConstant(name3, value) {
  return function() {
    this[name3] = value;
  };
}
function propertyFunction(name3, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) delete this[name3];
    else this[name3] = v;
  };
}
function property_default(name3, value) {
  return arguments.length > 1 ? this.each((value == null ? propertyRemove : typeof value === "function" ? propertyFunction : propertyConstant)(name3, value)) : this.node()[name3];
}

// node_modules/d3-selection/src/selection/classed.js
function classArray(string4) {
  return string4.trim().split(/^|\s+/);
}
function classList(node) {
  return node.classList || new ClassList(node);
}
function ClassList(node) {
  this._node = node;
  this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
  add: function(name3) {
    var i2 = this._names.indexOf(name3);
    if (i2 < 0) {
      this._names.push(name3);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  remove: function(name3) {
    var i2 = this._names.indexOf(name3);
    if (i2 >= 0) {
      this._names.splice(i2, 1);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  contains: function(name3) {
    return this._names.indexOf(name3) >= 0;
  }
};
function classedAdd(node, names) {
  var list = classList(node), i2 = -1, n = names.length;
  while (++i2 < n) list.add(names[i2]);
}
function classedRemove(node, names) {
  var list = classList(node), i2 = -1, n = names.length;
  while (++i2 < n) list.remove(names[i2]);
}
function classedTrue(names) {
  return function() {
    classedAdd(this, names);
  };
}
function classedFalse(names) {
  return function() {
    classedRemove(this, names);
  };
}
function classedFunction(names, value) {
  return function() {
    (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  };
}
function classed_default(name3, value) {
  var names = classArray(name3 + "");
  if (arguments.length < 2) {
    var list = classList(this.node()), i2 = -1, n = names.length;
    while (++i2 < n) if (!list.contains(names[i2])) return false;
    return true;
  }
  return this.each((typeof value === "function" ? classedFunction : value ? classedTrue : classedFalse)(names, value));
}

// node_modules/d3-selection/src/selection/text.js
function textRemove() {
  this.textContent = "";
}
function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.textContent = v == null ? "" : v;
  };
}
function text_default(value) {
  return arguments.length ? this.each(value == null ? textRemove : (typeof value === "function" ? textFunction : textConstant)(value)) : this.node().textContent;
}

// node_modules/d3-selection/src/selection/html.js
function htmlRemove() {
  this.innerHTML = "";
}
function htmlConstant(value) {
  return function() {
    this.innerHTML = value;
  };
}
function htmlFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.innerHTML = v == null ? "" : v;
  };
}
function html_default(value) {
  return arguments.length ? this.each(value == null ? htmlRemove : (typeof value === "function" ? htmlFunction : htmlConstant)(value)) : this.node().innerHTML;
}

// node_modules/d3-selection/src/selection/raise.js
function raise() {
  if (this.nextSibling) this.parentNode.appendChild(this);
}
function raise_default() {
  return this.each(raise);
}

// node_modules/d3-selection/src/selection/lower.js
function lower() {
  if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function lower_default() {
  return this.each(lower);
}

// node_modules/d3-selection/src/selection/append.js
function append_default(name3) {
  var create = typeof name3 === "function" ? name3 : creator_default(name3);
  return this.select(function() {
    return this.appendChild(create.apply(this, arguments));
  });
}

// node_modules/d3-selection/src/selection/insert.js
function constantNull() {
  return null;
}
function insert_default(name3, before) {
  var create = typeof name3 === "function" ? name3 : creator_default(name3), select = before == null ? constantNull : typeof before === "function" ? before : selector_default(before);
  return this.select(function() {
    return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
  });
}

// node_modules/d3-selection/src/selection/remove.js
function remove2() {
  var parent2 = this.parentNode;
  if (parent2) parent2.removeChild(this);
}
function remove_default() {
  return this.each(remove2);
}

// node_modules/d3-selection/src/selection/clone.js
function selection_cloneShallow() {
  var clone = this.cloneNode(false), parent2 = this.parentNode;
  return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
}
function selection_cloneDeep() {
  var clone = this.cloneNode(true), parent2 = this.parentNode;
  return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
}
function clone_default(deep) {
  return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
}

// node_modules/d3-selection/src/selection/datum.js
function datum_default(value) {
  return arguments.length ? this.property("__data__", value) : this.node().__data__;
}

// node_modules/d3-selection/src/selection/on.js
function contextListener(listener) {
  return function(event2) {
    listener.call(this, event2, this.__data__);
  };
}
function parseTypenames(typenames) {
  return typenames.trim().split(/^|\s+/).map(function(t4) {
    var name3 = "", i2 = t4.indexOf(".");
    if (i2 >= 0) name3 = t4.slice(i2 + 1), t4 = t4.slice(0, i2);
    return { type: t4, name: name3 };
  });
}
function onRemove(typename) {
  return function() {
    var on2 = this.__on;
    if (!on2) return;
    for (var j = 0, i2 = -1, m2 = on2.length, o; j < m2; ++j) {
      if (o = on2[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
      } else {
        on2[++i2] = o;
      }
    }
    if (++i2) on2.length = i2;
    else delete this.__on;
  };
}
function onAdd(typename, value, options4) {
  return function() {
    var on2 = this.__on, o, listener = contextListener(value);
    if (on2) for (var j = 0, m2 = on2.length; j < m2; ++j) {
      if ((o = on2[j]).type === typename.type && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
        this.addEventListener(o.type, o.listener = listener, o.options = options4);
        o.value = value;
        return;
      }
    }
    this.addEventListener(typename.type, listener, options4);
    o = { type: typename.type, name: typename.name, value, listener, options: options4 };
    if (!on2) this.__on = [o];
    else on2.push(o);
  };
}
function on_default(typename, value, options4) {
  var typenames = parseTypenames(typename + ""), i2, n = typenames.length, t4;
  if (arguments.length < 2) {
    var on2 = this.node().__on;
    if (on2) for (var j = 0, m2 = on2.length, o; j < m2; ++j) {
      for (i2 = 0, o = on2[j]; i2 < n; ++i2) {
        if ((t4 = typenames[i2]).type === o.type && t4.name === o.name) {
          return o.value;
        }
      }
    }
    return;
  }
  on2 = value ? onAdd : onRemove;
  for (i2 = 0; i2 < n; ++i2) this.each(on2(typenames[i2], value, options4));
  return this;
}

// node_modules/d3-selection/src/selection/dispatch.js
function dispatchEvent(node, type, params) {
  var window2 = window_default(node), event2 = window2.CustomEvent;
  if (typeof event2 === "function") {
    event2 = new event2(type, params);
  } else {
    event2 = window2.document.createEvent("Event");
    if (params) event2.initEvent(type, params.bubbles, params.cancelable), event2.detail = params.detail;
    else event2.initEvent(type, false, false);
  }
  node.dispatchEvent(event2);
}
function dispatchConstant(type, params) {
  return function() {
    return dispatchEvent(this, type, params);
  };
}
function dispatchFunction(type, params) {
  return function() {
    return dispatchEvent(this, type, params.apply(this, arguments));
  };
}
function dispatch_default(type, params) {
  return this.each((typeof params === "function" ? dispatchFunction : dispatchConstant)(type, params));
}

// node_modules/d3-selection/src/selection/iterator.js
function* iterator_default2() {
  for (var groups2 = this._groups, j = 0, m2 = groups2.length; j < m2; ++j) {
    for (var group2 = groups2[j], i2 = 0, n = group2.length, node; i2 < n; ++i2) {
      if (node = group2[i2]) yield node;
    }
  }
}

// node_modules/d3-selection/src/selection/index.js
var root3 = [null];
function Selection(groups2, parents) {
  this._groups = groups2;
  this._parents = parents;
}
function selection() {
  return new Selection([[document.documentElement]], root3);
}
function selection_selection() {
  return this;
}
Selection.prototype = selection.prototype = {
  constructor: Selection,
  select: select_default,
  selectAll: selectAll_default,
  selectChild: selectChild_default,
  selectChildren: selectChildren_default,
  filter: filter_default,
  data: data_default,
  enter: enter_default,
  exit: exit_default,
  join: join_default,
  merge: merge_default,
  selection: selection_selection,
  order: order_default,
  sort: sort_default2,
  call: call_default,
  nodes: nodes_default,
  node: node_default,
  size: size_default,
  empty: empty_default,
  each: each_default2,
  attr: attr_default,
  style: style_default,
  property: property_default,
  classed: classed_default,
  text: text_default,
  html: html_default,
  raise: raise_default,
  lower: lower_default,
  append: append_default,
  insert: insert_default,
  remove: remove_default,
  clone: clone_default,
  datum: datum_default,
  on: on_default,
  dispatch: dispatch_default,
  [Symbol.iterator]: iterator_default2
};

// node_modules/d3-selection/src/select.js
function select_default2(selector) {
  return typeof selector === "string" ? new Selection([[document.querySelector(selector)]], [document.documentElement]) : new Selection([[selector]], root3);
}

// node_modules/d3-selection/src/sourceEvent.js
function sourceEvent_default(event2) {
  let sourceEvent;
  while (sourceEvent = event2.sourceEvent) event2 = sourceEvent;
  return event2;
}

// node_modules/d3-selection/src/pointer.js
function pointer_default(event2, node) {
  event2 = sourceEvent_default(event2);
  if (node === void 0) node = event2.currentTarget;
  if (node) {
    var svg2 = node.ownerSVGElement || node;
    if (svg2.createSVGPoint) {
      var point2 = svg2.createSVGPoint();
      point2.x = event2.clientX, point2.y = event2.clientY;
      point2 = point2.matrixTransform(node.getScreenCTM().inverse());
      return [point2.x, point2.y];
    }
    if (node.getBoundingClientRect) {
      var rect = node.getBoundingClientRect();
      return [event2.clientX - rect.left - node.clientLeft, event2.clientY - rect.top - node.clientTop];
    }
  }
  return [event2.pageX, event2.pageY];
}

// src/charts/tooltip.ts
var tooltip = /* @__PURE__ */ (() => {
  let value = null;
  return () => {
    if (value === null) {
      value = document.createElement("div");
      value.className = "tooltip";
      document.body.appendChild(value);
    }
    return value;
  };
})();
var hide = () => {
  const t4 = tooltip();
  t4.style.opacity = "0";
};
var domHelpers = {
  /** Create a <br> element. */
  br: () => document.createElement("br"),
  /** Create a <em> element with the given content. */
  em: (content2) => {
    const em = document.createElement("em");
    em.textContent = content2;
    return em;
  },
  /** Create a text node for the given text. */
  t: (text2) => document.createTextNode(text2),
  /** Create a <pre> element with the given content. */
  pre: (content2) => {
    const pre = document.createElement("pre");
    pre.textContent = content2;
    return pre;
  }
};
var followingTooltip = (node, text2) => {
  let getter = text2;
  function followMouse(event2) {
    const t4 = tooltip();
    t4.style.opacity = "1";
    t4.style.left = `${event2.pageX.toString()}px`;
    t4.style.top = `${(event2.pageY - 15).toString()}px`;
  }
  node.addEventListener("mouseenter", () => {
    const t4 = tooltip();
    t4.replaceChildren(...getter());
  });
  node.addEventListener("mousemove", followMouse);
  node.addEventListener("mouseleave", hide);
  return {
    destroy: hide,
    update(t4) {
      getter = t4;
    }
  };
};
var positionedTooltip = (node, find3) => {
  function mousemove2(event2) {
    const [xPointer, yPointer] = pointer_default(event2);
    const res2 = find3(xPointer, yPointer);
    const matrix = node.getScreenCTM();
    if (res2 && matrix) {
      const [x2, y2, content2] = res2;
      const t4 = tooltip();
      t4.style.opacity = "1";
      t4.replaceChildren(...content2);
      t4.style.left = `${(window.scrollX + x2 + matrix.e).toString()}px`;
      t4.style.top = `${(window.scrollY + y2 + matrix.f - 15).toString()}px`;
    } else {
      hide();
    }
  }
  node.addEventListener("mousemove", mousemove2);
  node.addEventListener("mouseleave", hide);
  return {
    destroy: hide
  };
};

// src/charts/bar.ts
var bar_validator = array(
  object({
    date,
    budgets: record(number),
    balance: record(number),
    account_balances: record(record(number))
  })
);
var BarChart = class {
  constructor(name3, currencies2, bar_groups) {
    this.name = name3;
    this.currencies = currencies2;
    this.bar_groups = bar_groups;
    this.accounts = Array.from(
      new Set(bar_groups.map((d) => Object.keys(d.account_balances)).flat(2))
    ).sort();
    this.stacks = currencies2.map((currency) => [
      currency,
      stack_default().keys(this.accounts).value((d, account2) => d.account_balances[account2]?.[currency] ?? 0).offset(diverging_default)(bar_groups).filter((b) => b[0] !== b[1] && !Number.isNaN(b[1]))
    ]);
  }
  type = "barchart";
  /** The accounts that occur in some bar.  */
  accounts;
  /** For each currency, the stacks (one series per account) */
  stacks;
  filter(hidden_names) {
    const hidden_names_set = new Set(hidden_names);
    const currencies2 = new Set(
      this.currencies.filter((c) => !hidden_names_set.has(c))
    );
    const bar_groups = this.bar_groups.map((b) => ({
      ...b,
      values: b.values.filter((v) => currencies2.has(v.currency))
    }));
    const stacks = this.stacks.filter((s) => currencies2.has(s[0]));
    return { currencies: [...currencies2], bar_groups, stacks };
  }
  /** Whether this chart contains any stacks (or is just a single account). */
  get hasStackedData() {
    return this.accounts.length > 1;
  }
  /** The tooltip for a hovered account in the stacked bar chart. */
  tooltipTextAccount(c, d, account2, $chartToggledCurrencies) {
    const content2 = [];
    content2.push(domHelpers.em(account2));
    d.values.forEach(({ currency }) => {
      if (!$chartToggledCurrencies.includes(currency)) {
        const value = d.account_balances[account2]?.[currency] ?? 0;
        content2.push(domHelpers.t(c.amount(value, currency)));
        content2.push(domHelpers.br());
      }
    });
    content2.push(domHelpers.em(d.label));
    return content2;
  }
  /** The tooltip for a hovered bar group in the bar chart. */
  tooltipText(c, d) {
    const content2 = [];
    d.values.forEach((a) => {
      content2.push(
        domHelpers.t(
          a.budget ? `${c.amount(a.value, a.currency)} / ${c.amount(
            a.budget,
            a.currency
          )}` : c.amount(a.value, a.currency)
        )
      );
      content2.push(domHelpers.br());
    });
    content2.push(domHelpers.em(d.label));
    return content2;
  }
};
function currencies_to_show(data, $chartContext) {
  const counts = rollup(
    data.flatMap((interval2) => [
      ...Object.keys(interval2.budgets),
      ...Object.keys(interval2.balance)
    ]),
    (v) => v.length,
    (r2) => r2
  );
  const to_show = $chartContext.currencies.filter((c) => counts.delete(c));
  to_show.push(
    ...[...counts].sort((a, b) => b[1] - a[1]).map((i2) => i2[0]).slice(0, Math.max(to_show.length, 5) - to_show.length)
  );
  return to_show;
}
function bar(label, json, $chartContext) {
  return bar_validator(json).map((parsedData) => {
    const currencies2 = currencies_to_show(parsedData, $chartContext);
    const bar_groups = parsedData.map((interval2) => ({
      values: currencies2.map((currency) => ({
        currency,
        value: interval2.balance[currency] ?? 0,
        budget: interval2.budgets[currency] ?? 0
      })),
      date: interval2.date,
      label: $chartContext.dateFormat(interval2.date),
      account_balances: interval2.account_balances
    }));
    return new BarChart(label, currencies2, bar_groups);
  });
}

// src/charts/line.ts
var LineChart = class {
  constructor(name3, data, tooltipText) {
    this.name = name3;
    this.data = data;
    this.tooltipText = tooltipText;
    this.data = sort(data, (d) => -d.values.length);
    this.series_names = this.data.map((series) => series.name);
  }
  type = "linechart";
  series_names;
  /** Filter the data of this chart, excluding some series. */
  filter(hidden_names) {
    const hidden_names_set = new Set(hidden_names);
    return this.data.filter((series) => !hidden_names_set.has(series.name));
  }
};
var balances_validator = array(object({ date, balance: record(number) }));
function balances_from_parsed_data(label, parsed_data) {
  const groups2 = /* @__PURE__ */ new Map();
  for (const { date: date_val, balance } of parsed_data) {
    Object.entries(balance).forEach(([currency, value]) => {
      const group2 = groups2.get(currency);
      const datum2 = { date: date_val, value, name: currency };
      if (group2) {
        group2.push(datum2);
      } else {
        groups2.set(currency, [datum2]);
      }
    });
  }
  const data = [...groups2.entries()].map(([name3, values]) => ({
    name: name3,
    values
  }));
  return new LineChart(label, data, (c, d) => [
    domHelpers.t(c.amount(d.value, d.name)),
    domHelpers.em(day(d.date))
  ]);
}
function balances(label, json) {
  return balances_validator(json).map(
    (parsedData) => balances_from_parsed_data(label, parsedData)
  );
}

// src/charts/scatterplot.ts
var ScatterPlot = class {
  constructor(name3, data) {
    this.name = name3;
    this.data = data;
  }
  type = "scatterplot";
};
var scatterplot_validator = array(
  object({ type: string, date, description: string })
);
function scatterplot(label, json) {
  return scatterplot_validator(json).map(
    (value) => new ScatterPlot(label, value)
  );
}

// src/charts/index.ts
var parsers = {
  balances,
  bar,
  hierarchy: hierarchy2,
  scatterplot
};
var chart_data_validator = array(
  object({ label: string, type: string, data: unknown })
);
var ChartValidationError = class extends Error {
  constructor(type, cause) {
    super(`Parsing of data for ${type} chart failed.`, { cause });
  }
};
var UnknownChartTypeError = class extends Error {
  constructor(type) {
    super(`Unknown chart type ${type}`);
  }
};
function parseChartData(data, $chartContext) {
  return chart_data_validator(data).and_then(
    (chartData) => collect(
      chartData.map(({ type, label, data: data2 }) => {
        const parser = parsers[type];
        return parser ? parser(label, data2, $chartContext).map_err(
          (error2) => new ChartValidationError(type, error2)
        ) : err2(new UnknownChartTypeError(type));
      })
    )
  );
}

// node_modules/d3-axis/src/identity.js
function identity_default2(x2) {
  return x2;
}

// node_modules/d3-axis/src/axis.js
var top2 = 1;
var right = 2;
var bottom = 3;
var left = 4;
var epsilon3 = 1e-6;
function translateX(x2) {
  return "translate(" + x2 + ",0)";
}
function translateY(y2) {
  return "translate(0," + y2 + ")";
}
function number4(scale) {
  return (d) => +scale(d);
}
function center(scale, offset) {
  offset = Math.max(0, scale.bandwidth() - offset * 2) / 2;
  if (scale.round()) offset = Math.round(offset);
  return (d) => +scale(d) + offset;
}
function entering() {
  return !this.__axis;
}
function axis(orient, scale) {
  var tickArguments = [], tickValues = null, tickFormat2 = null, tickSizeInner = 6, tickSizeOuter = 6, tickPadding = 3, offset = typeof window !== "undefined" && window.devicePixelRatio > 1 ? 0 : 0.5, k = orient === top2 || orient === left ? -1 : 1, x2 = orient === left || orient === right ? "x" : "y", transform = orient === top2 || orient === bottom ? translateX : translateY;
  function axis2(context2) {
    var values = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain() : tickValues, format3 = tickFormat2 == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity_default2 : tickFormat2, spacing = Math.max(tickSizeInner, 0) + tickPadding, range2 = scale.range(), range0 = +range2[0] + offset, range1 = +range2[range2.length - 1] + offset, position = (scale.bandwidth ? center : number4)(scale.copy(), offset), selection2 = context2.selection ? context2.selection() : context2, path2 = selection2.selectAll(".domain").data([null]), tick2 = selection2.selectAll(".tick").data(values, scale).order(), tickExit = tick2.exit(), tickEnter = tick2.enter().append("g").attr("class", "tick"), line = tick2.select("line"), text2 = tick2.select("text");
    path2 = path2.merge(path2.enter().insert("path", ".tick").attr("class", "domain").attr("stroke", "currentColor"));
    tick2 = tick2.merge(tickEnter);
    line = line.merge(tickEnter.append("line").attr("stroke", "currentColor").attr(x2 + "2", k * tickSizeInner));
    text2 = text2.merge(tickEnter.append("text").attr("fill", "currentColor").attr(x2, k * spacing).attr("dy", orient === top2 ? "0em" : orient === bottom ? "0.71em" : "0.32em"));
    if (context2 !== selection2) {
      path2 = path2.transition(context2);
      tick2 = tick2.transition(context2);
      line = line.transition(context2);
      text2 = text2.transition(context2);
      tickExit = tickExit.transition(context2).attr("opacity", epsilon3).attr("transform", function(d) {
        return isFinite(d = position(d)) ? transform(d + offset) : this.getAttribute("transform");
      });
      tickEnter.attr("opacity", epsilon3).attr("transform", function(d) {
        var p = this.parentNode.__axis;
        return transform((p && isFinite(p = p(d)) ? p : position(d)) + offset);
      });
    }
    tickExit.remove();
    path2.attr("d", orient === left || orient === right ? tickSizeOuter ? "M" + k * tickSizeOuter + "," + range0 + "H" + offset + "V" + range1 + "H" + k * tickSizeOuter : "M" + offset + "," + range0 + "V" + range1 : tickSizeOuter ? "M" + range0 + "," + k * tickSizeOuter + "V" + offset + "H" + range1 + "V" + k * tickSizeOuter : "M" + range0 + "," + offset + "H" + range1);
    tick2.attr("opacity", 1).attr("transform", function(d) {
      return transform(position(d) + offset);
    });
    line.attr(x2 + "2", k * tickSizeInner);
    text2.attr(x2, k * spacing).text(format3);
    selection2.filter(entering).attr("fill", "none").attr("font-size", 10).attr("font-family", "sans-serif").attr("text-anchor", orient === right ? "start" : orient === left ? "end" : "middle");
    selection2.each(function() {
      this.__axis = position;
    });
  }
  axis2.scale = function(_2) {
    return arguments.length ? (scale = _2, axis2) : scale;
  };
  axis2.ticks = function() {
    return tickArguments = Array.from(arguments), axis2;
  };
  axis2.tickArguments = function(_2) {
    return arguments.length ? (tickArguments = _2 == null ? [] : Array.from(_2), axis2) : tickArguments.slice();
  };
  axis2.tickValues = function(_2) {
    return arguments.length ? (tickValues = _2 == null ? null : Array.from(_2), axis2) : tickValues && tickValues.slice();
  };
  axis2.tickFormat = function(_2) {
    return arguments.length ? (tickFormat2 = _2, axis2) : tickFormat2;
  };
  axis2.tickSize = function(_2) {
    return arguments.length ? (tickSizeInner = tickSizeOuter = +_2, axis2) : tickSizeInner;
  };
  axis2.tickSizeInner = function(_2) {
    return arguments.length ? (tickSizeInner = +_2, axis2) : tickSizeInner;
  };
  axis2.tickSizeOuter = function(_2) {
    return arguments.length ? (tickSizeOuter = +_2, axis2) : tickSizeOuter;
  };
  axis2.tickPadding = function(_2) {
    return arguments.length ? (tickPadding = +_2, axis2) : tickPadding;
  };
  axis2.offset = function(_2) {
    return arguments.length ? (offset = +_2, axis2) : offset;
  };
  return axis2;
}
function axisBottom(scale) {
  return axis(bottom, scale);
}
function axisLeft(scale) {
  return axis(left, scale);
}

// node_modules/d3-scale/src/init.js
function initRange(domain, range2) {
  switch (arguments.length) {
    case 0:
      break;
    case 1:
      this.range(domain);
      break;
    default:
      this.range(range2).domain(domain);
      break;
  }
  return this;
}

// node_modules/d3-scale/src/ordinal.js
var implicit = Symbol("implicit");
function ordinal() {
  var index3 = new InternMap(), domain = [], range2 = [], unknown2 = implicit;
  function scale(d) {
    let i2 = index3.get(d);
    if (i2 === void 0) {
      if (unknown2 !== implicit) return unknown2;
      index3.set(d, i2 = domain.push(d) - 1);
    }
    return range2[i2 % range2.length];
  }
  scale.domain = function(_2) {
    if (!arguments.length) return domain.slice();
    domain = [], index3 = new InternMap();
    for (const value of _2) {
      if (index3.has(value)) continue;
      index3.set(value, domain.push(value) - 1);
    }
    return scale;
  };
  scale.range = function(_2) {
    return arguments.length ? (range2 = Array.from(_2), scale) : range2.slice();
  };
  scale.unknown = function(_2) {
    return arguments.length ? (unknown2 = _2, scale) : unknown2;
  };
  scale.copy = function() {
    return ordinal(domain, range2).unknown(unknown2);
  };
  initRange.apply(scale, arguments);
  return scale;
}

// node_modules/d3-scale/src/band.js
function band() {
  var scale = ordinal().unknown(void 0), domain = scale.domain, ordinalRange = scale.range, r0 = 0, r1 = 1, step, bandwidth, round = false, paddingInner = 0, paddingOuter = 0, align = 0.5;
  delete scale.unknown;
  function rescale() {
    var n = domain().length, reverse = r1 < r0, start2 = reverse ? r1 : r0, stop2 = reverse ? r0 : r1;
    step = (stop2 - start2) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round) step = Math.floor(step);
    start2 += (stop2 - start2 - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round) start2 = Math.round(start2), bandwidth = Math.round(bandwidth);
    var values = range(n).map(function(i2) {
      return start2 + step * i2;
    });
    return ordinalRange(reverse ? values.reverse() : values);
  }
  scale.domain = function(_2) {
    return arguments.length ? (domain(_2), rescale()) : domain();
  };
  scale.range = function(_2) {
    return arguments.length ? ([r0, r1] = _2, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
  };
  scale.rangeRound = function(_2) {
    return [r0, r1] = _2, r0 = +r0, r1 = +r1, round = true, rescale();
  };
  scale.bandwidth = function() {
    return bandwidth;
  };
  scale.step = function() {
    return step;
  };
  scale.round = function(_2) {
    return arguments.length ? (round = !!_2, rescale()) : round;
  };
  scale.padding = function(_2) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_2), rescale()) : paddingInner;
  };
  scale.paddingInner = function(_2) {
    return arguments.length ? (paddingInner = Math.min(1, _2), rescale()) : paddingInner;
  };
  scale.paddingOuter = function(_2) {
    return arguments.length ? (paddingOuter = +_2, rescale()) : paddingOuter;
  };
  scale.align = function(_2) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _2)), rescale()) : align;
  };
  scale.copy = function() {
    return band(domain(), [r0, r1]).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
  };
  return initRange.apply(rescale(), arguments);
}
function pointish(scale) {
  var copy2 = scale.copy;
  scale.padding = scale.paddingOuter;
  delete scale.paddingInner;
  delete scale.paddingOuter;
  scale.copy = function() {
    return pointish(copy2());
  };
  return scale;
}
function point() {
  return pointish(band.apply(null, arguments).paddingInner(1));
}

// node_modules/d3-color/src/define.js
function define_default(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}
function extend(parent2, definition) {
  var prototype = Object.create(parent2.prototype);
  for (var key2 in definition) prototype[key2] = definition[key2];
  return prototype;
}

// node_modules/d3-color/src/color.js
function Color() {
}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex = /^#([0-9a-f]{3,8})$/;
var reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`);
var reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`);
var reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`);
var reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`);
var reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`);
var reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
var named = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
define_default(Color, color, {
  copy(channels) {
    return Object.assign(new this.constructor(), this, channels);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: color_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: color_formatHex,
  formatHex8: color_formatHex8,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});
function color_formatHex() {
  return this.rgb().formatHex();
}
function color_formatHex8() {
  return this.rgb().formatHex8();
}
function color_formatHsl() {
  return hslConvert(this).formatHsl();
}
function color_formatRgb() {
  return this.rgb().formatRgb();
}
function color(format3) {
  var m2, l;
  format3 = (format3 + "").trim().toLowerCase();
  return (m2 = reHex.exec(format3)) ? (l = m2[1].length, m2 = parseInt(m2[1], 16), l === 6 ? rgbn(m2) : l === 3 ? new Rgb(m2 >> 8 & 15 | m2 >> 4 & 240, m2 >> 4 & 15 | m2 & 240, (m2 & 15) << 4 | m2 & 15, 1) : l === 8 ? rgba(m2 >> 24 & 255, m2 >> 16 & 255, m2 >> 8 & 255, (m2 & 255) / 255) : l === 4 ? rgba(m2 >> 12 & 15 | m2 >> 8 & 240, m2 >> 8 & 15 | m2 >> 4 & 240, m2 >> 4 & 15 | m2 & 240, ((m2 & 15) << 4 | m2 & 15) / 255) : null) : (m2 = reRgbInteger.exec(format3)) ? new Rgb(m2[1], m2[2], m2[3], 1) : (m2 = reRgbPercent.exec(format3)) ? new Rgb(m2[1] * 255 / 100, m2[2] * 255 / 100, m2[3] * 255 / 100, 1) : (m2 = reRgbaInteger.exec(format3)) ? rgba(m2[1], m2[2], m2[3], m2[4]) : (m2 = reRgbaPercent.exec(format3)) ? rgba(m2[1] * 255 / 100, m2[2] * 255 / 100, m2[3] * 255 / 100, m2[4]) : (m2 = reHslPercent.exec(format3)) ? hsla(m2[1], m2[2] / 100, m2[3] / 100, 1) : (m2 = reHslaPercent.exec(format3)) ? hsla(m2[1], m2[2] / 100, m2[3] / 100, m2[4]) : named.hasOwnProperty(format3) ? rgbn(named[format3]) : format3 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n) {
  return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
}
function rgba(r2, g, b, a) {
  if (a <= 0) r2 = g = b = NaN;
  return new Rgb(r2, g, b, a);
}
function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb();
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r2, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r2) : new Rgb(r2, g, b, opacity == null ? 1 : opacity);
}
function Rgb(r2, g, b, opacity) {
  this.r = +r2;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}
define_default(Rgb, rgb, extend(Color, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
  },
  displayable() {
    return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: rgb_formatHex,
  formatHex8: rgb_formatHex8,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));
function rgb_formatHex() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
}
function rgb_formatHex8() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function rgb_formatRgb() {
  const a = clampa(this.opacity);
  return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
}
function clampa(opacity) {
  return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}
function clampi(value) {
  return Math.max(0, Math.min(255, Math.round(value) || 0));
}
function hex(value) {
  value = clampi(value);
  return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}
function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl();
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r2 = o.r / 255, g = o.g / 255, b = o.b / 255, min3 = Math.min(r2, g, b), max3 = Math.max(r2, g, b), h = NaN, s = max3 - min3, l = (max3 + min3) / 2;
  if (s) {
    if (r2 === max3) h = (g - b) / s + (g < b) * 6;
    else if (g === max3) h = (b - r2) / s + 2;
    else h = (r2 - g) / s + 4;
    s /= l < 0.5 ? max3 + min3 : 2 - max3 - min3;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}
function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}
function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}
define_default(Hsl, hsl, extend(Color, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb() {
    var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  clamp() {
    return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl() {
    const a = clampa(this.opacity);
    return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
  }
}));
function clamph(value) {
  value = (value || 0) % 360;
  return value < 0 ? value + 360 : value;
}
function clampt(value) {
  return Math.max(0, Math.min(1, value || 0));
}
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
}

// node_modules/d3-color/src/math.js
var radians = Math.PI / 180;
var degrees = 180 / Math.PI;

// node_modules/d3-color/src/lab.js
var K = 18;
var Xn = 0.96422;
var Yn = 1;
var Zn = 0.82521;
var t02 = 4 / 29;
var t12 = 6 / 29;
var t2 = 3 * t12 * t12;
var t3 = t12 * t12 * t12;
function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) return hcl2lab(o);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r2 = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y2 = xyz2lab((0.2225045 * r2 + 0.7168786 * g + 0.0606169 * b) / Yn), x2, z;
  if (r2 === g && g === b) x2 = z = y2;
  else {
    x2 = xyz2lab((0.4360747 * r2 + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r2 + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y2 - 16, 500 * (x2 - y2), 200 * (y2 - z), o.opacity);
}
function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}
function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}
define_default(Lab, lab, extend(Color, {
  brighter(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb() {
    var y2 = (this.l + 16) / 116, x2 = isNaN(this.a) ? y2 : y2 + this.a / 500, z = isNaN(this.b) ? y2 : y2 - this.b / 200;
    x2 = Xn * lab2xyz(x2);
    y2 = Yn * lab2xyz(y2);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb(3.1338561 * x2 - 1.6168667 * y2 - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x2 + 1.9161415 * y2 + 0.033454 * z),
      lrgb2rgb(0.0719453 * x2 - 0.2289914 * y2 + 1.4052427 * z),
      this.opacity
    );
  }
}));
function xyz2lab(t4) {
  return t4 > t3 ? Math.pow(t4, 1 / 3) : t4 / t2 + t02;
}
function lab2xyz(t4) {
  return t4 > t12 ? t4 * t4 * t4 : t2 * (t4 - t02);
}
function lrgb2rgb(x2) {
  return 255 * (x2 <= 31308e-7 ? 12.92 * x2 : 1.055 * Math.pow(x2, 1 / 2.4) - 0.055);
}
function rgb2lrgb(x2) {
  return (x2 /= 255) <= 0.04045 ? x2 / 12.92 : Math.pow((x2 + 0.055) / 1.055, 2.4);
}
function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * degrees;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}
function hcl2lab(o) {
  if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
  var h = o.h * radians;
  return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
define_default(Hcl, hcl, extend(Color, {
  brighter(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb() {
    return hcl2lab(this).rgb();
  }
}));

// node_modules/d3-interpolate/src/basis.js
function basis(t13, v0, v1, v2, v3) {
  var t22 = t13 * t13, t32 = t22 * t13;
  return ((1 - 3 * t13 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t13 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6;
}
function basis_default(values) {
  var n = values.length - 1;
  return function(t4) {
    var i2 = t4 <= 0 ? t4 = 0 : t4 >= 1 ? (t4 = 1, n - 1) : Math.floor(t4 * n), v1 = values[i2], v2 = values[i2 + 1], v0 = i2 > 0 ? values[i2 - 1] : 2 * v1 - v2, v3 = i2 < n - 1 ? values[i2 + 2] : 2 * v2 - v1;
    return basis((t4 - i2 / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/basisClosed.js
function basisClosed_default(values) {
  var n = values.length;
  return function(t4) {
    var i2 = Math.floor(((t4 %= 1) < 0 ? ++t4 : t4) * n), v0 = values[(i2 + n - 1) % n], v1 = values[i2 % n], v2 = values[(i2 + 1) % n], v3 = values[(i2 + 2) % n];
    return basis((t4 - i2 / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/constant.js
var constant_default4 = (x2) => () => x2;

// node_modules/d3-interpolate/src/color.js
function linear(a, d) {
  return function(t4) {
    return a + t4 * d;
  };
}
function exponential(a, b, y2) {
  return a = Math.pow(a, y2), b = Math.pow(b, y2) - a, y2 = 1 / y2, function(t4) {
    return Math.pow(a + t4 * b, y2);
  };
}
function gamma(y2) {
  return (y2 = +y2) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y2) : constant_default4(isNaN(a) ? b : a);
  };
}
function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant_default4(isNaN(a) ? b : a);
}

// node_modules/d3-interpolate/src/rgb.js
var rgb_default = function rgbGamma(y2) {
  var color2 = gamma(y2);
  function rgb2(start2, end) {
    var r2 = color2((start2 = rgb(start2)).r, (end = rgb(end)).r), g = color2(start2.g, end.g), b = color2(start2.b, end.b), opacity = nogamma(start2.opacity, end.opacity);
    return function(t4) {
      start2.r = r2(t4);
      start2.g = g(t4);
      start2.b = b(t4);
      start2.opacity = opacity(t4);
      return start2 + "";
    };
  }
  rgb2.gamma = rgbGamma;
  return rgb2;
}(1);
function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length, r2 = new Array(n), g = new Array(n), b = new Array(n), i2, color2;
    for (i2 = 0; i2 < n; ++i2) {
      color2 = rgb(colors[i2]);
      r2[i2] = color2.r || 0;
      g[i2] = color2.g || 0;
      b[i2] = color2.b || 0;
    }
    r2 = spline(r2);
    g = spline(g);
    b = spline(b);
    color2.opacity = 1;
    return function(t4) {
      color2.r = r2(t4);
      color2.g = g(t4);
      color2.b = b(t4);
      return color2 + "";
    };
  };
}
var rgbBasis = rgbSpline(basis_default);
var rgbBasisClosed = rgbSpline(basisClosed_default);

// node_modules/d3-interpolate/src/numberArray.js
function numberArray_default(a, b) {
  if (!b) b = [];
  var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i2;
  return function(t4) {
    for (i2 = 0; i2 < n; ++i2) c[i2] = a[i2] * (1 - t4) + b[i2] * t4;
    return c;
  };
}
function isNumberArray(x2) {
  return ArrayBuffer.isView(x2) && !(x2 instanceof DataView);
}

// node_modules/d3-interpolate/src/array.js
function genericArray(a, b) {
  var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x2 = new Array(na), c = new Array(nb), i2;
  for (i2 = 0; i2 < na; ++i2) x2[i2] = value_default(a[i2], b[i2]);
  for (; i2 < nb; ++i2) c[i2] = b[i2];
  return function(t4) {
    for (i2 = 0; i2 < na; ++i2) c[i2] = x2[i2](t4);
    return c;
  };
}

// node_modules/d3-interpolate/src/date.js
function date_default(a, b) {
  var d = /* @__PURE__ */ new Date();
  return a = +a, b = +b, function(t4) {
    return d.setTime(a * (1 - t4) + b * t4), d;
  };
}

// node_modules/d3-interpolate/src/number.js
function number_default(a, b) {
  return a = +a, b = +b, function(t4) {
    return a * (1 - t4) + b * t4;
  };
}

// node_modules/d3-interpolate/src/object.js
function object_default(a, b) {
  var i2 = {}, c = {}, k;
  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};
  for (k in b) {
    if (k in a) {
      i2[k] = value_default(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }
  return function(t4) {
    for (k in i2) c[k] = i2[k](t4);
    return c;
  };
}

// node_modules/d3-interpolate/src/string.js
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var reB = new RegExp(reA.source, "g");
function zero2(b) {
  return function() {
    return b;
  };
}
function one(b) {
  return function(t4) {
    return b(t4) + "";
  };
}
function string_default(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i2 = -1, s = [], q = [];
  a = a + "", b = b + "";
  while ((am = reA.exec(a)) && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) {
      bs = b.slice(bi, bs);
      if (s[i2]) s[i2] += bs;
      else s[++i2] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s[i2]) s[i2] += bm;
      else s[++i2] = bm;
    } else {
      s[++i2] = null;
      q.push({ i: i2, x: number_default(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i2]) s[i2] += bs;
    else s[++i2] = bs;
  }
  return s.length < 2 ? q[0] ? one(q[0].x) : zero2(b) : (b = q.length, function(t4) {
    for (var i3 = 0, o; i3 < b; ++i3) s[(o = q[i3]).i] = o.x(t4);
    return s.join("");
  });
}

// node_modules/d3-interpolate/src/value.js
function value_default(a, b) {
  var t4 = typeof b, c;
  return b == null || t4 === "boolean" ? constant_default4(b) : (t4 === "number" ? number_default : t4 === "string" ? (c = color(b)) ? (b = c, rgb_default) : string_default : b instanceof color ? rgb_default : b instanceof Date ? date_default : isNumberArray(b) ? numberArray_default : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object_default : number_default)(a, b);
}

// node_modules/d3-interpolate/src/round.js
function round_default2(a, b) {
  return a = +a, b = +b, function(t4) {
    return Math.round(a * (1 - t4) + b * t4);
  };
}

// node_modules/d3-scale/src/constant.js
function constants2(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-scale/src/number.js
function number5(x2) {
  return +x2;
}

// node_modules/d3-scale/src/continuous.js
var unit = [0, 1];
function identity2(x2) {
  return x2;
}
function normalize(a, b) {
  return (b -= a = +a) ? function(x2) {
    return (x2 - a) / b;
  } : constants2(isNaN(b) ? NaN : 0.5);
}
function clamper(a, b) {
  var t4;
  if (a > b) t4 = a, a = b, b = t4;
  return function(x2) {
    return Math.max(a, Math.min(b, x2));
  };
}
function bimap(domain, range2, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range2[0], r1 = range2[1];
  if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
  else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x2) {
    return r0(d0(x2));
  };
}
function polymap(domain, range2, interpolate) {
  var j = Math.min(domain.length, range2.length) - 1, d = new Array(j), r2 = new Array(j), i2 = -1;
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range2 = range2.slice().reverse();
  }
  while (++i2 < j) {
    d[i2] = normalize(domain[i2], domain[i2 + 1]);
    r2[i2] = interpolate(range2[i2], range2[i2 + 1]);
  }
  return function(x2) {
    var i3 = bisect_default(domain, x2, 1, j) - 1;
    return r2[i3](d[i3](x2));
  };
}
function copy(source3, target) {
  return target.domain(source3.domain()).range(source3.range()).interpolate(source3.interpolate()).clamp(source3.clamp()).unknown(source3.unknown());
}
function transformer() {
  var domain = unit, range2 = unit, interpolate = value_default, transform, untransform, unknown2, clamp = identity2, piecewise, output, input;
  function rescale() {
    var n = Math.min(domain.length, range2.length);
    if (clamp !== identity2) clamp = clamper(domain[0], domain[n - 1]);
    piecewise = n > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }
  function scale(x2) {
    return x2 == null || isNaN(x2 = +x2) ? unknown2 : (output || (output = piecewise(domain.map(transform), range2, interpolate)))(transform(clamp(x2)));
  }
  scale.invert = function(y2) {
    return clamp(untransform((input || (input = piecewise(range2, domain.map(transform), number_default)))(y2)));
  };
  scale.domain = function(_2) {
    return arguments.length ? (domain = Array.from(_2, number5), rescale()) : domain.slice();
  };
  scale.range = function(_2) {
    return arguments.length ? (range2 = Array.from(_2), rescale()) : range2.slice();
  };
  scale.rangeRound = function(_2) {
    return range2 = Array.from(_2), interpolate = round_default2, rescale();
  };
  scale.clamp = function(_2) {
    return arguments.length ? (clamp = _2 ? true : identity2, rescale()) : clamp !== identity2;
  };
  scale.interpolate = function(_2) {
    return arguments.length ? (interpolate = _2, rescale()) : interpolate;
  };
  scale.unknown = function(_2) {
    return arguments.length ? (unknown2 = _2, scale) : unknown2;
  };
  return function(t4, u) {
    transform = t4, untransform = u;
    return rescale();
  };
}
function continuous() {
  return transformer()(identity2, identity2);
}

// node_modules/d3-scale/src/tickFormat.js
function tickFormat(start2, stop2, count2, specifier) {
  var step = tickStep(start2, stop2, count2), precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start2), Math.abs(stop2));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value))) specifier.precision = precision;
      return formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start2), Math.abs(stop2))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed_default(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format2(specifier);
}

// node_modules/d3-scale/src/linear.js
function linearish(scale) {
  var domain = scale.domain;
  scale.ticks = function(count2) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], count2 == null ? 10 : count2);
  };
  scale.tickFormat = function(count2, specifier) {
    var d = domain();
    return tickFormat(d[0], d[d.length - 1], count2 == null ? 10 : count2, specifier);
  };
  scale.nice = function(count2) {
    if (count2 == null) count2 = 10;
    var d = domain();
    var i0 = 0;
    var i1 = d.length - 1;
    var start2 = d[i0];
    var stop2 = d[i1];
    var prestep;
    var step;
    var maxIter = 10;
    if (stop2 < start2) {
      step = start2, start2 = stop2, stop2 = step;
      step = i0, i0 = i1, i1 = step;
    }
    while (maxIter-- > 0) {
      step = tickIncrement(start2, stop2, count2);
      if (step === prestep) {
        d[i0] = start2;
        d[i1] = stop2;
        return domain(d);
      } else if (step > 0) {
        start2 = Math.floor(start2 / step) * step;
        stop2 = Math.ceil(stop2 / step) * step;
      } else if (step < 0) {
        start2 = Math.ceil(start2 * step) / step;
        stop2 = Math.floor(stop2 * step) / step;
      } else {
        break;
      }
      prestep = step;
    }
    return scale;
  };
  return scale;
}
function linear2() {
  var scale = continuous();
  scale.copy = function() {
    return copy(scale, linear2());
  };
  initRange.apply(scale, arguments);
  return linearish(scale);
}

// node_modules/d3-scale/src/nice.js
function nice(domain, interval2) {
  domain = domain.slice();
  var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], t4;
  if (x1 < x0) {
    t4 = i0, i0 = i1, i1 = t4;
    t4 = x0, x0 = x1, x1 = t4;
  }
  domain[i0] = interval2.floor(x0);
  domain[i1] = interval2.ceil(x1);
  return domain;
}

// node_modules/d3-scale/src/pow.js
function transformPow(exponent) {
  return function(x2) {
    return x2 < 0 ? -Math.pow(-x2, exponent) : Math.pow(x2, exponent);
  };
}
function transformSqrt(x2) {
  return x2 < 0 ? -Math.sqrt(-x2) : Math.sqrt(x2);
}
function transformSquare(x2) {
  return x2 < 0 ? -x2 * x2 : x2 * x2;
}
function powish(transform) {
  var scale = transform(identity2, identity2), exponent = 1;
  function rescale() {
    return exponent === 1 ? transform(identity2, identity2) : exponent === 0.5 ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent), transformPow(1 / exponent));
  }
  scale.exponent = function(_2) {
    return arguments.length ? (exponent = +_2, rescale()) : exponent;
  };
  return linearish(scale);
}
function pow() {
  var scale = powish(transformer());
  scale.copy = function() {
    return copy(scale, pow()).exponent(scale.exponent());
  };
  initRange.apply(scale, arguments);
  return scale;
}
function sqrt2() {
  return pow.apply(null, arguments).exponent(0.5);
}

// node_modules/d3-scale/src/time.js
function date3(t4) {
  return new Date(t4);
}
function number6(t4) {
  return t4 instanceof Date ? +t4 : +/* @__PURE__ */ new Date(+t4);
}
function calendar(ticks2, tickInterval, year, month, week, day2, hour, minute, second2, format3) {
  var scale = continuous(), invert = scale.invert, domain = scale.domain;
  var formatMillisecond = format3(".%L"), formatSecond = format3(":%S"), formatMinute = format3("%I:%M"), formatHour = format3("%I %p"), formatDay = format3("%a %d"), formatWeek = format3("%b %d"), formatMonth = format3("%B"), formatYear2 = format3("%Y");
  function tickFormat2(date4) {
    return (second2(date4) < date4 ? formatMillisecond : minute(date4) < date4 ? formatSecond : hour(date4) < date4 ? formatMinute : day2(date4) < date4 ? formatHour : month(date4) < date4 ? week(date4) < date4 ? formatDay : formatWeek : year(date4) < date4 ? formatMonth : formatYear2)(date4);
  }
  scale.invert = function(y2) {
    return new Date(invert(y2));
  };
  scale.domain = function(_2) {
    return arguments.length ? domain(Array.from(_2, number6)) : domain().map(date3);
  };
  scale.ticks = function(interval2) {
    var d = domain();
    return ticks2(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
  };
  scale.tickFormat = function(count2, specifier) {
    return specifier == null ? tickFormat2 : format3(specifier);
  };
  scale.nice = function(interval2) {
    var d = domain();
    if (!interval2 || typeof interval2.range !== "function") interval2 = tickInterval(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
    return interval2 ? domain(nice(d, interval2)) : scale;
  };
  scale.copy = function() {
    return copy(scale, calendar(ticks2, tickInterval, year, month, week, day2, hour, minute, second2, format3));
  };
  return scale;
}

// node_modules/d3-scale/src/utcTime.js
function utcTime() {
  return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear, utcMonth, utcSunday, utcDay, utcHour, utcMinute, second, utcFormat).domain([Date.UTC(2e3, 0, 1), Date.UTC(2e3, 0, 2)]), arguments);
}

// src/stores/format.ts
var short_format = format2(".3s");
var short = derived2(
  incognito,
  ($incognito) => $incognito ? (n) => replaceNumbers(short_format(n)) : short_format
);
var num = derived2(locale, ($locale) => localeFormatter($locale));
var ctx = derived2(
  [incognito, locale, precisions],
  ([$incognito, $locale, $precisions]) => formatter_context($incognito, $locale, $precisions)
);
var currentDateFormat = derived2(interval, (val) => dateFormat[val]);
var currentTimeFilterDateFormat = derived2(
  interval,
  (val) => timeFilterDateFormat[val]
);

// src/charts/Axis.svelte
var root_12 = ns_template(`<g class="zero svelte-1spnwv9"><line class="svelte-1spnwv9"></line></g>`);
var root4 = ns_template(`<g><!></g>`);
function Axis($$anchor, $$props) {
  push($$props, true);
  let x2 = prop($$props, "x", 3, false), y2 = prop($$props, "y", 3, false), innerHeight2 = prop($$props, "innerHeight", 3, 0);
  let transform = user_derived(() => x2() ? `translate(0,${innerHeight2().toString()})` : void 0);
  const renderAxis = (node, ax) => {
    const selection2 = select_default2(node);
    ax(selection2);
    return {
      update(new_ax) {
        new_ax(selection2);
      }
    };
  };
  var g = root4();
  let classes;
  var node_1 = child(g);
  {
    var consequent = ($$anchor2) => {
      var g_1 = root_12();
      var line = child(g_1);
      reset(g_1);
      template_effect(
        ($0, $1) => {
          set_attribute(g_1, "transform", $0);
          set_attribute(line, "x2", $1);
        },
        [
          () => `translate(0,${$$props.lineAtZero.toString()})`,
          () => -$$props.axis.tickSizeInner()
        ]
      );
      append($$anchor2, g_1);
    };
    if_block(node_1, ($$render) => {
      if (y2() && $$props.lineAtZero != null) $$render(consequent);
    });
  }
  reset(g);
  action(g, ($$node, $$action_arg) => renderAxis?.($$node, $$action_arg), () => $$props.axis);
  template_effect(
    ($0) => {
      set_attribute(g, "transform", get(transform));
      classes = set_class(g, 0, "svelte-1spnwv9", null, classes, $0);
    },
    [() => ({ y: y2() })]
  );
  append($$anchor, g);
  pop();
}

// src/charts/helpers.ts
function urlForTimeFilter(date4) {
  const url = new URL(window.location.href);
  url.searchParams.set("time", get2(currentTimeFilterDateFormat)(date4));
  return url.toString();
}
function includeZero([from, to]) {
  if (from === void 0) {
    return [0, 1];
  }
  return [Math.min(0, from), Math.max(0, to)];
}
function padExtent([from, to]) {
  if (from === void 0) {
    return [0, 1];
  }
  const diff = to - from;
  return [from - diff * 0.03, to + diff * 0.03];
}
function filterTicks(domain, count2) {
  if (domain.length <= count2) {
    return domain;
  }
  const showIndices = Math.ceil(domain.length / count2);
  return domain.filter((d, i2) => i2 % showIndices === 0);
}
function hclColorRange(count2, chroma = 45, luminance = 70) {
  const offset = 270;
  const delta = 360 / count2;
  const colors = [...Array(count2).keys()].map((index3) => {
    const hue = (index3 * delta + offset) % 360;
    return hcl(hue, chroma, luminance);
  });
  return colors.map((c) => c.toString());
}
var colors10 = hclColorRange(10);
var colors15 = hclColorRange(15, 30, 80);
var scatterplotScale = ordinal(colors10);
var treemapScale = derived2(
  accounts,
  ($accounts) => ordinal(colors15).domain($accounts)
);
var sunburstScale = derived2(
  accounts,
  ($accounts) => ordinal(colors10).domain($accounts)
);
var currenciesScale = derived2(
  [operating_currency, currencies_sorted],
  ([$operating_currency, $currencies_sorted]) => ordinal(colors10).domain([
    ...$operating_currency,
    ...$currencies_sorted
  ])
);

// src/charts/BarChart.svelte
var root_3 = ns_template(`<rect></rect><rect class="budget svelte-1azm6ea"></rect>`, 1);
var root_13 = ns_template(`<g><rect class="group-box svelte-1azm6ea"></rect><a><rect class="axis-group-box svelte-1azm6ea"></rect></a><!></g>`);
var on_mouseover = (_2, highlighted, account2) => {
  set(highlighted, get(account2), true);
};
var on_mouseout = (__1, highlighted) => {
  set(highlighted, null);
};
var root_7 = ns_template(`<rect></rect>`);
var root_6 = ns_template(`<a><g role="img"></g></a>`);
var root5 = ns_template(`<svg><g><!><!><!><!></g></svg>`);
function BarChart2($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $chartToggledCurrencies = () => store_get(chartToggledCurrencies, "$chartToggledCurrencies", $$stores);
  const $barChartMode = () => store_get(barChartMode, "$barChartMode", $$stores);
  const $short = () => store_get(short, "$short", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $currentTimeFilterDateFormat = () => store_get(currentTimeFilterDateFormat, "$currentTimeFilterDateFormat", $$stores);
  const $currenciesScale = () => store_get(currenciesScale, "$currenciesScale", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  const today = /* @__PURE__ */ new Date();
  const maxColumnWidth = 100;
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  const height = 250;
  let accounts2 = user_derived(() => $$props.chart.accounts);
  let filtered = user_derived(() => $$props.chart.filter($chartToggledCurrencies()));
  let currencies2 = user_derived(() => get(filtered).currencies);
  let bar_groups = user_derived(() => get(filtered).bar_groups);
  let stacks = user_derived(() => get(filtered).stacks);
  let innerHeight2 = user_derived(() => height - margin.top - margin.bottom);
  let maxWidth = user_derived(() => get(bar_groups).length * maxColumnWidth);
  let offset = user_derived(() => margin.left + Math.max(0, $$props.width - get(maxWidth)) / 2);
  let innerWidth = user_derived(() => Math.min($$props.width - margin.left - margin.right, get(maxWidth)));
  let showStackedBars = user_derived(() => $barChartMode() === "stacked" && $$props.chart.hasStackedData);
  let highlighted = state(null);
  let x0 = user_derived(() => band([0, get(innerWidth)]).domain(get(bar_groups).map((d) => d.label)).padding(0.1));
  let x1 = user_derived(() => band([0, get(x0).bandwidth()]).domain(get(currencies2)));
  let yExtent = user_derived(() => get(showStackedBars) ? extent(get(stacks).flatMap(([, s]) => s.flat(2))) : extent(get(bar_groups).map((d) => d.values).flat(), (d) => d.value));
  let y2 = user_derived(() => linear2([get(innerHeight2), 0]).domain(padExtent(includeZero(get(yExtent)))));
  let colorScale = user_derived(() => ordinal(hclColorRange(get(accounts2).length)).domain(get(accounts2)));
  let xAxis = user_derived(() => axisBottom(get(x0)).tickSizeOuter(0).tickValues(filterTicks(get(x0).domain(), get(innerWidth) / 70)));
  let yAxis = user_derived(() => axisLeft(get(y2)).tickPadding(6).tickSize(-get(innerWidth)).tickFormat($short()));
  var svg2 = root5();
  var g = child(svg2);
  var node = child(g);
  Axis(node, {
    x: true,
    get axis() {
      return get(xAxis);
    },
    get innerHeight() {
      return get(innerHeight2);
    }
  });
  var node_1 = sibling(node);
  const expression = user_derived(() => get(y2)(0));
  Axis(node_1, {
    y: true,
    get axis() {
      return get(yAxis);
    },
    get lineAtZero() {
      return get(expression);
    }
  });
  var node_2 = sibling(node_1);
  each(node_2, 17, () => get(bar_groups), index, ($$anchor2, group2) => {
    var g_1 = root_13();
    let classes;
    var rect = child(g_1);
    var a = sibling(rect);
    var rect_1 = child(a);
    reset(a);
    var node_3 = sibling(a);
    {
      var consequent = ($$anchor3) => {
        var fragment = comment();
        var node_4 = first_child(fragment);
        each(node_4, 17, () => get(group2).values, index, ($$anchor4, $$item) => {
          let currency = () => get($$item).currency;
          let value = () => get($$item).value;
          let budget = () => get($$item).budget;
          var fragment_1 = root_3();
          var rect_2 = first_child(fragment_1);
          var rect_3 = sibling(rect_2);
          template_effect(
            ($0, $1, $2, $3, $4, $5, $6, $7, $8) => {
              set_attribute(rect_2, "fill", $0);
              set_attribute(rect_2, "width", $1);
              set_attribute(rect_2, "x", $2);
              set_attribute(rect_2, "y", $3);
              set_attribute(rect_2, "height", $4);
              set_attribute(rect_3, "width", $5);
              set_attribute(rect_3, "x", $6);
              set_attribute(rect_3, "y", $7);
              set_attribute(rect_3, "height", $8);
            },
            [
              () => $currenciesScale()(currency()),
              () => get(x1).bandwidth(),
              () => get(x1)(currency()),
              () => get(y2)(Math.max(0, value())),
              () => Math.abs(get(y2)(value()) - get(y2)(0)),
              () => get(x1).bandwidth(),
              () => get(x1)(currency()),
              () => get(y2)(Math.max(0, budget())),
              () => Math.abs(get(y2)(budget()) - get(y2)(0))
            ]
          );
          append($$anchor4, fragment_1);
        });
        append($$anchor3, fragment);
      };
      if_block(node_3, ($$render) => {
        if (!get(showStackedBars)) $$render(consequent);
      });
    }
    reset(g_1);
    action(g_1, ($$node, $$action_arg) => followingTooltip?.($$node, $$action_arg), () => () => $$props.chart.tooltipText($ctx(), get(group2)));
    template_effect(
      ($0, $1, $2, $3, $4, $5, $6, $7) => {
        classes = set_class(g_1, 0, "group svelte-1azm6ea", null, classes, $0);
        set_attribute(g_1, "transform", $1);
        set_attribute(rect, "x", $2);
        set_attribute(rect, "width", $3);
        set_attribute(rect, "height", get(innerHeight2));
        set_attribute(a, "href", $4);
        set_attribute(a, "aria-label", $5);
        set_attribute(rect_1, "transform", $6);
        set_attribute(rect_1, "width", $7);
        set_attribute(rect_1, "height", margin.bottom);
      },
      [
        () => ({ desaturate: get(group2).date > today }),
        () => `translate(${(get(x0)(get(group2).label) ?? 0).toString()},0)`,
        () => (get(x0).bandwidth() - get(x0).step()) / 2,
        () => get(x0).step(),
        () => urlForTimeFilter(get(group2).date),
        () => $currentTimeFilterDateFormat()(get(group2).date),
        () => `translate(0,${get(innerHeight2).toString()})`,
        () => get(x0).bandwidth()
      ]
    );
    append($$anchor2, g_1);
  });
  var node_5 = sibling(node_2);
  {
    var consequent_1 = ($$anchor2) => {
      var fragment_2 = comment();
      var node_6 = first_child(fragment_2);
      each(node_6, 17, () => get(stacks), index, ($$anchor3, $$item) => {
        let currency = () => get($$item)[0];
        let account_stacks = () => get($$item)[1];
        var fragment_3 = comment();
        var node_7 = first_child(fragment_3);
        each(node_7, 17, account_stacks, index, ($$anchor4, stack2) => {
          var a_1 = root_6();
          const account2 = user_derived(() => get(stack2).key);
          var g_2 = child(a_1);
          let classes_1;
          g_2.__mouseover = [on_mouseover, highlighted, account2];
          g_2.__mouseout = [on_mouseout, highlighted];
          each(g_2, 21, () => get(stack2), index, ($$anchor5, bar2) => {
            var rect_4 = root_7();
            let classes_2;
            action(rect_4, ($$node, $$action_arg) => followingTooltip?.($$node, $$action_arg), () => () => $$props.chart.tooltipTextAccount($ctx(), get(bar2).data, get(account2), $chartToggledCurrencies()));
            template_effect(
              ($0, $1, $2, $3, $4, $5) => {
                set_attribute(rect_4, "width", $0);
                set_attribute(rect_4, "x", $1);
                set_attribute(rect_4, "y", $2);
                set_attribute(rect_4, "height", $3);
                set_attribute(rect_4, "fill", $4);
                classes_2 = set_class(rect_4, 0, "svelte-1azm6ea", null, classes_2, $5);
              },
              [
                () => get(x1).bandwidth(),
                () => (get(x0)(get(bar2).data.label) ?? 0) + (get(x1)(currency()) ?? 0),
                () => get(y2)(Math.max(get(bar2)[0], get(bar2)[1])),
                () => Math.abs(get(y2)(get(bar2)[1]) - get(y2)(get(bar2)[0])),
                () => get(colorScale)(get(account2)),
                () => ({ desaturate: get(bar2).data.date > today })
              ]
            );
            append($$anchor5, rect_4);
          });
          reset(g_2);
          reset(a_1);
          template_effect(
            ($0, $1) => {
              set_attribute(a_1, "href", $0);
              classes_1 = set_class(g_2, 0, "category svelte-1azm6ea", null, classes_1, $1);
            },
            [
              () => $urlForAccount()(get(account2)),
              () => ({
                faded: get(highlighted) != null && get(account2) !== get(highlighted)
              })
            ]
          );
          event("focus", g_2, () => {
            set(highlighted, get(account2), true);
          });
          event("blur", g_2, () => {
            set(highlighted, null);
          });
          append($$anchor4, a_1);
        });
        append($$anchor3, fragment_3);
      });
      append($$anchor2, fragment_2);
    };
    if_block(node_5, ($$render) => {
      if (get(showStackedBars)) $$render(consequent_1);
    });
  }
  reset(g);
  reset(svg2);
  template_effect(
    ($0, $1) => {
      set_attribute(svg2, "viewBox", $0);
      set_attribute(g, "transform", $1);
    },
    [
      () => `0 0 ${$$props.width.toString()} ${height.toString()}`,
      () => `translate(${get(offset).toString()},${margin.top.toString()})`
    ]
  );
  append($$anchor, svg2);
  pop();
  $$cleanup();
}
delegate(["mouseover", "mouseout"]);

// src/charts/ChartLegend.svelte
var root_14 = template(`<button type="button"><i class="svelte-1vr06b0"></i> <span class="svelte-1vr06b0"> </span></button>`);
var root6 = template(`<div></div>`);
function ChartLegend($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $active = () => store_get($$props.active, "$active", $$stores);
  const $toggled = () => store_get($$props.toggled, "$toggled", $$stores);
  const $currenciesScale = () => store_get(currenciesScale, "$currenciesScale", $$stores);
  var div = root6();
  each(div, 21, () => $$props.legend, index, ($$anchor2, item) => {
    var button = root_14();
    button.__click = () => {
      if ($$props.active) {
        $$props.active.set(get(item));
      } else if ($$props.toggled) {
        $$props.toggled.update((v) => v.includes(get(item)) ? v.filter((i2) => i2 !== get(item)) : [...v, get(item)]);
      }
    };
    let classes;
    var i_1 = child(button);
    var span = sibling(i_1, 2);
    var text2 = child(span, true);
    reset(span);
    reset(button);
    template_effect(
      ($0, $1) => {
        classes = set_class(button, 1, "svelte-1vr06b0", null, classes, $0);
        set_style(i_1, `background-color: ${$1 ?? ""}`);
        set_text(text2, get(item));
      },
      [
        () => ({
          inactive: $$props.active ? get(item) !== $active() : $toggled()?.includes(get(item))
        }),
        () => $$props.color ? $currenciesScale()(get(item)) : "#bbb"
      ]
    );
    append($$anchor2, button);
  });
  reset(div);
  append($$anchor, div);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/charts/Sunburst.svelte
var on_mouseover2 = (_2, current, d) => {
  set(current, get(d), true);
};
var root_2 = ns_template(`<a><path fill-rule="evenodd" role="img"></path></a>`);
var root_15 = ns_template(`<g role="img"><circle style="opacity:0"></circle><text class="account svelte-1j2l4ij" text-anchor="middle"> </text><text class="balance svelte-1j2l4ij" dy="1.2em" text-anchor="middle"> </text><!></g>`);
function Sunburst($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  const $sunburstScale = () => store_get(sunburstScale, "$sunburstScale", $$stores);
  let radius = user_derived(() => Math.min($$props.width, $$props.height) / 2);
  let root68 = user_derived(() => partition_default()($$props.data));
  let nodes = user_derived(() => get(root68).descendants().filter((d) => !d.data.dummy && d.depth > 0));
  let current = state(null);
  user_pre_effect(() => {
    $$props.data;
    untrack(() => {
      set(current, null);
    });
  });
  function balanceText(d) {
    const val = d.value ?? 0;
    const total = get(root68).value ?? 0;
    return total ? `${$ctx().amount(val, $$props.currency)} (${formatPercentage(val / total)})` : $ctx().amount(val, $$props.currency);
  }
  const x2 = linear2([0, 2 * Math.PI]);
  let y2 = user_derived(() => sqrt2([0, get(radius)]));
  let arcShape = user_derived(() => arc_default().startAngle((d) => x2(d.x0)).endAngle((d) => x2(d.x1)).innerRadius((d) => get(y2)(d.y0)).outerRadius((d) => get(y2)(d.y1)));
  var g = root_15();
  var circle = child(g);
  var text2 = sibling(circle);
  var text_1 = child(text2, true);
  reset(text2);
  var text_2 = sibling(text2);
  var text_3 = child(text_2, true);
  reset(text_2);
  var node = sibling(text_2);
  each(node, 17, () => get(nodes), index, ($$anchor2, d) => {
    var a = root_2();
    var path2 = child(a);
    path2.__mouseover = [on_mouseover2, current, d];
    let classes;
    reset(a);
    template_effect(
      ($0, $1, $2, $3) => {
        set_attribute(a, "href", $0);
        set_attribute(a, "aria-label", get(d).data.account);
        set_attribute(path2, "fill", $1);
        set_attribute(path2, "d", $2);
        classes = set_class(path2, 0, "svelte-1j2l4ij", null, classes, $3);
      },
      [
        () => $urlForAccount()(get(d).data.account),
        () => $sunburstScale()(get(d).data.account),
        () => get(arcShape)(get(d)),
        () => ({
          half: get(current) && !get(current).data.account.startsWith(get(d).data.account)
        })
      ]
    );
    event("focus", path2, () => {
      set(current, get(d), true);
    });
    append($$anchor2, a);
  });
  reset(g);
  template_effect(
    ($0, $1) => {
      set_attribute(g, "width", $$props.width);
      set_attribute(g, "height", $$props.height);
      set_attribute(g, "transform", $0);
      set_attribute(circle, "r", get(radius));
      set_text(text_1, (get(current) ?? get(root68)).data.account);
      set_text(text_3, $1);
    },
    [
      () => `translate(${($$props.width / 2).toString()},${($$props.height / 2).toString()})`,
      () => balanceText(get(current) ?? get(root68))
    ]
  );
  event("mouseleave", g, () => {
    set(current, null);
  });
  append($$anchor, g);
  pop();
  $$cleanup();
}
delegate(["mouseover"]);

// src/charts/Treemap.svelte
var root_22 = ns_template(`<g><rect></rect><a><text dy=".5em" text-anchor="middle"> </text></a></g>`);
var root_16 = ns_template(`<svg class="svelte-dnkmbd"></svg>`);
function Treemap($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $treemapScale = () => store_get(treemapScale, "$treemapScale", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  let height = user_derived(() => Math.min($$props.width / 2.5, 400));
  const tree = treemap_default().paddingInner(2).round(true);
  let root68 = user_derived(() => tree.size([$$props.width, get(height)])($$props.data));
  let leaves = user_derived(() => get(root68).leaves().filter((d) => d.value != null && d.value !== 0));
  function fill(d) {
    const node = d.data.dummy && d.parent ? d.parent : d;
    if (node.depth === 1 || !node.parent) {
      return $treemapScale()(node.data.account);
    }
    return $treemapScale()(node.parent.data.account);
  }
  function tooltipText(d) {
    const val = d.value ?? 0;
    const rootValue = get(root68).value ?? 1;
    return [
      domHelpers.t(`${$ctx().amount(val, $$props.currency)} (${formatPercentage(val / rootValue)})`),
      domHelpers.em(d.data.account)
    ];
  }
  const setVisibility = (node, param) => {
    function update3(d) {
      const length = node.getComputedTextLength();
      node.style.visibility = d.x1 - d.x0 > length + 4 && d.y1 - d.y0 > 14 ? "visible" : "hidden";
    }
    update3(param);
    return { update: update3 };
  };
  var svg2 = root_16();
  each(svg2, 21, () => get(leaves), index, ($$anchor2, d) => {
    var g = root_22();
    var rect = child(g);
    var a = sibling(rect);
    var text2 = child(a);
    var text_1 = child(text2, true);
    reset(text2);
    action(text2, ($$node, $$action_arg) => setVisibility?.($$node, $$action_arg), () => get(d));
    reset(a);
    reset(g);
    action(g, ($$node, $$action_arg) => followingTooltip?.($$node, $$action_arg), () => () => tooltipText(get(d)));
    template_effect(
      ($0, $1, $2, $3) => {
        set_attribute(g, "transform", $0);
        set_attribute(rect, "fill", $1);
        set_attribute(rect, "width", get(d).x1 - get(d).x0);
        set_attribute(rect, "height", get(d).y1 - get(d).y0);
        set_attribute(a, "href", $2);
        set_attribute(text2, "x", (get(d).x1 - get(d).x0) / 2);
        set_attribute(text2, "y", (get(d).y1 - get(d).y0) / 2);
        set_text(text_1, $3);
      },
      [
        () => `translate(${get(d).x0.toString()},${get(d).y0.toString()})`,
        () => fill(get(d)),
        () => $urlForAccount()(get(d).data.account),
        () => get(d).data.account.split(":").pop() ?? ""
      ]
    );
    append($$anchor2, g);
  });
  reset(svg2);
  template_effect(($0) => set_attribute(svg2, "viewBox", $0), [
    () => `0 0 ${$$props.width.toString()} ${get(height).toString()}`
  ]);
  append($$anchor, svg2);
  pop();
  $$cleanup();
}

// src/charts/HierarchyContainer.svelte
var root_17 = ns_template(`<svg><text text-anchor="middle"> </text></svg>`);
var root_62 = ns_template(`<g><!></g>`);
var root_5 = ns_template(`<svg></svg>`);
function HierarchyContainer($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $hierarchyChartMode = () => store_get(hierarchyChartMode, "$hierarchyChartMode", $$stores);
  const $treemap_currency = () => store_get(get(treemap_currency), "$treemap_currency", $$stores);
  let data = user_derived(() => $$props.chart.data);
  let currencies2 = user_derived(() => $$props.chart.currencies);
  let treemap_currency = user_derived(() => $$props.chart.treemap_currency);
  let mode = user_derived($hierarchyChartMode);
  let treemap = user_derived(() => get(mode) === "treemap" ? get(data).get($treemap_currency() ?? "") : void 0);
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var svg2 = root_17();
      var text2 = child(svg2);
      set_attribute(text2, "y", 80);
      var text_1 = child(text2, true);
      reset(text2);
      reset(svg2);
      template_effect(
        ($0, $1) => {
          set_attribute(svg2, "viewBox", $0);
          set_attribute(text2, "x", $$props.width / 2);
          set_text(text_1, $1);
        },
        [
          () => `0 0 ${$$props.width.toString()} 160`,
          () => _("Chart is empty.")
        ]
      );
      append($$anchor2, svg2);
    };
    var alternate = ($$anchor2, $$elseif) => {
      {
        var consequent_1 = ($$anchor3) => {
          Treemap($$anchor3, {
            get data() {
              return get(treemap);
            },
            get currency() {
              return $treemap_currency();
            },
            get width() {
              return $$props.width;
            }
          });
        };
        var alternate_1 = ($$anchor3, $$elseif2) => {
          {
            var consequent_2 = ($$anchor4) => {
              var svg_1 = root_5();
              each(svg_1, 23, () => [...get(data)], ([chart_currency, d]) => chart_currency, ($$anchor5, $$item, i2) => {
                let chart_currency = () => get($$item)[0];
                let d = () => get($$item)[1];
                var g = root_62();
                var node_1 = child(g);
                const expression = user_derived(() => $$props.width / get(currencies2).length);
                Sunburst(node_1, {
                  get data() {
                    return d();
                  },
                  get currency() {
                    return chart_currency();
                  },
                  get width() {
                    return get(expression);
                  },
                  height: 500
                });
                reset(g);
                template_effect(($0) => set_attribute(g, "transform", $0), [
                  () => `translate(${($$props.width * get(i2) / get(currencies2).length).toString()},0)`
                ]);
                append($$anchor5, g);
              });
              reset(svg_1);
              template_effect(($0) => set_attribute(svg_1, "viewBox", $0), [
                () => `0 0 ${$$props.width.toString()} 500`
              ]);
              append($$anchor4, svg_1);
            };
            if_block(
              $$anchor3,
              ($$render) => {
                if (get(mode) === "sunburst") $$render(consequent_2);
              },
              $$elseif2
            );
          }
        };
        if_block(
          $$anchor2,
          ($$render) => {
            if (get(treemap) && $treemap_currency()) $$render(consequent_1);
            else $$render(alternate_1, false);
          },
          $$elseif
        );
      }
    };
    if_block(node, ($$render) => {
      if (get(currencies2).length === 0) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// node_modules/d3-quadtree/src/add.js
function add_default(d) {
  const x2 = +this._x.call(null, d), y2 = +this._y.call(null, d);
  return add2(this.cover(x2, y2), x2, y2, d);
}
function add2(tree, x2, y2, d) {
  if (isNaN(x2) || isNaN(y2)) return tree;
  var parent2, node = tree._root, leaf2 = { data: d }, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1, xm, ym, xp, yp, right2, bottom2, i2, j;
  if (!node) return tree._root = leaf2, tree;
  while (node.length) {
    if (right2 = x2 >= (xm = (x0 + x1) / 2)) x0 = xm;
    else x1 = xm;
    if (bottom2 = y2 >= (ym = (y0 + y1) / 2)) y0 = ym;
    else y1 = ym;
    if (parent2 = node, !(node = node[i2 = bottom2 << 1 | right2])) return parent2[i2] = leaf2, tree;
  }
  xp = +tree._x.call(null, node.data);
  yp = +tree._y.call(null, node.data);
  if (x2 === xp && y2 === yp) return leaf2.next = node, parent2 ? parent2[i2] = leaf2 : tree._root = leaf2, tree;
  do {
    parent2 = parent2 ? parent2[i2] = new Array(4) : tree._root = new Array(4);
    if (right2 = x2 >= (xm = (x0 + x1) / 2)) x0 = xm;
    else x1 = xm;
    if (bottom2 = y2 >= (ym = (y0 + y1) / 2)) y0 = ym;
    else y1 = ym;
  } while ((i2 = bottom2 << 1 | right2) === (j = (yp >= ym) << 1 | xp >= xm));
  return parent2[j] = node, parent2[i2] = leaf2, tree;
}
function addAll(data) {
  var d, i2, n = data.length, x2, y2, xz = new Array(n), yz = new Array(n), x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
  for (i2 = 0; i2 < n; ++i2) {
    if (isNaN(x2 = +this._x.call(null, d = data[i2])) || isNaN(y2 = +this._y.call(null, d))) continue;
    xz[i2] = x2;
    yz[i2] = y2;
    if (x2 < x0) x0 = x2;
    if (x2 > x1) x1 = x2;
    if (y2 < y0) y0 = y2;
    if (y2 > y1) y1 = y2;
  }
  if (x0 > x1 || y0 > y1) return this;
  this.cover(x0, y0).cover(x1, y1);
  for (i2 = 0; i2 < n; ++i2) {
    add2(this, xz[i2], yz[i2], data[i2]);
  }
  return this;
}

// node_modules/d3-quadtree/src/cover.js
function cover_default(x2, y2) {
  if (isNaN(x2 = +x2) || isNaN(y2 = +y2)) return this;
  var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1;
  if (isNaN(x0)) {
    x1 = (x0 = Math.floor(x2)) + 1;
    y1 = (y0 = Math.floor(y2)) + 1;
  } else {
    var z = x1 - x0 || 1, node = this._root, parent2, i2;
    while (x0 > x2 || x2 >= x1 || y0 > y2 || y2 >= y1) {
      i2 = (y2 < y0) << 1 | x2 < x0;
      parent2 = new Array(4), parent2[i2] = node, node = parent2, z *= 2;
      switch (i2) {
        case 0:
          x1 = x0 + z, y1 = y0 + z;
          break;
        case 1:
          x0 = x1 - z, y1 = y0 + z;
          break;
        case 2:
          x1 = x0 + z, y0 = y1 - z;
          break;
        case 3:
          x0 = x1 - z, y0 = y1 - z;
          break;
      }
    }
    if (this._root && this._root.length) this._root = node;
  }
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  return this;
}

// node_modules/d3-quadtree/src/data.js
function data_default2() {
  var data = [];
  this.visit(function(node) {
    if (!node.length) do
      data.push(node.data);
    while (node = node.next);
  });
  return data;
}

// node_modules/d3-quadtree/src/extent.js
function extent_default(_2) {
  return arguments.length ? this.cover(+_2[0][0], +_2[0][1]).cover(+_2[1][0], +_2[1][1]) : isNaN(this._x0) ? void 0 : [[this._x0, this._y0], [this._x1, this._y1]];
}

// node_modules/d3-quadtree/src/quad.js
function quad_default(node, x0, y0, x1, y1) {
  this.node = node;
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
}

// node_modules/d3-quadtree/src/find.js
function find_default2(x2, y2, radius) {
  var data, x0 = this._x0, y0 = this._y0, x1, y1, x22, y22, x3 = this._x1, y3 = this._y1, quads = [], node = this._root, q, i2;
  if (node) quads.push(new quad_default(node, x0, y0, x3, y3));
  if (radius == null) radius = Infinity;
  else {
    x0 = x2 - radius, y0 = y2 - radius;
    x3 = x2 + radius, y3 = y2 + radius;
    radius *= radius;
  }
  while (q = quads.pop()) {
    if (!(node = q.node) || (x1 = q.x0) > x3 || (y1 = q.y0) > y3 || (x22 = q.x1) < x0 || (y22 = q.y1) < y0) continue;
    if (node.length) {
      var xm = (x1 + x22) / 2, ym = (y1 + y22) / 2;
      quads.push(
        new quad_default(node[3], xm, ym, x22, y22),
        new quad_default(node[2], x1, ym, xm, y22),
        new quad_default(node[1], xm, y1, x22, ym),
        new quad_default(node[0], x1, y1, xm, ym)
      );
      if (i2 = (y2 >= ym) << 1 | x2 >= xm) {
        q = quads[quads.length - 1];
        quads[quads.length - 1] = quads[quads.length - 1 - i2];
        quads[quads.length - 1 - i2] = q;
      }
    } else {
      var dx = x2 - +this._x.call(null, node.data), dy = y2 - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
      if (d2 < radius) {
        var d = Math.sqrt(radius = d2);
        x0 = x2 - d, y0 = y2 - d;
        x3 = x2 + d, y3 = y2 + d;
        data = node.data;
      }
    }
  }
  return data;
}

// node_modules/d3-quadtree/src/remove.js
function remove_default2(d) {
  if (isNaN(x2 = +this._x.call(null, d)) || isNaN(y2 = +this._y.call(null, d))) return this;
  var parent2, node = this._root, retainer, previous, next2, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1, x2, y2, xm, ym, right2, bottom2, i2, j;
  if (!node) return this;
  if (node.length) while (true) {
    if (right2 = x2 >= (xm = (x0 + x1) / 2)) x0 = xm;
    else x1 = xm;
    if (bottom2 = y2 >= (ym = (y0 + y1) / 2)) y0 = ym;
    else y1 = ym;
    if (!(parent2 = node, node = node[i2 = bottom2 << 1 | right2])) return this;
    if (!node.length) break;
    if (parent2[i2 + 1 & 3] || parent2[i2 + 2 & 3] || parent2[i2 + 3 & 3]) retainer = parent2, j = i2;
  }
  while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  if (next2 = node.next) delete node.next;
  if (previous) return next2 ? previous.next = next2 : delete previous.next, this;
  if (!parent2) return this._root = next2, this;
  next2 ? parent2[i2] = next2 : delete parent2[i2];
  if ((node = parent2[0] || parent2[1] || parent2[2] || parent2[3]) && node === (parent2[3] || parent2[2] || parent2[1] || parent2[0]) && !node.length) {
    if (retainer) retainer[j] = node;
    else this._root = node;
  }
  return this;
}
function removeAll(data) {
  for (var i2 = 0, n = data.length; i2 < n; ++i2) this.remove(data[i2]);
  return this;
}

// node_modules/d3-quadtree/src/root.js
function root_default() {
  return this._root;
}

// node_modules/d3-quadtree/src/size.js
function size_default2() {
  var size = 0;
  this.visit(function(node) {
    if (!node.length) do
      ++size;
    while (node = node.next);
  });
  return size;
}

// node_modules/d3-quadtree/src/visit.js
function visit_default(callback) {
  var quads = [], q, node = this._root, child2, x0, y0, x1, y1;
  if (node) quads.push(new quad_default(node, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
      var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child2 = node[3]) quads.push(new quad_default(child2, xm, ym, x1, y1));
      if (child2 = node[2]) quads.push(new quad_default(child2, x0, ym, xm, y1));
      if (child2 = node[1]) quads.push(new quad_default(child2, xm, y0, x1, ym));
      if (child2 = node[0]) quads.push(new quad_default(child2, x0, y0, xm, ym));
    }
  }
  return this;
}

// node_modules/d3-quadtree/src/visitAfter.js
function visitAfter_default(callback) {
  var quads = [], next2 = [], q;
  if (this._root) quads.push(new quad_default(this._root, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    var node = q.node;
    if (node.length) {
      var child2, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child2 = node[0]) quads.push(new quad_default(child2, x0, y0, xm, ym));
      if (child2 = node[1]) quads.push(new quad_default(child2, xm, y0, x1, ym));
      if (child2 = node[2]) quads.push(new quad_default(child2, x0, ym, xm, y1));
      if (child2 = node[3]) quads.push(new quad_default(child2, xm, ym, x1, y1));
    }
    next2.push(q);
  }
  while (q = next2.pop()) {
    callback(q.node, q.x0, q.y0, q.x1, q.y1);
  }
  return this;
}

// node_modules/d3-quadtree/src/x.js
function defaultX(d) {
  return d[0];
}
function x_default(_2) {
  return arguments.length ? (this._x = _2, this) : this._x;
}

// node_modules/d3-quadtree/src/y.js
function defaultY(d) {
  return d[1];
}
function y_default(_2) {
  return arguments.length ? (this._y = _2, this) : this._y;
}

// node_modules/d3-quadtree/src/quadtree.js
function quadtree(nodes, x2, y2) {
  var tree = new Quadtree(x2 == null ? defaultX : x2, y2 == null ? defaultY : y2, NaN, NaN, NaN, NaN);
  return nodes == null ? tree : tree.addAll(nodes);
}
function Quadtree(x2, y2, x0, y0, x1, y1) {
  this._x = x2;
  this._y = y2;
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  this._root = void 0;
}
function leaf_copy(leaf2) {
  var copy2 = { data: leaf2.data }, next2 = copy2;
  while (leaf2 = leaf2.next) next2 = next2.next = { data: leaf2.data };
  return copy2;
}
var treeProto = quadtree.prototype = Quadtree.prototype;
treeProto.copy = function() {
  var copy2 = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child2;
  if (!node) return copy2;
  if (!node.length) return copy2._root = leaf_copy(node), copy2;
  nodes = [{ source: node, target: copy2._root = new Array(4) }];
  while (node = nodes.pop()) {
    for (var i2 = 0; i2 < 4; ++i2) {
      if (child2 = node.source[i2]) {
        if (child2.length) nodes.push({ source: child2, target: node.target[i2] = new Array(4) });
        else node.target[i2] = leaf_copy(child2);
      }
    }
  }
  return copy2;
};
treeProto.add = add_default;
treeProto.addAll = addAll;
treeProto.cover = cover_default;
treeProto.data = data_default2;
treeProto.extent = extent_default;
treeProto.find = find_default2;
treeProto.remove = remove_default2;
treeProto.removeAll = removeAll;
treeProto.root = root_default;
treeProto.size = size_default2;
treeProto.visit = visit_default;
treeProto.visitAfter = visitAfter_default;
treeProto.x = x_default;
treeProto.y = y_default;

// src/charts/LineChart.svelte
var root_23 = ns_template(`<path class="svelte-1gzc8m3"></path>`);
var root_18 = ns_template(`<g class="area svelte-1gzc8m3"></g>`);
var root_32 = ns_template(`<path class="svelte-1gzc8m3"></path>`);
var root_63 = ns_template(`<circle r="2"></circle>`);
var root_52 = ns_template(`<g></g>`);
var root_4 = ns_template(`<g></g>`);
var root7 = ns_template(`<svg class="svelte-1gzc8m3"><filter id="desaturateFuture"><feColorMatrix type="saturate" values="0.5"></feColorMatrix><feBlend in2="SourceGraphic"></feBlend></filter><g class="svelte-1gzc8m3"><!><!><!><g class="lines svelte-1gzc8m3"></g><!></g></svg>`);
function LineChart2($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $chartToggledCurrencies = () => store_get(chartToggledCurrencies, "$chartToggledCurrencies", $$stores);
  const $lineChartMode = () => store_get(lineChartMode, "$lineChartMode", $$stores);
  const $short = () => store_get(short, "$short", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $currenciesScale = () => store_get(currenciesScale, "$currenciesScale", $$stores);
  const today = /* @__PURE__ */ new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  const height = 250;
  let innerWidth = user_derived(() => $$props.width - margin.left - margin.right);
  let innerHeight2 = user_derived(() => height - margin.top - margin.bottom);
  let data = user_derived(() => $$props.chart.filter($chartToggledCurrencies()));
  let allValues = user_derived(() => get(data).map((d) => d.values).flat(1));
  let xExtent = user_derived(() => [
    min(get(data), (s) => s.values[0]?.date) ?? today,
    max(get(data), (s) => s.values[s.values.length - 1]?.date) ?? today
  ]);
  let x2 = user_derived(() => utcTime([0, get(innerWidth)]).domain(get(xExtent)));
  let valueExtent = user_derived(() => extent(get(allValues), (v) => v.value));
  let yExtent = user_derived(() => $lineChartMode() === "area" ? includeZero(get(valueExtent)) : get(valueExtent));
  let y2 = user_derived(() => linear2([get(innerHeight2), 0]).domain(padExtent(get(yExtent))));
  let quad = user_derived(() => quadtree(get(allValues), (d) => get(x2)(d.date), (d) => get(y2)(d.value)));
  let lineShape = user_derived(() => line_default().x((d) => get(x2)(d.date)).y((d) => get(y2)(d.value)).curve(stepAfter));
  let areaShape = user_derived(() => area_default().x((d) => get(x2)(d.date)).y1((d) => get(y2)(d.value)).y0(Math.min(get(innerHeight2), get(y2)(0))).curve(stepAfter));
  let xAxis = user_derived(() => axisBottom(get(x2)).tickSizeOuter(0));
  let yAxis = user_derived(() => axisLeft(get(y2)).tickPadding(6).tickSize(-get(innerWidth)).tickFormat($short()));
  const tooltipFindNode = (xPos, yPos) => {
    const d = get(quad).find(xPos, yPos);
    return d && [
      get(x2)(d.date),
      get(y2)(d.value),
      $$props.chart.tooltipText($ctx(), d)
    ];
  };
  let futureFilter = user_derived(() => get(xExtent)[1] > today ? "url(#desaturateFuture)" : void 0);
  var svg2 = root7();
  var filter2 = child(svg2);
  var feColorMatrix = child(filter2);
  next();
  reset(filter2);
  var g = sibling(filter2);
  var node = child(g);
  Axis(node, {
    x: true,
    get axis() {
      return get(xAxis);
    },
    get innerHeight() {
      return get(innerHeight2);
    }
  });
  var node_1 = sibling(node);
  Axis(node_1, {
    y: true,
    get axis() {
      return get(yAxis);
    }
  });
  var node_2 = sibling(node_1);
  {
    var consequent = ($$anchor2) => {
      var g_1 = root_18();
      each(g_1, 21, () => get(data), index, ($$anchor3, d) => {
        var path2 = root_23();
        template_effect(
          ($0, $1) => {
            set_attribute(path2, "d", $0);
            set_attribute(path2, "fill", $1);
          },
          [
            () => get(areaShape)(get(d).values),
            () => $currenciesScale()(get(d).name)
          ]
        );
        append($$anchor3, path2);
      });
      reset(g_1);
      template_effect(() => set_attribute(g_1, "filter", get(futureFilter)));
      append($$anchor2, g_1);
    };
    if_block(node_2, ($$render) => {
      if ($lineChartMode() === "area") $$render(consequent);
    });
  }
  var g_2 = sibling(node_2);
  each(g_2, 21, () => get(data), index, ($$anchor2, d) => {
    var path_1 = root_32();
    template_effect(
      ($0, $1) => {
        set_attribute(path_1, "d", $0);
        set_attribute(path_1, "stroke", $1);
      },
      [
        () => get(lineShape)(get(d).values),
        () => $currenciesScale()(get(d).name)
      ]
    );
    append($$anchor2, path_1);
  });
  reset(g_2);
  var node_3 = sibling(g_2);
  {
    var consequent_1 = ($$anchor2) => {
      var g_3 = root_4();
      each(g_3, 21, () => get(data), index, ($$anchor3, d) => {
        var g_4 = root_52();
        each(g_4, 21, () => get(d).values, index, ($$anchor4, v) => {
          var circle = root_63();
          let classes;
          template_effect(
            ($0, $1, $2) => {
              set_attribute(circle, "cx", $0);
              set_attribute(circle, "cy", $1);
              classes = set_class(circle, 0, "svelte-1gzc8m3", null, classes, $2);
            },
            [
              () => get(x2)(get(v).date),
              () => get(y2)(get(v).value),
              () => ({ desaturate: get(v).date > today })
            ]
          );
          append($$anchor4, circle);
        });
        reset(g_4);
        template_effect(($0) => set_attribute(g_4, "fill", $0), [
          () => $currenciesScale()(get(d).name)
        ]);
        append($$anchor3, g_4);
      });
      reset(g_3);
      append($$anchor2, g_3);
    };
    if_block(node_3, ($$render) => {
      if ($lineChartMode() === "line") $$render(consequent_1);
    });
  }
  reset(g);
  action(g, ($$node, $$action_arg) => positionedTooltip?.($$node, $$action_arg), () => tooltipFindNode);
  reset(svg2);
  template_effect(
    ($0, $1, $2) => {
      set_attribute(svg2, "viewBox", $0);
      set_attribute(feColorMatrix, "x", $1);
      set_attribute(g, "transform", $2);
      set_attribute(g_2, "filter", get(futureFilter));
    },
    [
      () => `0 0 ${$$props.width.toString()} ${height.toString()}`,
      () => get(x2)(today),
      () => `translate(${margin.left.toString()},${margin.top.toString()})`
    ]
  );
  append($$anchor, svg2);
  pop();
  $$cleanup();
}

// src/charts/ModeSwitch.svelte
var root_19 = template(`<label><input type="radio" class="svelte-14t26d6"> </label>`);
var root8 = template(`<span></span>`);
function ModeSwitch($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $store = () => store_get($$props.store, "$store", $$stores);
  const binding_group = [];
  var span = root8();
  each(span, 21, () => $$props.store.values(), index, ($$anchor2, $$item) => {
    let option = () => get($$item)[0];
    let name3 = () => get($$item)[1];
    var label = root_19();
    let classes;
    var input = child(label);
    remove_input_defaults(input);
    var input_value;
    var text2 = sibling(input);
    reset(label);
    template_effect(
      ($0) => {
        classes = set_class(label, 1, "button svelte-14t26d6", null, classes, $0);
        if (input_value !== (input_value = option())) {
          input.value = null == (input.__value = option()) ? "" : option();
        }
        set_text(text2, ` ${name3() ?? ""}`);
      },
      [
        () => ({ muted: $store() !== option() })
      ]
    );
    bind_group(
      binding_group,
      [],
      input,
      () => {
        option();
        return $store();
      },
      ($$value) => store_set($$props.store, $$value)
    );
    append($$anchor2, label);
  });
  reset(span);
  append($$anchor, span);
  pop();
  $$cleanup();
}

// src/charts/ScatterPlot.svelte
var root_110 = ns_template(`<circle r="5"></circle>`);
var root9 = ns_template(`<svg class="svelte-jl8ee"><g class="svelte-jl8ee"><!><!><g></g></g></svg>`);
function ScatterPlot2($$anchor, $$props) {
  push($$props, true);
  const today = /* @__PURE__ */ new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 70 };
  const height = 250;
  let innerWidth = user_derived(() => $$props.width - margin.left - margin.right);
  let innerHeight2 = user_derived(() => height - margin.top - margin.bottom);
  let dateExtent = user_derived(() => extent($$props.chart.data, (d) => d.date));
  let x2 = user_derived(() => utcTime([0, get(innerWidth)]).domain(get(dateExtent)[0] ? get(dateExtent) : [0, 1]));
  let y2 = user_derived(() => point([get(innerHeight2), 0]).domain($$props.chart.data.map((d) => d.type)).padding(1));
  let xAxis = user_derived(() => axisBottom(get(x2)).tickSizeOuter(0));
  let yAxis = user_derived(() => axisLeft(get(y2)).tickPadding(6).tickSize(-get(innerWidth)).tickFormat((d) => d));
  let quad = user_derived(() => quadtree([...$$props.chart.data], (d) => get(x2)(d.date), (d) => get(y2)(d.type) ?? 0));
  function tooltipText(d) {
    return [
      domHelpers.t(d.description),
      domHelpers.em(day(d.date))
    ];
  }
  const tooltipFindNode = (xPos, yPos) => {
    const d = get(quad).find(xPos, yPos);
    return d && [
      get(x2)(d.date),
      get(y2)(d.type) ?? 0,
      tooltipText(d)
    ];
  };
  var svg2 = root9();
  var g = child(svg2);
  var node = child(g);
  Axis(node, {
    x: true,
    get axis() {
      return get(xAxis);
    },
    get innerHeight() {
      return get(innerHeight2);
    }
  });
  var node_1 = sibling(node);
  Axis(node_1, {
    y: true,
    get axis() {
      return get(yAxis);
    }
  });
  var g_1 = sibling(node_1);
  each(g_1, 21, () => $$props.chart.data, index, ($$anchor2, dot) => {
    var circle = root_110();
    let classes;
    template_effect(
      ($0, $1, $2, $3) => {
        set_attribute(circle, "fill", $0);
        set_attribute(circle, "cx", $1);
        set_attribute(circle, "cy", $2);
        classes = set_class(circle, 0, "svelte-jl8ee", null, classes, $3);
      },
      [
        () => scatterplotScale(get(dot).type),
        () => get(x2)(get(dot).date),
        () => get(y2)(get(dot).type),
        () => ({ desaturate: get(dot).date > today })
      ]
    );
    append($$anchor2, circle);
  });
  reset(g_1);
  reset(g);
  action(g, ($$node, $$action_arg) => positionedTooltip?.($$node, $$action_arg), () => tooltipFindNode);
  reset(svg2);
  template_effect(
    ($0, $1) => {
      set_attribute(svg2, "viewBox", $0);
      set_attribute(g, "transform", $1);
    },
    [
      () => `0 0 ${$$props.width.toString()} ${height.toString()}`,
      () => `translate(${margin.left.toString()},${margin.top.toString()})`
    ]
  );
  append($$anchor, svg2);
  pop();
}

// src/charts/Chart.svelte
var root_111 = template(`<!> <!> <!> <span class="spacer"></span> <!>`, 1);
var root_10 = template(`<span class="spacer"></span>`);
var root10 = template(`<div class="flex-row"><!> <!> <button type="button" class="show-charts svelte-wpmxoo"> </button></div> <div><!></div>`, 1);
function Chart($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $showCharts = () => store_get(showCharts, "$showCharts", $$stores);
  const $barChartMode = () => store_get(barChartMode, "$barChartMode", $$stores);
  const $hierarchyChartMode = () => store_get(hierarchyChartMode, "$hierarchyChartMode", $$stores);
  let width = state(void 0);
  var fragment = root10();
  var div = first_child(fragment);
  var node = child(div);
  {
    var consequent_6 = ($$anchor2) => {
      var fragment_1 = root_111();
      var node_1 = first_child(fragment_1);
      {
        var consequent = ($$anchor3) => {
          const expression = user_derived(() => !($barChartMode() === "stacked" && $$props.chart.hasStackedData));
          ChartLegend($$anchor3, {
            get legend() {
              return $$props.chart.currencies;
            },
            get color() {
              return get(expression);
            },
            toggled: chartToggledCurrencies
          });
        };
        if_block(node_1, ($$render) => {
          if ($$props.chart.type === "barchart") $$render(consequent);
        });
      }
      var node_2 = sibling(node_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          ChartLegend($$anchor3, {
            get legend() {
              return $$props.chart.series_names;
            },
            color: true,
            toggled: chartToggledCurrencies
          });
        };
        if_block(node_2, ($$render) => {
          if ($$props.chart.type === "linechart") $$render(consequent_1);
        });
      }
      var node_3 = sibling(node_2, 2);
      {
        var consequent_2 = ($$anchor3) => {
          ChartLegend($$anchor3, {
            get legend() {
              return $$props.chart.currencies;
            },
            color: false,
            get active() {
              return $$props.chart.treemap_currency;
            }
          });
        };
        if_block(node_3, ($$render) => {
          if ($$props.chart.type === "hierarchy" && $hierarchyChartMode() === "treemap" && $$props.chart.treemap_currency) $$render(consequent_2);
        });
      }
      var node_4 = sibling(node_3, 4);
      {
        var consequent_3 = ($$anchor3) => {
          ModeSwitch($$anchor3, { store: hierarchyChartMode });
        };
        var alternate = ($$anchor3, $$elseif) => {
          {
            var consequent_4 = ($$anchor4) => {
              ModeSwitch($$anchor4, { store: lineChartMode });
            };
            var alternate_1 = ($$anchor4, $$elseif2) => {
              {
                var consequent_5 = ($$anchor5) => {
                  ModeSwitch($$anchor5, { store: barChartMode });
                };
                if_block(
                  $$anchor4,
                  ($$render) => {
                    if ($$props.chart.type === "barchart" && $$props.chart.hasStackedData) $$render(consequent_5);
                  },
                  $$elseif2
                );
              }
            };
            if_block(
              $$anchor3,
              ($$render) => {
                if ($$props.chart.type === "linechart") $$render(consequent_4);
                else $$render(alternate_1, false);
              },
              $$elseif
            );
          }
        };
        if_block(node_4, ($$render) => {
          if ($$props.chart.type === "hierarchy") $$render(consequent_3);
          else $$render(alternate, false);
        });
      }
      append($$anchor2, fragment_1);
    };
    var alternate_2 = ($$anchor2) => {
      var span = root_10();
      append($$anchor2, span);
    };
    if_block(node, ($$render) => {
      if ($showCharts()) $$render(consequent_6);
      else $$render(alternate_2, false);
    });
  }
  var node_5 = sibling(node, 2);
  snippet(node_5, () => $$props.children ?? noop);
  var button = sibling(node_5, 2);
  button.__click = () => {
    showCharts.update((v) => !v);
  };
  var text2 = child(button, true);
  reset(button);
  reset(div);
  var div_1 = sibling(div, 2);
  var node_6 = child(div_1);
  {
    var consequent_11 = ($$anchor2) => {
      var fragment_8 = comment();
      var node_7 = first_child(fragment_8);
      {
        var consequent_7 = ($$anchor3) => {
          BarChart2($$anchor3, {
            get chart() {
              return $$props.chart;
            },
            get width() {
              return get(width);
            }
          });
        };
        var alternate_3 = ($$anchor3, $$elseif) => {
          {
            var consequent_8 = ($$anchor4) => {
              HierarchyContainer($$anchor4, {
                get chart() {
                  return $$props.chart;
                },
                get width() {
                  return get(width);
                }
              });
            };
            var alternate_4 = ($$anchor4, $$elseif2) => {
              {
                var consequent_9 = ($$anchor5) => {
                  LineChart2($$anchor5, {
                    get chart() {
                      return $$props.chart;
                    },
                    get width() {
                      return get(width);
                    }
                  });
                };
                var alternate_5 = ($$anchor5, $$elseif3) => {
                  {
                    var consequent_10 = ($$anchor6) => {
                      ScatterPlot2($$anchor6, {
                        get chart() {
                          return $$props.chart;
                        },
                        get width() {
                          return get(width);
                        }
                      });
                    };
                    if_block(
                      $$anchor5,
                      ($$render) => {
                        if ($$props.chart.type === "scatterplot") $$render(consequent_10);
                      },
                      $$elseif3
                    );
                  }
                };
                if_block(
                  $$anchor4,
                  ($$render) => {
                    if ($$props.chart.type === "linechart") $$render(consequent_9);
                    else $$render(alternate_5, false);
                  },
                  $$elseif2
                );
              }
            };
            if_block(
              $$anchor3,
              ($$render) => {
                if ($$props.chart.type === "hierarchy") $$render(consequent_8);
                else $$render(alternate_4, false);
              },
              $$elseif
            );
          }
        };
        if_block(node_7, ($$render) => {
          if ($$props.chart.type === "barchart") $$render(consequent_7);
          else $$render(alternate_3, false);
        });
      }
      append($$anchor2, fragment_8);
    };
    if_block(node_6, ($$render) => {
      if (get(width)) $$render(consequent_11);
    });
  }
  reset(div_1);
  template_effect(() => {
    set_text(text2, $showCharts() ? "\u25BC" : "\u25C0");
    div_1.hidden = !$showCharts();
  });
  bind_element_size(div_1, "clientWidth", ($$value) => set(width, $$value));
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// node_modules/svelte/src/internal/flags/legacy.js
enable_legacy_mode_flag();

// src/charts/SelectCombobox.svelte
var id = 0;
var on_keydown = (event2, key_action) => {
  const action2 = key_action(event2);
  if (action2) {
    event2.preventDefault();
    action2();
  }
};
var on_mousedown = (ev, actions, option) => {
  if (ev.button === 0) {
    actions.select(get(option));
  }
};
var root_112 = template(`<li role="option"> </li>`);
var root11 = template(`<span class="svelte-qt53xf"><button type="button" role="combobox" class="muted"> </button> <ul role="listbox" class="svelte-qt53xf"></ul></span>`);
function SelectCombobox($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 15);
  let hidden = state(true);
  let index3 = state(proxy2($$props.options.indexOf(value())));
  let ul = state(void 0);
  id += 1;
  const listbox_id = `combobox-listbox-${id.toString()}`;
  const SEPARATOR = ",";
  let values = user_derived(() => value().split(SEPARATOR));
  user_effect(() => {
    if (!get(hidden) && get(index3)) {
      get(ul)?.children[get(index3)]?.scrollIntoView({ block: "nearest", inline: "nearest" });
    }
  });
  const actions = {
    /** Close the popup list. */
    close: () => {
      set(hidden, true);
    },
    /** Find the first element matching the typed letter and focus it. */
    find_letter: (key2, event2) => {
      const match = $$props.options.findIndex((o) => o.toLowerCase().startsWith(key2));
      if (match > -1) {
        event2.stopPropagation();
        set(index3, match, true);
        set(hidden, false);
      }
    },
    /** Focus the first element and open if not open yet. */
    first: () => {
      set(index3, 0);
      set(hidden, false);
    },
    /** Focus the last element and open if not open yet. */
    last: () => {
      set(index3, 0);
      set(hidden, false);
    },
    /** Focus the previous element in the popup. */
    next: () => {
      set(index3, get(index3) === 0 ? $$props.options.length - 1 : get(index3) - 1, true);
    },
    /** Open the popup list. */
    open: () => {
      set(hidden, false);
    },
    /** Focus the previous element in the popup. */
    previous: () => {
      set(index3, get(index3) === $$props.options.length - 1 ? 0 : get(index3) + 1, true);
    },
    /** Select the given or the focused element in the options list. */
    select: (o) => {
      const option = o ?? $$props.options[get(index3)];
      if (option != null) {
        if ($$props.multiple_select != null && $$props.multiple_select(option) && get(values).every($$props.multiple_select)) {
          value(get(values).includes(option) ? get(values).filter((v) => v !== option).join(SEPARATOR) : [...get(values), option].join(SEPARATOR));
        } else {
          value(option);
        }
        set(index3, $$props.options.indexOf(option), true);
        set(hidden, true);
      }
    },
    /** Toggle the popup list. */
    toggle: () => {
      set(hidden, !get(hidden));
    }
  };
  function key_action(event2) {
    const { key: key2 } = event2;
    const modifier = event2.altKey || event2.ctrlKey || event2.metaKey;
    if (/^[\w]$/.exec(key2) && !modifier) {
      return actions.find_letter.bind(null, key2, event2);
    }
    if (key2 === "Home") {
      return actions.first;
    }
    if (key2 === "End") {
      return actions.last;
    }
    if ((key2 === "Enter" || key2 === " ") && !get(hidden)) {
      return actions.select;
    }
    if (key2 === "Escape" && !get(hidden)) {
      return actions.close;
    }
    if (key2 === "ArrowUp") {
      return get(hidden) ? actions.open : actions.next;
    }
    if (key2 === "ArrowDown") {
      return get(hidden) ? actions.open : actions.previous;
    }
    return null;
  }
  var span = root11();
  var button = child(span);
  set_attribute(button, "aria-controls", listbox_id);
  button.__click = function(...$$args) {
    actions.toggle?.apply(this, $$args);
  };
  button.__keydown = [on_keydown, key_action];
  var text2 = child(button, true);
  reset(button);
  var ul_1 = sibling(button, 2);
  set_attribute(ul_1, "id", listbox_id);
  each(ul_1, 21, () => $$props.options, index, ($$anchor2, option, i2) => {
    var li = root_112();
    li.__mousedown = [on_mousedown, actions, option];
    let classes;
    var text_1 = child(li, true);
    reset(li);
    template_effect(
      ($0, $1, $2) => {
        set_attribute(li, "aria-selected", $0);
        classes = set_class(li, 1, "svelte-qt53xf", null, classes, $1);
        set_text(text_1, $2);
      },
      [
        () => get(values).includes(get(option)),
        () => ({ current: i2 === get(index3) }),
        () => $$props.description(get(option))
      ]
    );
    append($$anchor2, li);
  });
  reset(ul_1);
  bind_this(ul_1, ($$value) => set(ul, $$value), () => get(ul));
  reset(span);
  template_effect(
    ($0) => {
      set_attribute(button, "aria-expanded", !get(hidden));
      set_text(text2, $0);
      ul_1.hidden = get(hidden);
    },
    [() => $$props.description(value())]
  );
  event("blur", button, function(...$$args) {
    actions.close?.apply(this, $$args);
  });
  append($$anchor, span);
  pop();
}
delegate(["click", "keydown", "mousedown"]);

// src/charts/ConversionAndInterval.svelte
var root12 = template(`<!> <!>`, 1);
function ConversionAndInterval($$anchor, $$props) {
  push($$props, false);
  const [$$stores, $$cleanup] = setup_stores();
  const $conversion = () => store_get(conversion, "$conversion", $$stores);
  const $conversions = () => store_get(conversions, "$conversions", $$stores);
  const $interval = () => store_get(interval, "$interval", $$stores);
  const conversion_description = (option) => {
    switch (option) {
      case "at_cost":
        return _("At Cost");
      case "at_value":
        return _("At Market Value");
      case "units":
        return _("Units");
      default:
        return format(_("Converted to %(currency)s"), { currency: option });
    }
  };
  const is_currency_conversion = (option) => !["at_cost", "at_value", "units"].includes(option);
  init2();
  var fragment = root12();
  var node = first_child(fragment);
  SelectCombobox(node, {
    get options() {
      return $conversions();
    },
    description: conversion_description,
    multiple_select: is_currency_conversion,
    get value() {
      mark_store_binding();
      return $conversion();
    },
    set value($$value) {
      store_set(conversion, $$value);
    },
    $$legacy: true
  });
  var node_1 = sibling(node, 2);
  SelectCombobox(node_1, {
    options: INTERVALS,
    description: (o) => intervalLabel(getInterval(o)),
    get value() {
      mark_store_binding();
      return $interval();
    },
    set value($$value) {
      store_set(interval, $$value);
    },
    $$legacy: true
  });
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/charts/ChartSwitcher.svelte
var on_click2 = (__1, $lastActiveChartName, chart) => {
  store_set(lastActiveChartName, get(chart).name);
};
var root_33 = template(`<button type="button"> </button>`);
var root_113 = template(`<!> <div class="svelte-13m80wt"></div>`, 1);
function ChartSwitcher($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $lastActiveChartName = () => store_get(lastActiveChartName, "$lastActiveChartName", $$stores);
  const $showCharts = () => store_get(showCharts, "$showCharts", $$stores);
  let active_chart = user_derived(() => $$props.charts.find((c) => c.name === $lastActiveChartName()) ?? $$props.charts[0]);
  let shortcutPrevious = user_derived(() => (index3) => {
    const current = get(active_chart) ? $$props.charts.indexOf(get(active_chart)) : -1;
    return index3 === (current - 1 + $$props.charts.length) % $$props.charts.length ? { key: "C", note: _("Previous") } : void 0;
  });
  let shortcutNext = user_derived(() => (index3) => {
    const current = get(active_chart) ? $$props.charts.indexOf(get(active_chart)) : -1;
    return index3 === (current + 1 + $$props.charts.length) % $$props.charts.length ? { key: "c", note: _("Next") } : void 0;
  });
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var fragment_1 = root_113();
      var node_1 = first_child(fragment_1);
      Chart(node_1, {
        get chart() {
          return get(active_chart);
        },
        children: ($$anchor3, $$slotProps) => {
          ConversionAndInterval($$anchor3, {});
        },
        $$slots: { default: true }
      });
      var div = sibling(node_1, 2);
      each(div, 21, () => $$props.charts, index, ($$anchor3, chart, index3) => {
        var button = root_33();
        let classes;
        button.__click = [on_click2, $lastActiveChartName, chart];
        var text2 = child(button, true);
        reset(button);
        action(button, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => get(shortcutPrevious)(index3));
        action(button, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => get(shortcutNext)(index3));
        template_effect(
          ($0) => {
            classes = set_class(button, 1, "unset svelte-13m80wt", null, classes, $0);
            set_text(text2, get(chart).name);
          },
          [
            () => ({
              selected: get(chart) === get(active_chart)
            })
          ]
        );
        append($$anchor3, button);
      });
      reset(div);
      template_effect(() => div.hidden = !$showCharts());
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if (get(active_chart)) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/charts/context.ts
var operatingCurrenciesWithConversion = derived2(
  [operating_currency, currencies, conversion],
  ([$operating_currency, $currencies, $conversion]) => $currencies.includes($conversion) && !$operating_currency.includes($conversion) ? [...$operating_currency, $conversion] : $operating_currency
);
var chartContext = derived2(
  [operatingCurrenciesWithConversion, currentDateFormat],
  ([$operatingCurrenciesWithConversion, $currentDateFormat]) => ({
    currencies: $operatingCurrenciesWithConversion,
    dateFormat: $currentDateFormat
  })
);

// src/stores/accounts.ts
var collapse_account = derived2(fava_options, ($fava_options) => {
  const matchers = $fava_options.collapse_pattern.map((p) => new RegExp(p));
  return (name3) => matchers.some((p) => p.test(name3));
});
var invert_account = derived2(
  [fava_options, options],
  ([$fava_options, $options]) => $fava_options.invert_income_liabilities_equity ? (name3) => name3.startsWith($options.name_income) || name3.startsWith($options.name_liabilities) || name3.startsWith($options.name_equity) || name3 === _("Net Profit") : () => false
);
var is_closed_account = derived2(
  [account_details],
  ([$account_details]) => (name3, date4) => {
    const close_date = $account_details[name3]?.close_date;
    if (!close_date) {
      return false;
    }
    return date4 === null ? true : close_date < date4;
  }
);

// src/tree-table/helpers.ts
var key = Symbol("tree-table");
var setTreeTableContext = (ctx2) => setContext(key, ctx2);
var getTreeTableContext = () => getContext(key);
var get_not_shown = derived2(
  [fava_options, accounts, is_closed_account],
  ([$fava_options, $accounts, $is_closed_account]) => (node, end) => {
    const {
      show_accounts_with_zero_balance,
      show_accounts_with_zero_transactions,
      show_closed_accounts
    } = $fava_options;
    const not_shown = /* @__PURE__ */ new Set();
    const should_show_recursive = (n) => {
      if (
        // We need to evaluate this for all descendants recursively
        // the .map().some() ensures it does not short-circuit
        n.children.map(should_show_recursive).some((b) => b) || !is_empty(n.balance_children)
      ) {
        return true;
      }
      if (!$accounts.includes(n.account) || !show_closed_accounts && $is_closed_account(n.account, end) || !show_accounts_with_zero_balance && is_empty(n.balance) || !show_accounts_with_zero_transactions && !n.has_txns) {
        not_shown.add(n.account);
        return false;
      }
      return true;
    };
    should_show_recursive(node);
    return not_shown;
  }
);
function get_collapsed(root68, $collapse_account) {
  const s = /* @__PURE__ */ new Set();
  const get_collapsed_recursive = ({ children: children2, account: account2 }) => {
    if (children2.length && $collapse_account(account2)) {
      s.add(account2);
    }
    children2.forEach(get_collapsed_recursive);
  };
  get_collapsed_recursive(root68);
  return s;
}

// src/tree-table/AccountCellHeader.svelte
var root_114 = template(`<button type="button" class="link svelte-1ihav4y"> </button>`);
var root13 = template(`<span class="svelte-1ihav4y"><!></span>`);
function AccountCellHeader($$anchor, $$props) {
  push($$props, false);
  const [$$stores, $$cleanup] = setup_stores();
  const $toggled = () => store_get(toggled, "$toggled", $$stores);
  const { toggled } = getTreeTableContext();
  const help_title = _("Hold Shift while clicking to expand all children.\nHold Ctrl or Cmd while clicking to expand one level.");
  init2();
  var span = root13();
  set_attribute(span, "title", help_title);
  var node = child(span);
  {
    var consequent = ($$anchor2) => {
      var button = root_114();
      button.__click = () => {
        toggled.set(/* @__PURE__ */ new Set());
      };
      var text2 = child(button, true);
      reset(button);
      template_effect(
        ($0, $1) => {
          set_attribute(button, "title", $0);
          set_text(text2, $1);
        },
        [
          () => _("Expand all accounts"),
          () => _("Expand all")
        ],
        derived_safe_equal
      );
      append($$anchor2, button);
    };
    if_block(node, ($$render) => {
      if ($toggled().size) $$render(consequent);
    });
  }
  reset(span);
  append($$anchor, span);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/lib/account.ts
function parent(name3) {
  const parentEnd = name3.lastIndexOf(":");
  return parentEnd > 0 ? name3.slice(0, parentEnd) : "";
}
function leaf(name3) {
  const parentEnd = name3.lastIndexOf(":");
  return parentEnd > 0 ? name3.slice(parentEnd + 1) : name3;
}
function isDescendant(name3, of) {
  if (of === "") {
    return true;
  }
  return name3 === of || name3.startsWith(`${of}:`);
}

// src/sidebar/AccountIndicator.svelte
var root_24 = template(`<span title="The last entry is a passing balance check."></span>`);
var root_34 = template(`<copyable-text></copyable-text>`, 2);
var root_42 = template(`<span></span>`);
var root_115 = template(`<!> <!>`, 1);
function AccountIndicator($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $account_details = () => store_get(account_details, "$account_details", $$stores);
  const $fava_options = () => store_get(fava_options, "$fava_options", $$stores);
  let small = prop($$props, "small", 3, false);
  let details = user_derived(() => $account_details()[$$props.account]);
  let status = user_derived(() => get(details)?.uptodate_status);
  let balance = user_derived(() => get(details)?.balance_string ?? "");
  let last_entry = user_derived(() => get(details)?.last_entry);
  let last_account_activity = user_derived(() => get(last_entry) ? timeDay.count(get(last_entry).date, /* @__PURE__ */ new Date()) : 0);
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent_2 = ($$anchor2) => {
      var fragment_1 = root_115();
      var node_1 = first_child(fragment_1);
      {
        var consequent = ($$anchor3) => {
          var span = root_24();
          let classes;
          template_effect(($0) => classes = set_class(span, 1, "status-indicator status-green svelte-eoatdy", null, classes, $0), [() => ({ small: small() })]);
          append($$anchor3, span);
        };
        var alternate = ($$anchor3) => {
          var copyable_text = root_34();
          let classes_1;
          template_effect(() => set_custom_element_data(copyable_text, "title", `${get(status) === "yellow" ? "The last entry is not a balance check." : "The last entry is a failing balance check."}

Click to copy the balance directives to the clipboard:

${get(balance)}`));
          template_effect(() => set_custom_element_data(copyable_text, "data-clipboard-text", get(balance)));
          template_effect(($0) => classes_1 = set_class(copyable_text, 1, `status-indicator status-${get(status) ?? ""}`, "svelte-eoatdy", classes_1, $0), [() => ({ small: small() })]);
          append($$anchor3, copyable_text);
        };
        if_block(node_1, ($$render) => {
          if (get(status) === "green") $$render(consequent);
          else $$render(alternate, false);
        });
      }
      var node_2 = sibling(node_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var span_1 = root_42();
          let classes_2;
          template_effect(
            ($0) => {
              classes_2 = set_class(span_1, 1, "status-indicator status-gray svelte-eoatdy", null, classes_2, $0);
              set_attribute(span_1, "title", `This account has not been updated in a while. (${get(last_account_activity) ?? ""} days ago)`);
            },
            [() => ({ small: small() })]
          );
          append($$anchor3, span_1);
        };
        if_block(node_2, ($$render) => {
          if (get(last_account_activity) > $fava_options().uptodate_indicator_grey_lookback_days) $$render(consequent_1);
        });
      }
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if (get(status)) $$render(consequent_2);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/tree-table/AccountCell.svelte
var root_116 = template(`<button type="button" class="unset svelte-c3bl36"> </button>`);
var root14 = template(`<span class="droptarget svelte-c3bl36"><!> <a class="account svelte-c3bl36"> </a> <!></span>`);
function AccountCell($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $toggled = () => store_get(toggled, "$toggled", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  const { toggled } = getTreeTableContext();
  let account2 = user_derived(() => $$props.node.account), children2 = user_derived(() => $$props.node.children);
  let on_click12 = user_derived(() => (event2) => {
    toggled.update((t4) => {
      const new_t = new Set(t4);
      const is_toggled = new_t.has(get(account2));
      if (is_toggled) {
        new_t.delete(get(account2));
      } else {
        new_t.add(get(account2));
      }
      if (event2.shiftKey) {
        const toggle_all = (n) => {
          if (is_toggled) {
            new_t.delete(n.account);
          } else {
            new_t.add(n.account);
          }
          n.children.filter((c) => c.children.length > 0).forEach(toggle_all);
        };
        get(children2).forEach(toggle_all);
      }
      if (is_toggled && (event2.ctrlKey || event2.metaKey)) {
        get(children2).filter((c) => c.children.length > 0).forEach((n) => {
          new_t.add(n.account);
        });
      }
      return new_t;
    });
  });
  var span = root14();
  var node_1 = child(span);
  {
    var consequent = ($$anchor2) => {
      var button = root_116();
      button.__click = function(...$$args) {
        get(on_click12)?.apply(this, $$args);
      };
      var text2 = child(button, true);
      reset(button);
      template_effect(($0) => set_text(text2, $0), [
        () => $toggled().has(get(account2)) ? "\u25B8" : "\u25BE"
      ]);
      append($$anchor2, button);
    };
    if_block(node_1, ($$render) => {
      if (get(children2).length > 0) $$render(consequent);
    });
  }
  var a = sibling(node_1, 2);
  var text_1 = child(a, true);
  reset(a);
  var node_2 = sibling(a, 2);
  AccountIndicator(node_2, {
    get account() {
      return get(account2);
    },
    small: true
  });
  reset(span);
  template_effect(
    ($0, $1) => {
      set_attribute(span, "data-account-name", get(account2));
      set_attribute(a, "href", $0);
      set_text(text_1, $1);
    },
    [
      () => $urlForAccount()(get(account2)),
      () => leaf(get(account2))
    ]
  );
  append($$anchor, span);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/tree-table/Diff.svelte
var root15 = template(`<br> <span> </span>`, 1);
function Diff($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  var fragment = root15();
  var span = sibling(first_child(fragment), 2);
  let classes;
  var text2 = child(span);
  reset(span);
  template_effect(
    ($0, $1, $2) => {
      set_attribute(span, "title", $0);
      classes = set_class(span, 1, "svelte-16zx9ty", null, classes, $1);
      set_text(text2, `(${$2 ?? ""})`);
    },
    [
      () => $ctx().amount($$props.num, $$props.currency),
      () => ({ positive: $$props.diff > 0 }),
      () => $ctx().num($$props.diff, $$props.currency)
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/tree-table/IntervalTreeTableNode.svelte
var root_25 = template(`<span> </span> <!> <br>`, 1);
var root_53 = template(`<span> </span> <!> <br>`, 1);
var root_117 = template(`<span><!> <!></span>`);
var root_64 = template(`<ol></ol>`);
var root16 = template(`<li><p><!> <!></p> <!></li>`);
function IntervalTreeTableNode_1($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $toggled = () => store_get(toggled, "$toggled", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const { toggled, not_shown } = getTreeTableContext();
  let node = user_derived(() => $$props.nodes[0]);
  let account2 = user_derived(() => get(node).account), children2 = user_derived(() => get(node).children);
  let account_budgets = user_derived(() => $$props.budgets[get(account2)]);
  let is_toggled = user_derived(() => $toggled().has(get(account2)));
  var li = root16();
  var p = child(li);
  var node_1 = child(p);
  AccountCell(node_1, {
    get node() {
      return get(node);
    }
  });
  var node_2 = sibling(node_1, 2);
  each(node_2, 17, () => $$props.nodes, index, ($$anchor2, n, index3) => {
    var span = root_117();
    const account_budget2 = user_derived(() => get(account_budgets)?.[index3]);
    const has_balance = user_derived(() => !is_empty(get(n).balance) || get(account_budget2) != null && !is_empty(get(account_budget2).budget));
    const show_balance = user_derived(() => !get(is_toggled) && get(has_balance));
    const shown_balance = user_derived(() => get(show_balance) ? get(n).balance : get(n).balance_children);
    const shown_budget = user_derived(() => get(show_balance) ? get(account_budget2)?.budget : get(account_budget2)?.budget_children);
    let classes;
    var node_3 = child(span);
    each(node_3, 17, () => Object.entries(get(shown_balance)), index, ($$anchor3, $$item) => {
      let currency = () => get($$item)[0];
      let number7 = () => get($$item)[1];
      var fragment = root_25();
      const budget = user_derived(() => get(shown_budget)?.[currency()]);
      var span_1 = first_child(fragment);
      var text2 = child(span_1, true);
      reset(span_1);
      var node_4 = sibling(span_1, 2);
      {
        var consequent = ($$anchor4) => {
          const expression = user_derived(() => get(budget) - number7());
          Diff($$anchor4, {
            get diff() {
              return get(expression);
            },
            get num() {
              return get(budget);
            },
            get currency() {
              return currency();
            }
          });
        };
        if_block(node_4, ($$render) => {
          if (get(budget)) $$render(consequent);
        });
      }
      next(2);
      template_effect(
        ($0, $1) => {
          set_attribute(span_1, "title", $0);
          set_text(text2, $1);
        },
        [
          () => $currency_name()(currency()),
          () => $ctx().amount(number7(), currency())
        ]
      );
      append($$anchor3, fragment);
    });
    var node_5 = sibling(node_3, 2);
    {
      var consequent_1 = ($$anchor3) => {
        var fragment_2 = comment();
        var node_6 = first_child(fragment_2);
        each(node_6, 17, () => Object.entries(get(shown_budget)).filter(([c]) => !(get(shown_balance)[c] ?? 0)), index, ($$anchor4, $$item) => {
          let currency = () => get($$item)[0];
          let budget = () => get($$item)[1];
          var fragment_3 = root_53();
          var span_2 = first_child(fragment_3);
          var text_1 = child(span_2, true);
          reset(span_2);
          var node_7 = sibling(span_2, 2);
          Diff(node_7, {
            get diff() {
              return budget();
            },
            get num() {
              return budget();
            },
            get currency() {
              return currency();
            }
          });
          next(2);
          template_effect(
            ($0, $1) => {
              set_attribute(span_2, "title", $0);
              set_text(text_1, $1);
            },
            [
              () => $currency_name()(currency()),
              () => $ctx().amount(0, currency())
            ]
          );
          append($$anchor4, fragment_3);
        });
        append($$anchor3, fragment_2);
      };
      if_block(node_5, ($$render) => {
        if (get(shown_budget)) $$render(consequent_1);
      });
    }
    reset(span);
    template_effect(($0) => classes = set_class(span, 1, "num other", null, classes, $0), [
      () => ({
        dimmed: !get(is_toggled) && !get(has_balance)
      })
    ]);
    append($$anchor2, span);
  });
  reset(p);
  var node_8 = sibling(p, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ol = root_64();
      each(ol, 23, () => get(children2), (child2) => child2.account, ($$anchor3, child2, index3) => {
        var fragment_4 = comment();
        var node_9 = first_child(fragment_4);
        {
          var consequent_2 = ($$anchor4) => {
            const expression_1 = user_derived(() => $$props.nodes.map((n) => n.children[get(index3)]));
            IntervalTreeTableNode_1($$anchor4, {
              get nodes() {
                return get(expression_1);
              },
              get budgets() {
                return $$props.budgets;
              }
            });
          };
          if_block(node_9, ($$render) => {
            if (!$not_shown().has(get(child2).account)) $$render(consequent_2);
          });
        }
        append($$anchor3, fragment_4);
      });
      reset(ol);
      append($$anchor2, ol);
    };
    if_block(node_8, ($$render) => {
      if (!get(is_toggled) && get(children2).some((n) => !$not_shown().has(n.account))) $$render(consequent_3);
    });
  }
  reset(li);
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/tree-table/IntervalTreeTable.svelte
var root_118 = template(`<span class="num other"><a> </a></span>`);
var root17 = template(`<ol class="flex-table tree-table-new svelte-o61rw3"><li class="head"><p><!> <!></p></li> <!></ol>`);
function IntervalTreeTable($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $collapse_account = () => store_get(collapse_account, "$collapse_account", $$stores);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const $get_not_shown = () => store_get(get_not_shown, "$get_not_shown", $$stores);
  const $currentTimeFilterDateFormat = () => store_get(currentTimeFilterDateFormat, "$currentTimeFilterDateFormat", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  const toggled = writable(get_collapsed($$props.trees[0], $collapse_account()));
  const not_shown = writable(/* @__PURE__ */ new Set());
  setTreeTableContext({ toggled, not_shown });
  user_effect(() => {
    store_set(not_shown, intersection(...$$props.trees.map((n, index3) => $get_not_shown()(n, $$props.dates[index3]?.end ?? null))));
  });
  let account2 = user_derived(() => $$props.trees[0].account);
  let start_date = user_derived(() => $$props.accumulate ? min($$props.dates, (d) => d.begin) : void 0);
  let start_date_filter = user_derived(() => get(start_date) ? $currentTimeFilterDateFormat()(get(start_date)) : void 0);
  let time_filters = user_derived(() => $$props.dates.map((date_range2) => {
    const title = $currentTimeFilterDateFormat()(date_range2.begin);
    return get(start_date_filter) != null ? [
      title,
      `${get(start_date_filter)}-${title}`
    ] : [title, title];
  }));
  var ol = root17();
  var li = child(ol);
  var p = child(li);
  var node = child(p);
  AccountCellHeader(node, {});
  var node_1 = sibling(node, 2);
  each(node_1, 17, () => get(time_filters), index, ($$anchor2, $$item) => {
    let title = () => get($$item)[0];
    let time = () => get($$item)[1];
    var span = root_118();
    var a = child(span);
    var text2 = child(a, true);
    reset(a);
    reset(span);
    template_effect(
      ($0) => {
        set_attribute(a, "href", $0);
        set_text(text2, title());
      },
      [
        () => $urlForAccount()(get(account2), { time: time() })
      ]
    );
    append($$anchor2, span);
  });
  reset(p);
  reset(li);
  var node_2 = sibling(li, 2);
  IntervalTreeTableNode_1(node_2, {
    get nodes() {
      return $$props.trees;
    },
    get budgets() {
      return $$props.budgets;
    }
  });
  reset(ol);
  append($$anchor, ol);
  pop();
  $$cleanup();
}

// src/reports/accounts/AccountReport.svelte
var root_26 = template(`<a> </a>`);
var root_43 = template(`<a> </a>`);
var root_65 = template(`<a> </a>`);
var root18 = template(`<!> <div class="droptarget"><div class="headerline"><h3><!></h3> <h3><!></h3> <h3><!></h3></div> <!></div>`, 1);
function AccountReport($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $chartContext = () => store_get(chartContext, "$chartContext", $$stores);
  const $interval = () => store_get(interval, "$interval", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  let accumulate = user_derived(() => $$props.report_type === "balances");
  let chartData = user_derived(() => parseChartData($$props.charts, $chartContext()).unwrap_or(null));
  let interval_label = user_derived(() => intervalLabel($interval()).toLowerCase());
  var fragment = root18();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      ChartSwitcher($$anchor2, {
        get charts() {
          return get(chartData);
        }
      });
    };
    if_block(node, ($$render) => {
      if (get(chartData)) $$render(consequent);
    });
  }
  var div = sibling(node, 2);
  var div_1 = child(div);
  var h3 = child(div_1);
  var node_1 = child(h3);
  {
    var consequent_1 = ($$anchor2) => {
      var a = root_26();
      var text2 = child(a, true);
      reset(a);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a, "href", $0);
          set_attribute(a, "title", $1);
          set_text(text2, $2);
        },
        [
          () => $urlForAccount()($$props.account),
          () => _("Journal of all entries for this Account and Sub-Accounts"),
          () => _("Account Journal")
        ]
      );
      append($$anchor2, a);
    };
    var alternate = ($$anchor2) => {
      var text_1 = text();
      template_effect(($0) => set_text(text_1, $0), [() => _("Account Journal")]);
      append($$anchor2, text_1);
    };
    if_block(node_1, ($$render) => {
      if ($$props.report_type !== "journal") $$render(consequent_1);
      else $$render(alternate, false);
    });
  }
  reset(h3);
  var h3_1 = sibling(h3, 2);
  var node_2 = child(h3_1);
  {
    var consequent_2 = ($$anchor2) => {
      var a_1 = root_43();
      var text_2 = child(a_1);
      reset(a_1);
      template_effect(
        ($0, $1) => {
          set_attribute(a_1, "href", $0);
          set_text(text_2, `${$1 ?? ""} (${get(interval_label) ?? ""})`);
        },
        [
          () => $urlForAccount()($$props.account, { r: "changes" }),
          () => _("Changes")
        ]
      );
      append($$anchor2, a_1);
    };
    var alternate_1 = ($$anchor2) => {
      var text_3 = text();
      template_effect(($0) => set_text(text_3, `${$0 ?? ""} (${get(interval_label) ?? ""})`), [() => _("Changes")]);
      append($$anchor2, text_3);
    };
    if_block(node_2, ($$render) => {
      if ($$props.report_type !== "changes") $$render(consequent_2);
      else $$render(alternate_1, false);
    });
  }
  reset(h3_1);
  var h3_2 = sibling(h3_1, 2);
  var node_3 = child(h3_2);
  {
    var consequent_3 = ($$anchor2) => {
      var a_2 = root_65();
      var text_4 = child(a_2);
      reset(a_2);
      template_effect(
        ($0, $1) => {
          set_attribute(a_2, "href", $0);
          set_text(text_4, `${$1 ?? ""} (${get(interval_label) ?? ""})`);
        },
        [
          () => $urlForAccount()($$props.account, { r: "balances" }),
          () => _("Balances")
        ]
      );
      append($$anchor2, a_2);
    };
    var alternate_2 = ($$anchor2) => {
      var text_5 = text();
      template_effect(($0) => set_text(text_5, `${$0 ?? ""} (${get(interval_label) ?? ""})`), [() => _("Balances")]);
      append($$anchor2, text_5);
    };
    if_block(node_3, ($$render) => {
      if ($$props.report_type !== "balances") $$render(consequent_3);
      else $$render(alternate_2, false);
    });
  }
  reset(h3_2);
  reset(div_1);
  var node_4 = sibling(div_1, 2);
  {
    var consequent_4 = ($$anchor2) => {
      var fragment_5 = comment();
      var node_5 = first_child(fragment_5);
      html(node_5, () => $$props.journal, false, false);
      append($$anchor2, fragment_5);
    };
    var alternate_3 = ($$anchor2, $$elseif) => {
      {
        var consequent_5 = ($$anchor3) => {
          IntervalTreeTable($$anchor3, {
            get trees() {
              return $$props.interval_balances;
            },
            get dates() {
              return $$props.dates;
            },
            get budgets() {
              return $$props.budgets;
            },
            get accumulate() {
              return get(accumulate);
            }
          });
        };
        if_block(
          $$anchor2,
          ($$render) => {
            if ($$props.interval_balances && is_non_empty($$props.interval_balances) && $$props.budgets && $$props.dates) $$render(consequent_5);
          },
          $$elseif
        );
      }
    };
    if_block(node_4, ($$render) => {
      if ($$props.report_type === "journal") $$render(consequent_4);
      else $$render(alternate_3, false);
    });
  }
  reset(div);
  template_effect(() => set_attribute(div, "data-account-name", $$props.account));
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/accounts/index.ts
var to_report_type = (s) => s === "balances" || s === "changes" ? s : "journal";
var account_report = new Route(
  "account",
  AccountReport,
  async (url) => {
    const [, account2 = ""] = getUrlPath(url)?.split("/") ?? [];
    const report_type = to_report_type(url.searchParams.get("r"));
    const res2 = await get3("account_report", {
      ...getURLFilters(url),
      a: account2,
      r: report_type
    });
    return { ...res2, account: account2, report_type };
  },
  (route) => {
    if (route.url) {
      const [, account2] = getUrlPath(route.url)?.split("/") ?? [];
      return `account:${account2 ?? "ERROR"}`;
    }
    throw new Error("Internal error: Expected route to have URL.");
  }
);

// src/sort/SortHeader.svelte
var on_click3 = (_2, sorter, $$props) => {
  sorter(sorter().switchColumn($$props.column));
};
var root19 = template(`<th data-sort=""> </th>`);
function SortHeader($$anchor, $$props) {
  push($$props, true);
  let sorter = prop($$props, "sorter", 15);
  var th = root19();
  th.__click = [on_click3, sorter, $$props];
  var text2 = child(th, true);
  reset(th);
  template_effect(() => {
    set_attribute(th, "data-order", $$props.column === sorter().column ? sorter().order : void 0);
    set_text(text2, $$props.column.name);
  });
  append($$anchor, th);
  pop();
}
delegate(["click"]);

// src/reports/commodities/CommodityTable.svelte
var root_27 = template(`<tr><td> </td><td class="num"> </td></tr>`);
var root20 = template(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function CommodityTable($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const columns3 = [
    new NumberColumn(_("Date"), (d) => d[0].valueOf()),
    new NumberColumn(_("Price"), (d) => d[1])
  ];
  let sorter = state(proxy2(new Sorter(columns3[0], "desc")));
  let sorted_prices = user_derived(() => get(sorter).sort($$props.prices));
  var table = root20();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 21, () => columns3, index, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return get(column);
      },
      get sorter() {
        return get(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get(sorted_prices), ([date4, value]) => date4, ($$anchor2, $$item) => {
    let date4 = () => get($$item)[0];
    let value = () => get($$item)[1];
    var tr_1 = root_27();
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var text_1 = child(td_1, true);
    reset(td_1);
    reset(tr_1);
    template_effect(
      ($0, $1) => {
        set_text(text2, $0);
        set_text(text_1, $1);
      },
      [
        () => day(date4()),
        () => $ctx().amount(value(), $$props.quote)
      ]
    );
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
  $$cleanup();
}

// src/reports/commodities/Commodities.svelte
var root_119 = template(`<div class="left"><h3> </h3> <!></div>`);
var root21 = template(`<!> <!>`, 1);
function Commodities($$anchor, $$props) {
  var fragment = root21();
  var node = first_child(fragment);
  ChartSwitcher(node, {
    get charts() {
      return $$props.charts;
    }
  });
  var node_1 = sibling(node, 2);
  each(node_1, 17, () => $$props.commodities, index, ($$anchor2, $$item) => {
    let base2 = () => get($$item).base;
    let quote = () => get($$item).quote;
    let prices = () => get($$item).prices;
    var div = root_119();
    var h3 = child(div);
    var text2 = child(h3);
    reset(h3);
    var node_2 = sibling(h3, 2);
    CommodityTable(node_2, {
      get prices() {
        return prices();
      },
      get quote() {
        return quote();
      }
    });
    reset(div);
    template_effect(() => set_text(text2, `${base2() ?? ""} / ${quote() ?? ""}`));
    append($$anchor2, div);
  });
  append($$anchor, fragment);
}

// src/reports/commodities/index.ts
var commodities2 = new Route(
  "commodities",
  Commodities,
  async (url) => get3("commodities", getURLFilters(url)).then((cs) => {
    const charts = cs.map(({ base: base2, quote, prices }) => {
      const name3 = `${base2} / ${quote}`;
      const values = prices.map((d) => ({ name: name3, date: d[0], value: d[1] }));
      return new LineChart(name3, [{ name: name3, values }], (c, d) => [
        domHelpers.t(`1 ${base2} = ${c.amount(d.value, quote)}`),
        domHelpers.em(day(d.date))
      ]);
    });
    return { commodities: cs, charts };
  }),
  () => _("Commodities")
);

// src/lib/fuzzy.ts
function fuzzytest(pattern, text2) {
  const casesensitive = pattern === pattern.toLowerCase();
  const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
  if (exact > -1) {
    return pattern.length ** 2;
  }
  let score2 = 0;
  let localScore = 0;
  let pindex = 0;
  for (const char of text2) {
    const search2 = pattern[pindex];
    if (char === search2 || char.toLowerCase() === search2) {
      pindex += 1;
      localScore += 1;
    } else {
      localScore = 0;
    }
    score2 += localScore;
  }
  return pindex === pattern.length ? score2 : 0;
}
function fuzzyfilter(pattern, suggestions) {
  if (!pattern) {
    return suggestions;
  }
  return suggestions.map((s) => [s, fuzzytest(pattern, s)]).filter(([, score2]) => score2 > 0).sort((a, b) => b[1] - a[1]).map(([s]) => s);
}
function fuzzywrap(pattern, text2) {
  if (!pattern) {
    return [["text", text2]];
  }
  const casesensitive = pattern === pattern.toLowerCase();
  const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
  if (exact > -1) {
    const before = text2.slice(0, exact);
    const match2 = text2.slice(exact, exact + pattern.length);
    const after = text2.slice(exact + pattern.length);
    const result2 = [];
    if (before) {
      result2.push(["text", before]);
    }
    result2.push(["match", match2]);
    if (after) {
      result2.push(["text", after]);
    }
    return result2;
  }
  let pindex = 0;
  let plain = null;
  let match = null;
  const result = [];
  for (const char of text2) {
    const search2 = pattern[pindex];
    if (char === search2 || char.toLowerCase() === search2) {
      match = match != null ? match + char : char;
      if (plain != null) {
        result.push(["text", plain]);
        plain = null;
      }
      pindex += 1;
    } else {
      plain = plain != null ? plain + char : char;
      if (match != null) {
        result.push(["match", match]);
        match = null;
      }
    }
  }
  if (pindex < pattern.length) {
    return [["text", text2]];
  }
  if (plain != null) {
    result.push(["text", plain]);
    plain = null;
  }
  if (match != null) {
    result.push(["match", match]);
    match = null;
  }
  return result;
}

// src/AutocompleteInput.svelte
var id2 = 0;
function keydown2(event2, filteredSuggestions, index3, hidden, select, input, $$props, expanded, value) {
  if (event2.key === "Enter") {
    const suggestion = get(filteredSuggestions)[get(index3)]?.suggestion;
    if (get(index3) > -1 && !get(hidden) && suggestion != null) {
      event2.preventDefault();
      select(suggestion);
    } else if (get(input)) {
      $$props.onEnter?.(get(input));
    }
  } else if (event2.key === " " && event2.ctrlKey) {
    set(hidden, false);
  } else if (event2.key === "Escape") {
    event2.stopPropagation();
    if (get(expanded)) {
      set(index3, -1);
      set(hidden, true);
    } else {
      value("");
    }
  } else if (event2.key === "ArrowUp") {
    event2.preventDefault();
    set(index3, get(index3) === 0 ? get(filteredSuggestions).length - 1 : get(index3) - 1);
  } else if (event2.key === "ArrowDown") {
    event2.preventDefault();
    set(index3, get(index3) === get(filteredSuggestions).length - 1 ? 0 : get(index3) + 1);
  }
}
var on_input = (_2, hidden) => {
  set(hidden, false);
};
var on_click4 = (__1, value, input, $$props) => {
  value("");
  if (get(input)) {
    $$props.onSelect?.(get(input));
  }
};
var root_120 = template(`<button type="button" class="muted round svelte-1puw1i1">\xD7</button>`);
var on_mousedown2 = (ev, mousedown, suggestion) => {
  mousedown(ev, suggestion());
};
var root_66 = template(`<span class="svelte-1puw1i1"> </span>`);
var root_35 = template(`<li role="option"></li>`);
var root_28 = template(`<ul role="listbox" class="svelte-1puw1i1"></ul>`);
var root22 = template(`<span><input type="text" autocomplete="off" role="combobox" class="svelte-1puw1i1"> <!> <!></span>`);
function AutocompleteInput($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 15), setSize = prop($$props, "setSize", 3, false), clearButton = prop($$props, "clearButton", 3, false);
  id2 += 1;
  const autocomple_id = `combobox-autocomplete-${id2.toString()}`;
  let hidden = state(true);
  let index3 = state(-1);
  let input = state(void 0);
  let size = user_derived(() => setSize() ? Math.max(value().length, $$props.placeholder.length) + 1 : void 0);
  let extractedValue = user_derived(() => get(input) && $$props.valueExtractor ? $$props.valueExtractor(value(), get(input)) : value());
  let filteredSuggestions = user_derived(() => {
    const filtered = fuzzyfilter(get(extractedValue), $$props.suggestions).slice(0, 30).map((suggestion) => ({
      suggestion,
      fuzzywrapped: fuzzywrap(get(extractedValue), suggestion)
    }));
    return filtered.length === 1 && filtered[0]?.suggestion === get(extractedValue) ? [] : filtered;
  });
  user_effect(() => {
    const msg = $$props.checkValidity ? $$props.checkValidity(value()) : "";
    get(input)?.setCustomValidity(msg);
  });
  user_pre_effect(() => {
    set(index3, Math.min(get(index3), get(filteredSuggestions).length - 1));
  });
  function select(suggestion) {
    value(get(input) && $$props.valueSelector ? $$props.valueSelector(suggestion, get(input)) : suggestion);
    if (get(input)) {
      $$props.onSelect?.(get(input));
    }
    set(hidden, true);
  }
  function mousedown(event2, suggestion) {
    if (event2.button === 0) {
      select(suggestion);
    }
  }
  let expanded = user_derived(() => !get(hidden) && get(filteredSuggestions).length > 0);
  var span = root22();
  var input_1 = child(span);
  remove_input_defaults(input_1);
  set_attribute(input_1, "aria-controls", autocomple_id);
  input_1.__input = [on_input, hidden];
  input_1.__keydown = [
    keydown2,
    filteredSuggestions,
    index3,
    hidden,
    select,
    input,
    $$props,
    expanded,
    value
  ];
  effect(() => bind_value(input_1, value));
  bind_this(input_1, ($$value) => set(input, $$value), () => get(input));
  action(input_1, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => $$props.key);
  var node = sibling(input_1, 2);
  {
    var consequent = ($$anchor2) => {
      var button = root_120();
      set_attribute(button, "tabindex", -1);
      button.__click = [on_click4, value, input, $$props];
      append($$anchor2, button);
    };
    if_block(node, ($$render) => {
      if (clearButton() && value()) $$render(consequent);
    });
  }
  var node_1 = sibling(node, 2);
  {
    var consequent_2 = ($$anchor2) => {
      var ul = root_28();
      set_attribute(ul, "id", autocomple_id);
      each(ul, 21, () => get(filteredSuggestions), index, ($$anchor3, $$item, i2) => {
        let fuzzywrapped = () => get($$item).fuzzywrapped;
        let suggestion = () => get($$item).suggestion;
        var li = root_35();
        li.__mousedown = [on_mousedown2, mousedown, suggestion];
        let classes;
        each(li, 21, fuzzywrapped, index, ($$anchor4, $$item2) => {
          let type = () => get($$item2)[0];
          let text2 = () => get($$item2)[1];
          var fragment = comment();
          var node_2 = first_child(fragment);
          {
            var consequent_1 = ($$anchor5) => {
              var text_1 = text();
              template_effect(() => set_text(text_1, text2()));
              append($$anchor5, text_1);
            };
            var alternate = ($$anchor5) => {
              var span_1 = root_66();
              var text_2 = child(span_1, true);
              reset(span_1);
              template_effect(() => set_text(text_2, text2()));
              append($$anchor5, span_1);
            };
            if_block(node_2, ($$render) => {
              if (type() === "text") $$render(consequent_1);
              else $$render(alternate, false);
            });
          }
          append($$anchor4, fragment);
        });
        reset(li);
        template_effect(
          ($0) => {
            set_attribute(li, "aria-selected", i2 === get(index3));
            classes = set_class(li, 1, "svelte-1puw1i1", null, classes, $0);
          },
          [() => ({ selected: i2 === get(index3) })]
        );
        append($$anchor3, li);
      });
      reset(ul);
      template_effect(() => ul.hidden = get(hidden));
      append($$anchor2, ul);
    };
    if_block(node_1, ($$render) => {
      if (get(filteredSuggestions).length) $$render(consequent_2);
    });
  }
  reset(span);
  template_effect(() => {
    set_class(span, 1, clsx2($$props.className), "svelte-1puw1i1");
    set_attribute(input_1, "aria-expanded", get(expanded));
    set_attribute(input_1, "placeholder", $$props.placeholder);
    input_1.required = $$props.required;
    set_attribute(input_1, "size", get(size));
  });
  event("blur", input_1, (event2) => {
    set(hidden, true);
    $$props.onBlur?.(event2.currentTarget);
  });
  event("focus", input_1, () => {
    set(hidden, false);
  });
  append($$anchor, span);
  pop();
}
delegate(["input", "keydown", "click", "mousedown"]);

// src/entry-forms/AccountInput.svelte
function AccountInput($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  const $is_closed_account = () => store_get(is_closed_account, "$is_closed_account", $$stores);
  let value = prop($$props, "value", 15);
  let checkValidity = user_derived(() => (val) => !$accounts().length || $accounts().includes(val) || $$props.required !== true && !val ? "" : _("Should be one of the declared accounts"));
  let parsed_date = user_derived(() => date($$props.date).unwrap_or(null));
  let account_suggestions = user_derived(() => $$props.suggestions ?? $accounts());
  let filtered_suggestions = user_derived(() => get(parsed_date) ? get(account_suggestions).filter((account2) => !$is_closed_account()(account2, get(parsed_date))) : get(account_suggestions));
  const expression = user_derived(() => _("Account"));
  AutocompleteInput($$anchor, {
    get placeholder() {
      return get(expression);
    },
    get className() {
      return $$props.className;
    },
    get checkValidity() {
      return get(checkValidity);
    },
    get required() {
      return $$props.required;
    },
    get suggestions() {
      return get(filtered_suggestions);
    },
    get value() {
      return value();
    },
    set value($$value) {
      value($$value);
    }
  });
  pop();
  $$cleanup();
}

// src/lib/paths.ts
function basename(filename) {
  const parts2 = filename.split(/\/|\\/);
  return parts2[parts2.length - 1] ?? "";
}
function ext(filename) {
  const match = /\.(\w+)$/.exec(filename);
  return match?.[1] ?? "";
}
function documentHasAccount(filename, account2) {
  const accountParts = account2.split(":").reverse();
  const folders = filename.split(/\/|\\/).reverse().slice(1);
  return accountParts.every((part, index3) => part === folders[index3]);
}

// src/lib/tree.ts
function stratify(data, id3, init4) {
  const root68 = { children: [], ...init4("") };
  const map2 = /* @__PURE__ */ new Map();
  map2.set("", root68);
  function addAccount(name3, datum2) {
    const existing = map2.get(name3);
    if (existing) {
      Object.assign(existing, init4(name3, datum2));
      return existing;
    }
    const node = { children: [], ...init4(name3, datum2) };
    map2.set(name3, node);
    const parentName = parent(name3);
    const parentNode = map2.get(parentName) ?? addAccount(parentName);
    parentNode.children.push(node);
    return node;
  }
  [...data].sort((a, b) => id3(a).localeCompare(id3(b))).forEach((datum2) => addAccount(id3(datum2), datum2));
  return root68;
}

// src/lib/focus.ts
var FOCUSABLE_ELEMENTS = [
  "a[href]",
  'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',
  "select:not([disabled]):not([aria-hidden])",
  "textarea:not([disabled]):not([aria-hidden])",
  "button:not([disabled]):not([aria-hidden])",
  "object",
  "[contenteditable]"
].join(", ");
function getFocusableElements(el) {
  return [...el.querySelectorAll(FOCUSABLE_ELEMENTS)];
}
function attemptFocus(el) {
  try {
    el.focus();
  } catch (e) {
  }
  return document.activeElement === el;
}

// src/modals/ModalBase.svelte
var root_121 = template(`<div class="overlay svelte-15o701a"><div class="background svelte-15o701a" aria-hidden="true"></div> <div class="content svelte-15o701a" role="dialog" aria-modal="true"><!> <button type="button" class="muted close svelte-15o701a">x</button></div></div>`);
function ModalBase($$anchor, $$props) {
  push($$props, true);
  let closeHandler = prop($$props, "closeHandler", 3, closeOverlay);
  const handleFocus = (el) => {
    const keydown3 = (ev) => {
      if (ev.key === "Tab") {
        const focusable = getFocusableElements(el);
        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        if (ev.shiftKey && document.activeElement === first && last) {
          ev.preventDefault();
          attemptFocus(last);
        } else if (!ev.shiftKey && document.activeElement === last && first) {
          ev.preventDefault();
          attemptFocus(first);
        }
      } else if (ev.key === "Escape") {
        ev.preventDefault();
        closeHandler()();
      }
    };
    document.addEventListener("keydown", keydown3);
    const selectorFocusEl = $$props.focus != null ? el.querySelector($$props.focus) : void 0;
    const focusEl = selectorFocusEl ?? getFocusableElements(el)[0];
    if (focusEl) {
      attemptFocus(focusEl);
    }
    return {
      destroy: () => {
        document.removeEventListener("keydown", keydown3);
      }
    };
  };
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_121();
      var div_1 = child(div);
      div_1.__click = function(...$$args) {
        closeHandler()?.apply(this, $$args);
      };
      var div_2 = sibling(div_1, 2);
      var node_1 = child(div_2);
      snippet(node_1, () => $$props.children);
      var button = sibling(node_1, 2);
      button.__click = function(...$$args) {
        closeHandler()?.apply(this, $$args);
      };
      reset(div_2);
      action(div_2, ($$node) => handleFocus?.($$node));
      reset(div);
      append($$anchor2, div);
    };
    if_block(node, ($$render) => {
      if ($$props.shown) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
delegate(["click"]);

// src/reports/documents/stores.ts
var selectedAccount = writable("");

// src/reports/documents/Accounts.svelte
var on_click5 = (ev, expanded) => {
  set(expanded, !get(expanded));
  ev.stopPropagation();
};
var root_29 = template(`<button type="button" class="unset toggle svelte-8xh817"> </button>`);
var on_click_1 = (_2, $selectedAccount, selected, $$props) => {
  store_set(selectedAccount, get(selected) ? "" : $$props.node.name);
};
var root_36 = template(`<span class="count svelte-8xh817"> </span>`);
var root_122 = template(`<p><!> <button type="button" class="unset leaf svelte-8xh817"> </button> <!></p>`);
var root_54 = template(`<li><!></li>`);
var root_44 = template(`<ul class="svelte-8xh817"></ul>`);
var root23 = template(`<!> <!>`, 1);
function Accounts_1($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $selectedAccount = () => store_get(selectedAccount, "$selectedAccount", $$stores);
  let expanded = state(true);
  let drag = state(false);
  let hasChildren = user_derived(() => $$props.node.children.length > 0);
  let selected = user_derived(() => $selectedAccount() === $$props.node.name);
  function dragenter(event2) {
    const types2 = event2.dataTransfer?.types ?? [];
    if (types2.includes("fava/filename")) {
      event2.preventDefault();
      set(drag, true);
    }
  }
  function drop2(event2) {
    event2.preventDefault();
    const filename = event2.dataTransfer?.getData("fava/filename");
    if (filename != null) {
      $$props.move({ account: $$props.node.name, filename });
      set(drag, false);
    }
  }
  var fragment = root23();
  var node_1 = first_child(fragment);
  {
    var consequent_2 = ($$anchor2) => {
      var p = root_122();
      let classes;
      var node_2 = child(p);
      {
        var consequent = ($$anchor3) => {
          var button = root_29();
          button.__click = [on_click5, expanded];
          var text2 = child(button, true);
          reset(button);
          template_effect(() => set_text(text2, get(expanded) ? "\u25BE" : "\u25B8"));
          append($$anchor3, button);
        };
        if_block(node_2, ($$render) => {
          if (get(hasChildren)) $$render(consequent);
        });
      }
      var button_1 = sibling(node_2, 2);
      button_1.__click = [
        on_click_1,
        $selectedAccount,
        selected,
        $$props
      ];
      var text_1 = child(button_1, true);
      reset(button_1);
      var node_3 = sibling(button_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var span = root_36();
          var text_2 = child(span, true);
          reset(span);
          template_effect(() => set_text(text_2, $$props.node.count));
          append($$anchor3, span);
        };
        if_block(node_3, ($$render) => {
          if ($$props.node.count > 0) $$render(consequent_1);
        });
      }
      reset(p);
      template_effect(
        ($0, $1) => {
          set_attribute(p, "title", $$props.node.name);
          classes = set_class(p, 1, "droptarget svelte-8xh817", null, classes, $0);
          set_attribute(p, "data-account-name", $$props.node.name);
          set_text(text_1, $1);
        },
        [
          () => ({
            selected: get(selected),
            drag: get(drag)
          }),
          () => leaf($$props.node.name)
        ]
      );
      event("dragenter", p, dragenter);
      event("dragover", p, dragenter);
      event("dragleave", p, () => {
        set(drag, false);
      });
      event("drop", p, drop2);
      append($$anchor2, p);
    };
    if_block(node_1, ($$render) => {
      if ($$props.node.name) $$render(consequent_2);
    });
  }
  var node_4 = sibling(node_1, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ul = root_44();
      each(ul, 21, () => $$props.node.children, index, ($$anchor3, child2) => {
        var li = root_54();
        var node_5 = child(li);
        Accounts_1(node_5, {
          get node() {
            return get(child2);
          },
          get move() {
            return $$props.move;
          }
        });
        reset(li);
        append($$anchor3, li);
      });
      reset(ul);
      template_effect(() => ul.hidden = !get(expanded));
      append($$anchor2, ul);
    };
    if_block(node_4, ($$render) => {
      if (get(hasChildren)) $$render(consequent_3);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/editor/DocumentPreviewEditor.svelte
var root24 = template(`<div class="svelte-96o3lr"></div>`);
function DocumentPreviewEditor($$anchor, $$props) {
  push($$props, true);
  const { editor: editor2, renderEditor } = initDocumentPreviewEditor("");
  const set_editor_content = (value) => {
    if (value !== editor2.state.sliceDoc()) {
      editor2.dispatch(replaceContents(editor2.state, value));
    }
  };
  user_effect(() => {
    fetch2($$props.url).then(handleText).then(set_editor_content, () => {
      set_editor_content(`Loading ${$$props.url} failed...`);
    });
  });
  var div = root24();
  action(div, ($$node) => renderEditor?.($$node));
  append($$anchor, div);
  pop();
}

// src/reports/documents/DocumentPreview.svelte
var plainTextExtensions = ["csv", "json", "qfx", "txt", "xml"];
var imageExtensions = [
  "gif",
  "jpg",
  "jpeg",
  "png",
  "svg",
  "webp",
  "bmp",
  "ico"
];
var root_123 = template(`<object class="svelte-586ug7"></object>`);
var root_55 = template(`<img class="svelte-586ug7">`);
var root_72 = template(`<iframe sandbox="" class="svelte-586ug7"></iframe>`);
function DocumentPreview($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlForRaw = () => store_get(urlForRaw, "$urlForRaw", $$stores);
  let extension = user_derived(() => ext($$props.filename).toLowerCase());
  let url = user_derived(() => $urlForRaw()("document/", { filename: $$props.filename }));
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var object2 = root_123();
      template_effect(() => {
        set_attribute(object2, "title", $$props.filename);
        set_attribute(object2, "data", get(url));
      });
      append($$anchor2, object2);
    };
    var alternate = ($$anchor2, $$elseif) => {
      {
        var consequent_1 = ($$anchor3) => {
          DocumentPreviewEditor($$anchor3, {
            get url() {
              return get(url);
            }
          });
        };
        var alternate_1 = ($$anchor3, $$elseif2) => {
          {
            var consequent_2 = ($$anchor4) => {
              var img = root_55();
              template_effect(() => {
                set_attribute(img, "src", get(url));
                set_attribute(img, "alt", $$props.filename);
              });
              append($$anchor4, img);
            };
            var alternate_2 = ($$anchor4, $$elseif3) => {
              {
                var consequent_3 = ($$anchor5) => {
                  var iframe = root_72();
                  template_effect(() => {
                    set_attribute(iframe, "src", get(url));
                    set_attribute(iframe, "title", $$props.filename);
                  });
                  append($$anchor5, iframe);
                };
                var alternate_3 = ($$anchor5) => {
                  var text2 = text();
                  template_effect(() => set_text(text2, `Preview for file \`${$$props.filename ?? ""}\` with file type \`${get(extension) ?? ""}\` is not implemented`));
                  append($$anchor5, text2);
                };
                if_block(
                  $$anchor4,
                  ($$render) => {
                    if (["html", "htm"].includes(get(extension))) $$render(consequent_3);
                    else $$render(alternate_3, false);
                  },
                  $$elseif3
                );
              }
            };
            if_block(
              $$anchor3,
              ($$render) => {
                if (imageExtensions.includes(get(extension))) $$render(consequent_2);
                else $$render(alternate_2, false);
              },
              $$elseif2
            );
          }
        };
        if_block(
          $$anchor2,
          ($$render) => {
            if (plainTextExtensions.includes(get(extension))) $$render(consequent_1);
            else $$render(alternate_1, false);
          },
          $$elseif
        );
      }
    };
    if_block(node, ($$render) => {
      if (get(extension) === "pdf") $$render(consequent);
      else $$render(alternate, false);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/documents/Table.svelte
var on_click6 = (__1, selected, doc2) => {
  selected(get(doc2));
};
var root_210 = template(`<tr><td> </td><td> </td></tr>`);
var root25 = template(`<table class="svelte-1511gpj"><thead><tr class="svelte-1511gpj"></tr></thead><tbody></tbody></table>`);
function Table($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $selectedAccount = () => store_get(selectedAccount, "$selectedAccount", $$stores);
  let selected = prop($$props, "selected", 15, null);
  function name3(doc2) {
    const base2 = basename(doc2.filename);
    return base2.startsWith(doc2.date) ? base2.substring(11) : base2;
  }
  const columns3 = [
    new DateColumn(_("Date")),
    new StringColumn(_("Name"), (d) => name3(d))
  ];
  let sorter = state(proxy2(new Sorter(columns3[0], "desc")));
  let filtered_documents = user_derived(() => $$props.data.filter((doc2) => isDescendant(doc2.account, $selectedAccount())));
  let sorted_documents = user_derived(() => get(sorter).sort(get(filtered_documents)));
  var table = root25();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 21, () => columns3, index, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return get(column);
      },
      get sorter() {
        return get(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get(sorted_documents), index, ($$anchor2, doc2) => {
    var tr_1 = root_210();
    set_attribute(tr_1, "draggable", true);
    tr_1.__click = [on_click6, selected, doc2];
    let classes;
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var text_1 = child(td_1, true);
    reset(td_1);
    reset(tr_1);
    template_effect(
      ($0, $1) => {
        set_attribute(tr_1, "title", get(doc2).filename);
        classes = set_class(tr_1, 1, "svelte-1511gpj", null, classes, $0);
        set_text(text2, get(doc2).date);
        set_text(text_1, $1);
      },
      [
        () => ({ selected: selected() === get(doc2) }),
        () => name3(get(doc2))
      ]
    );
    event("dragstart", tr_1, (ev) => {
      ev.dataTransfer?.setData("fava/filename", get(doc2).filename);
    });
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/reports/documents/Documents.svelte
var root_211 = template(`<form><h3> </h3> <p><code> </code></p> <p><!> <input> <button type="submit"> </button></p></form>`);
var root26 = template(`<!> <div class="fixed-fullsize-container svelte-11fib5h"><!> <div><!></div> <!></div>`, 1);
function Documents($$anchor, $$props) {
  push($$props, true);
  let grouped = user_derived(() => group($$props.documents, (d) => d.account));
  let node = user_derived(() => stratify(get(grouped).entries(), ([s]) => s, (name3, d) => ({ name: name3, count: d?.[1].length ?? 0 })));
  let selected = state(null);
  let moving = state(null);
  function keyup(ev) {
    if (ev.key === "F2" && get(selected) && !get(moving)) {
      set(
        moving,
        {
          account: get(selected).account,
          filename: get(selected).filename,
          newName: basename(get(selected).filename)
        },
        true
      );
    }
  }
  async function move3(event2) {
    event2.preventDefault();
    if (get(moving)) {
      const moved = await moveDocument(get(moving).filename, get(moving).account, get(moving).newName);
      if (moved) {
        set(moving, null);
        router_default.reload();
      }
    }
  }
  var fragment = root26();
  event("keyup", $window, keyup);
  var node_1 = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      ModalBase($$anchor2, {
        shown: true,
        closeHandler: () => {
          set(moving, null);
        },
        children: ($$anchor3, $$slotProps) => {
          var form = root_211();
          var h3 = child(form);
          var text2 = child(h3, true);
          reset(h3);
          var p = sibling(h3, 2);
          var code = child(p);
          var text_1 = child(code, true);
          reset(code);
          reset(p);
          var p_1 = sibling(p, 2);
          var node_2 = child(p_1);
          AccountInput(node_2, {
            get value() {
              return get(moving).account;
            },
            set value($$value) {
              get(moving).account = $$value;
            }
          });
          var input = sibling(node_2, 2);
          remove_input_defaults(input);
          set_attribute(input, "size", 40);
          var button = sibling(input, 2);
          var text_2 = child(button, true);
          reset(button);
          reset(p_1);
          reset(form);
          template_effect(
            ($0, $1) => {
              set_text(text2, $0);
              set_text(text_1, get(moving).filename);
              set_text(text_2, $1);
            },
            [
              () => _("Move or rename document"),
              () => _("Move")
            ]
          );
          event("submit", form, move3);
          bind_value(input, () => get(moving).newName, ($$value) => get(moving).newName = $$value);
          append($$anchor3, form);
        },
        $$slots: { default: true }
      });
    };
    if_block(node_1, ($$render) => {
      if (get(moving)) $$render(consequent);
    });
  }
  var div = sibling(node_1, 2);
  var node_3 = child(div);
  Accounts_1(node_3, {
    get node() {
      return get(node);
    },
    move: (arg) => {
      set(moving, { ...arg, newName: basename(arg.filename) }, true);
    }
  });
  var div_1 = sibling(node_3, 2);
  var node_4 = child(div_1);
  Table(node_4, {
    get data() {
      return $$props.documents;
    },
    get selected() {
      return get(selected);
    },
    set selected($$value) {
      set(selected, $$value, true);
    }
  });
  reset(div_1);
  var node_5 = sibling(div_1, 2);
  {
    var consequent_1 = ($$anchor2) => {
      DocumentPreview($$anchor2, {
        get filename() {
          return get(selected).filename;
        }
      });
    };
    if_block(node_5, ($$render) => {
      if (get(selected)) $$render(consequent_1);
    });
  }
  reset(div);
  append($$anchor, fragment);
  pop();
}

// src/reports/documents/index.ts
var documents = new Route(
  "documents",
  Documents,
  async (url) => get3("documents", getURLFilters(url)).then((data) => ({
    documents: data
  })),
  () => _("Documents")
);

// src/editor/SaveButton.svelte
var root27 = template(`<button type="submit"> </button>`);
function SaveButton($$anchor, $$props) {
  push($$props, true);
  let buttonContent = user_derived(() => $$props.saving ? _("Saving...") : _("Save"));
  var button = root27();
  var text2 = child(button, true);
  reset(button);
  action(button, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => ({ key: "Control+s", mac: "Meta+s" }));
  template_effect(() => {
    button.disabled = !$$props.changed;
    set_text(text2, get(buttonContent));
  });
  append($$anchor, button);
  pop();
}

// src/reports/editor/AppMenu.svelte
var root28 = template(`<div role="menubar" class="svelte-5ozbeh"><!></div>`);
function AppMenu($$anchor, $$props) {
  var div = root28();
  var node = child(div);
  snippet(node, () => $$props.children);
  reset(div);
  append($$anchor, div);
}

// src/reports/editor/AppMenuItem.svelte
var on_keydown2 = (event2, open) => {
  if (event2.key === "Escape") {
    set(open, false);
  } else if (event2.key === "ArrowDown") {
    set(open, true);
  }
};
var root29 = template(`<span tabindex="0" role="menuitem"> <ul role="menu" class="svelte-hpa0bh"><!></ul></span>`);
function AppMenuItem($$anchor, $$props) {
  let open = state(false);
  var span = root29();
  span.__keydown = [on_keydown2, open];
  let classes;
  var text2 = child(span);
  var ul = sibling(text2);
  var node = child(ul);
  snippet(node, () => $$props.children);
  reset(ul);
  reset(span);
  template_effect(
    ($0) => {
      classes = set_class(span, 1, "svelte-hpa0bh", null, classes, $0);
      set_text(text2, `${$$props.name ?? ""} `);
    },
    [() => ({ open: get(open) })]
  );
  event("blur", span, () => {
    set(open, false);
  });
  append($$anchor, span);
}
delegate(["keydown"]);

// src/reports/editor/AppMenuSubItem.svelte
var on_keydown3 = (event2, $$props) => {
  if (event2.key === "Enter") {
    $$props.action();
  }
};
var root_124 = template(`<span class="svelte-1su1a4z"><!></span>`);
var root30 = template(`<li role="menuitem"><!> <!></li>`);
function AppMenuSubItem($$anchor, $$props) {
  push($$props, true);
  let selected = prop($$props, "selected", 3, false);
  var li = root30();
  li.__click = function(...$$args) {
    $$props.action?.apply(this, $$args);
  };
  li.__keydown = [on_keydown3, $$props];
  let classes;
  var node = child(li);
  snippet(node, () => $$props.children);
  var node_1 = sibling(node, 2);
  {
    var consequent = ($$anchor2) => {
      var span = root_124();
      var node_2 = child(span);
      snippet(node_2, () => $$props.right);
      reset(span);
      append($$anchor2, span);
    };
    if_block(node_1, ($$render) => {
      if ($$props.right) $$render(consequent);
    });
  }
  reset(li);
  template_effect(
    ($0) => {
      set_attribute(li, "title", $$props.title);
      classes = set_class(li, 1, "svelte-1su1a4z", null, classes, $0);
    },
    [() => ({ selected: selected() })]
  );
  append($$anchor, li);
  pop();
}
delegate(["click", "keydown"]);

// src/reports/editor/Key.svelte
var root_125 = template(`<kbd> </kbd> `, 1);
function Key($$anchor, $$props) {
  push($$props, true);
  var fragment = comment();
  var node = first_child(fragment);
  each(node, 17, () => $$props.key, index, ($$anchor2, part, index3) => {
    var fragment_1 = root_125();
    var kbd = first_child(fragment_1);
    var text2 = child(kbd, true);
    reset(kbd);
    var text_1 = sibling(kbd, 1, true);
    template_effect(() => {
      set_text(text2, get(part));
      set_text(text_1, index3 === $$props.key.length - 1 ? "" : "+");
    });
    append($$anchor2, fragment_1);
  });
  append($$anchor, fragment);
  pop();
}

// src/reports/editor/EditorMenu.svelte
var root_56 = template(`<!> <!> <!> <!>`, 1);
var root_172 = template(`<span> </span>`);
var root_126 = template(`<!> <!> <!>`, 1);
var root31 = template(`<div class="svelte-1b7r65z"><!> <!></div>`);
function EditorMenu($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $options = () => store_get(options, "$options", $$stores);
  const $fava_options = () => store_get(fava_options, "$fava_options", $$stores);
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  let sources = user_derived(() => [
    $options().filename,
    ...$options().include.filter((f) => f !== $options().filename)
  ]);
  let insertEntryOptions = user_derived(() => $fava_options().insert_entry);
  function goToFileAndLine(filename, line) {
    const url = $urlFor()("editor/", { file_path: filename, line });
    const load = filename !== $$props.file_path;
    router_default.navigate(url, load);
    if (!load && line != null) {
      $$props.editor.dispatch(scrollToLine($$props.editor.state, line));
      $$props.editor.focus();
    }
  }
  var div = root31();
  var node = child(div);
  AppMenu(node, {
    children: ($$anchor2, $$slotProps) => {
      var fragment = root_126();
      var node_1 = first_child(fragment);
      const expression = user_derived(() => _("File"));
      AppMenuItem(node_1, {
        get name() {
          return get(expression);
        },
        children: ($$anchor3, $$slotProps2) => {
          var fragment_1 = comment();
          var node_2 = first_child(fragment_1);
          each(node_2, 17, () => get(sources), index, ($$anchor4, source3) => {
            const expression_1 = user_derived(() => get(source3) === $$props.file_path);
            AppMenuSubItem($$anchor4, {
              action: () => {
                goToFileAndLine(get(source3));
              },
              get selected() {
                return get(expression_1);
              },
              children: ($$anchor5, $$slotProps3) => {
                next();
                var text2 = text();
                template_effect(() => set_text(text2, get(source3)));
                append($$anchor5, text2);
              },
              $$slots: { default: true }
            });
          });
          append($$anchor3, fragment_1);
        },
        $$slots: { default: true }
      });
      var node_3 = sibling(node_1, 2);
      const expression_2 = user_derived(() => _("Edit"));
      AppMenuItem(node_3, {
        get name() {
          return get(expression_2);
        },
        children: ($$anchor3, $$slotProps2) => {
          var fragment_4 = root_56();
          var node_4 = first_child(fragment_4);
          {
            const right2 = ($$anchor4) => {
              Key($$anchor4, { key: [modKey, "d"] });
            };
            AppMenuSubItem(node_4, {
              action: () => beancountFormat($$props.editor),
              right: right2,
              children: ($$anchor4, $$slotProps3) => {
                next();
                var text_1 = text();
                template_effect(($0) => set_text(text_1, $0), [() => _("Align Amounts")]);
                append($$anchor4, text_1);
              },
              $$slots: { right: true, default: true }
            });
          }
          var node_5 = sibling(node_4, 2);
          {
            const right2 = ($$anchor4) => {
              Key($$anchor4, { key: [modKey, "/"] });
            };
            AppMenuSubItem(node_5, {
              action: () => toggleComment($$props.editor),
              right: right2,
              children: ($$anchor4, $$slotProps3) => {
                next();
                var text_2 = text();
                template_effect(($0) => set_text(text_2, $0), [() => _("Toggle Comment (selection)")]);
                append($$anchor4, text_2);
              },
              $$slots: { right: true, default: true }
            });
          }
          var node_6 = sibling(node_5, 2);
          {
            const right2 = ($$anchor4) => {
              Key($$anchor4, { key: ["Ctrl", "Alt", "]"] });
            };
            AppMenuSubItem(node_6, {
              action: () => unfoldAll($$props.editor),
              right: right2,
              children: ($$anchor4, $$slotProps3) => {
                next();
                var text_3 = text();
                template_effect(($0) => set_text(text_3, $0), [() => _("Open all folds")]);
                append($$anchor4, text_3);
              },
              $$slots: { right: true, default: true }
            });
          }
          var node_7 = sibling(node_6, 2);
          {
            const right2 = ($$anchor4) => {
              Key($$anchor4, { key: ["Ctrl", "Alt", "["] });
            };
            AppMenuSubItem(node_7, {
              action: () => foldAll($$props.editor),
              right: right2,
              children: ($$anchor4, $$slotProps3) => {
                next();
                var text_4 = text();
                template_effect(($0) => set_text(text_4, $0), [() => _("Close all folds")]);
                append($$anchor4, text_4);
              },
              $$slots: { right: true, default: true }
            });
          }
          append($$anchor3, fragment_4);
        },
        $$slots: { default: true }
      });
      var node_8 = sibling(node_3, 2);
      {
        var consequent = ($$anchor3) => {
          const expression_3 = user_derived(() => `'insert-entry' ${_("Options")}`);
          AppMenuItem($$anchor3, {
            get name() {
              return get(expression_3);
            },
            children: ($$anchor4, $$slotProps2) => {
              var fragment_14 = comment();
              var node_9 = first_child(fragment_14);
              each(node_9, 17, () => get(insertEntryOptions), index, ($$anchor5, opt) => {
                const expression_4 = user_derived(() => `${get(opt).filename}:${get(opt).lineno.toString()}`);
                {
                  const right2 = ($$anchor6) => {
                    var span = root_172();
                    var text_5 = child(span, true);
                    reset(span);
                    template_effect(() => set_text(text_5, get(opt).date));
                    append($$anchor6, span);
                  };
                  AppMenuSubItem($$anchor5, {
                    get title() {
                      return get(expression_4);
                    },
                    action: () => {
                      goToFileAndLine(get(opt).filename, get(opt).lineno - 1);
                    },
                    right: right2,
                    children: ($$anchor6, $$slotProps3) => {
                      next();
                      var text_6 = text();
                      template_effect(() => set_text(text_6, get(opt).re));
                      append($$anchor6, text_6);
                    },
                    $$slots: { right: true, default: true }
                  });
                }
              });
              append($$anchor4, fragment_14);
            },
            $$slots: { default: true }
          });
        };
        if_block(node_8, ($$render) => {
          if (get(insertEntryOptions).length) $$render(consequent);
        });
      }
      append($$anchor2, fragment);
    },
    $$slots: { default: true }
  });
  var node_10 = sibling(node, 2);
  snippet(node_10, () => $$props.children);
  reset(div);
  append($$anchor, div);
  pop();
  $$cleanup();
}

// src/reports/editor/Editor.svelte
var root32 = template(`<form class="fixed-fullsize-container svelte-llllbf"><!> <div class="svelte-llllbf"></div></form>`);
function Editor($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $fava_options = () => store_get(fava_options, "$fava_options", $$stores);
  const $searchParams = () => store_get(searchParams, "$searchParams", $$stores);
  const $errors = () => store_get(errors, "$errors", $$stores);
  let file_path = user_derived(() => $$props.source.file_path);
  let changed = state(false);
  const onDocChanges = () => {
    set(changed, true);
  };
  let sha256sum = state("");
  let saving = state(false);
  async function save(cm) {
    set(saving, true);
    try {
      set(
        sha256sum,
        await put("source", {
          file_path: get(file_path),
          source: cm.state.sliceDoc(),
          sha256sum: get(sha256sum)
        }),
        true
      );
      set(changed, false);
      cm.focus();
      get3("errors").then(
        (v) => {
          errors.set(v);
        },
        log_error
      );
    } catch (error2) {
      notify_err(error2, (e) => e.message);
    } finally {
      set(saving, false);
    }
  }
  const { editor: editor2, renderEditor } = initBeancountEditor(
    "",
    onDocChanges,
    [
      {
        key: "Control-s",
        mac: "Meta-s",
        run: () => {
          save(editor2).catch(() => {
          });
          return true;
        }
      }
    ],
    $$props.beancount_language_support
  );
  user_effect(() => {
    $$props.source;
    untrack(() => {
      editor2.dispatch(replaceContents(editor2.state, $$props.source.source));
      set(sha256sum, $$props.source.sha256sum, true);
      editor2.focus();
      set(changed, false);
    });
  });
  user_effect(() => {
    get(file_path);
    untrack(() => {
      const opts2 = $fava_options().insert_entry.filter((f) => f.filename === get(file_path));
      const last_insert_opt = opts2[opts2.length - 1];
      const line = parseInt($searchParams().get("line") ?? "0", 10);
      let line_to_scroll_to = null;
      if (line > 0) {
        line_to_scroll_to = line;
      } else if (last_insert_opt) {
        line_to_scroll_to = last_insert_opt.lineno - 1;
      }
      editor2.dispatch(scrollToLine(editor2.state, line_to_scroll_to ?? editor2.state.doc.lines));
    });
  });
  user_effect(() => {
    const errorsForFile = $errors().filter((err3) => err3.source === null || err3.source.filename === get(file_path));
    editor2.dispatch(setErrors(editor2.state, errorsForFile));
  });
  const checkEditorChanges = () => get(changed) ? "There are unsaved changes. Are you sure you want to leave?" : null;
  onMount(() => router_default.addInteruptHandler(checkEditorChanges));
  var form = root32();
  var node = child(form);
  EditorMenu(node, {
    get file_path() {
      return get(file_path);
    },
    editor: editor2,
    children: ($$anchor2, $$slotProps) => {
      SaveButton($$anchor2, {
        get changed() {
          return get(changed);
        },
        get saving() {
          return get(saving);
        }
      });
    },
    $$slots: { default: true }
  });
  var div = sibling(node, 2);
  action(div, ($$node) => renderEditor?.($$node));
  reset(form);
  event("submit", form, async (event2) => {
    event2.preventDefault();
    return save(editor2);
  });
  append($$anchor, form);
  pop();
  $$cleanup();
}

// src/reports/editor/index.ts
var editor = new Route(
  "editor",
  Editor,
  async (url) => Promise.all([
    get3("source", {
      filename: url.searchParams.get("file_path") ?? ""
    }),
    getBeancountLanguageSupport()
  ]).then(([source3, beancount_language_support]) => ({
    source: source3,
    beancount_language_support
  })),
  () => _("Editor")
);

// src/reports/errors/Errors.svelte
var root_45 = template(`<td> </td> <td class="num"><a class="source"> </a></td>`, 1);
var root_57 = template(`<td></td> <td class="num"></td>`, 1);
var root_8 = template(`<a> </a>`);
var root_37 = template(`<tr><!><td class="pre"></td></tr>`);
var root_127 = template(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
var root_9 = template(`<p> </p>`);
function Errors($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  const $errors = () => store_get(errors, "$errors", $$stores);
  const $urlForSource = () => store_get(urlForSource, "$urlForSource", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  let account_re = user_derived(() => new RegExp(`(${$accounts().join("|")})`));
  function extract_accounts(msg) {
    return msg.split(get(account_re)).map((text2, index3) => index3 % 2 === 0 ? ["text", text2] : ["account", text2]);
  }
  const columns3 = [
    new StringColumn(_("File"), (d) => d.source?.filename ?? ""),
    new NumberColumn(_("Line"), (d) => d.source?.lineno ?? 0),
    new StringColumn(_("Error"), (d) => d.message)
  ];
  let sorter = state(proxy2(new Sorter(columns3[0], "desc")));
  let sorted_errors = user_derived(() => get(sorter).sort($errors()));
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent_2 = ($$anchor2) => {
      var table = root_127();
      var thead = child(table);
      var tr = child(thead);
      each(tr, 21, () => columns3, index, ($$anchor3, column) => {
        SortHeader($$anchor3, {
          get column() {
            return get(column);
          },
          get sorter() {
            return get(sorter);
          },
          set sorter($$value) {
            set(sorter, $$value, true);
          }
        });
      });
      reset(tr);
      reset(thead);
      var tbody = sibling(thead);
      each(tbody, 21, () => get(sorted_errors), index, ($$anchor3, $$item) => {
        let message = () => get($$item).message;
        let source3 = () => get($$item).source;
        var tr_1 = root_37();
        var node_1 = child(tr_1);
        {
          var consequent = ($$anchor4) => {
            var fragment_2 = root_45();
            const url = user_derived(() => $urlForSource()(source3().filename, source3().lineno.toString()));
            const title = user_derived(() => format(_("Show source %(file)s:%(lineno)s"), {
              file: source3().filename,
              lineno: source3().lineno.toString()
            }));
            var td = first_child(fragment_2);
            var text_1 = child(td, true);
            reset(td);
            var td_1 = sibling(td, 2);
            var a = child(td_1);
            var text_2 = child(a, true);
            reset(a);
            reset(td_1);
            template_effect(() => {
              set_text(text_1, source3().filename);
              set_attribute(a, "href", get(url));
              set_attribute(a, "title", get(title));
              set_text(text_2, source3().lineno);
            });
            append($$anchor4, fragment_2);
          };
          var alternate = ($$anchor4) => {
            var fragment_3 = root_57();
            next(2);
            append($$anchor4, fragment_3);
          };
          if_block(node_1, ($$render) => {
            if (source3()) $$render(consequent);
            else $$render(alternate, false);
          });
        }
        var td_2 = sibling(node_1);
        each(td_2, 21, () => extract_accounts(message()), index, ($$anchor4, $$item2) => {
          let type = () => get($$item2)[0];
          let text2 = () => get($$item2)[1];
          var fragment_4 = comment();
          var node_2 = first_child(fragment_4);
          {
            var consequent_1 = ($$anchor5) => {
              var text_3 = text();
              template_effect(() => set_text(text_3, text2()));
              append($$anchor5, text_3);
            };
            var alternate_1 = ($$anchor5) => {
              var a_1 = root_8();
              var text_4 = child(a_1, true);
              reset(a_1);
              template_effect(
                ($0) => {
                  set_attribute(a_1, "href", $0);
                  set_text(text_4, text2());
                },
                [() => $urlForAccount()(text2())]
              );
              append($$anchor5, a_1);
            };
            if_block(node_2, ($$render) => {
              if (type() === "text") $$render(consequent_1);
              else $$render(alternate_1, false);
            });
          }
          append($$anchor4, fragment_4);
        });
        reset(td_2);
        reset(tr_1);
        append($$anchor3, tr_1);
      });
      reset(tbody);
      reset(table);
      append($$anchor2, table);
    };
    var alternate_2 = ($$anchor2) => {
      var p = root_9();
      var text_5 = child(p, true);
      reset(p);
      template_effect(($0) => set_text(text_5, $0), [() => _("No errors.")]);
      append($$anchor2, p);
    };
    if_block(node, ($$render) => {
      if ($errors().length) $$render(consequent_2);
      else $$render(alternate_2, false);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/errors/index.ts
var errors2 = new DatalessRoute(
  "errors",
  Errors,
  () => _("Errors")
);

// src/reports/events/EventTable.svelte
var root_212 = template(`<tr><td> </td><td> </td></tr>`);
var root33 = template(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function EventTable($$anchor, $$props) {
  push($$props, true);
  const columns3 = [
    new DateColumn(_("Date")),
    new StringColumn(_("Description"), (d) => d.description)
  ];
  let sorter = state(proxy2(new Sorter(columns3[0], "desc")));
  let sorted_events = user_derived(() => get(sorter).sort($$props.events));
  var table = root33();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 21, () => columns3, index, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return get(column);
      },
      get sorter() {
        return get(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get(sorted_events), index, ($$anchor2, event2) => {
    var tr_1 = root_212();
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var text_1 = child(td_1, true);
    reset(td_1);
    reset(tr_1);
    template_effect(() => {
      set_text(text2, get(event2).date);
      set_text(text_1, get(event2).description);
    });
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
}

// src/reports/events/Events.svelte
var root_213 = template(`<div class="left"><h3> </h3> <!></div>`);
var root_128 = template(`<!> <!>`, 1);
var root_38 = template(`<p> </p>`);
function Events2($$anchor, $$props) {
  push($$props, true);
  let groups2 = user_derived(() => [
    ...group($$props.events, (e) => e.type)
  ]);
  let charts = user_derived(() => [
    new ScatterPlot(_("Events"), $$props.events.map(({ date: date4, type, description }) => ({ date: new Date(date4), type, description })))
  ]);
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var fragment_1 = root_128();
      var node_1 = first_child(fragment_1);
      ChartSwitcher(node_1, {
        get charts() {
          return get(charts);
        }
      });
      var node_2 = sibling(node_1, 2);
      each(node_2, 17, () => get(groups2), ([type, events_in_group]) => type, ($$anchor3, $$item) => {
        let type = () => get($$item)[0];
        let events_in_group = () => get($$item)[1];
        var div = root_213();
        var h3 = child(div);
        var text2 = child(h3, true);
        reset(h3);
        var node_3 = sibling(h3, 2);
        EventTable(node_3, {
          get events() {
            return events_in_group();
          }
        });
        reset(div);
        template_effect(($0) => set_text(text2, $0), [
          () => format(_("Event: %(type)s"), { type: type() })
        ]);
        append($$anchor3, div);
      });
      append($$anchor2, fragment_1);
    };
    var alternate = ($$anchor2) => {
      var p = root_38();
      var text_1 = child(p, true);
      reset(p);
      template_effect(($0) => set_text(text_1, $0), [() => _("No events.")]);
      append($$anchor2, p);
    };
    if_block(node, ($$render) => {
      if (get(groups2).length) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  append($$anchor, fragment);
  pop();
}

// src/reports/events/index.ts
var events = new Route(
  "events",
  Events2,
  async (url) => get3("events", getURLFilters(url)).then((data) => ({ events: data })),
  () => _("Events")
);

// src/reports/query/QueryLinks.svelte
var root_129 = template(`, <a data-remote="">XLSX</a> , or <a data-remote="">ODS</a>`, 1);
var root34 = template(`<span class="svelte-bt1doq"> <a data-remote="">CSV</a> <!> )</span>`);
function QueryLinks($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  const $HAVE_EXCEL = () => store_get(HAVE_EXCEL, "$HAVE_EXCEL", $$stores);
  let params = user_derived(() => ({ query_string: $$props.query }));
  var span = root34();
  var text2 = child(span);
  var a = sibling(text2);
  var node = sibling(a, 2);
  {
    var consequent = ($$anchor2) => {
      var fragment = root_129();
      var a_1 = sibling(first_child(fragment));
      var a_2 = sibling(a_1, 2);
      template_effect(
        ($0, $1) => {
          set_attribute(a_1, "href", $0);
          set_attribute(a_2, "href", $1);
        },
        [
          () => $urlFor()("download-query/query_result.xlsx", get(params)),
          () => $urlFor()("download-query/query_result.ods", get(params))
        ]
      );
      append($$anchor2, fragment);
    };
    if_block(node, ($$render) => {
      if ($HAVE_EXCEL()) $$render(consequent);
    });
  }
  next();
  reset(span);
  template_effect(
    ($0, $1) => {
      set_text(text2, `(${$0 ?? ""} `);
      set_attribute(a, "href", $1);
    },
    [
      () => _("Download as"),
      () => $urlFor()("download-query/query_result.csv", get(params))
    ]
  );
  append($$anchor, span);
  pop();
  $$cleanup();
}

// src/reports/query/QueryTable.svelte
var root_46 = template(`<td>&nbsp;</td>`);
var root_67 = template(`<td> </td>`);
var root_82 = template(`<td class="num"> </td>`);
var root_11 = template(`<a> </a> <!>`, 1);
var root_132 = template(`<a> </a>`);
var root_102 = template(`<td><!></td>`);
var root_162 = template(`<td> </td>`);
var root_182 = template(`<td> </td>`);
var root_20 = template(`<td class="num"> </td>`);
var root_222 = template(`<td class="num"> <!></td>`);
var root_262 = template(` <br>`, 1);
var root_252 = template(`<td class="num"></td>`);
var root_214 = template(`<tr></tr>`);
var root35 = template(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function QueryTable($$anchor, $$props) {
  push($$props, false);
  const [$$stores, $$cleanup] = setup_stores();
  const $num = () => store_get(num, "$num", $$stores);
  const $accounts_set = () => store_get(accounts_set, "$accounts_set", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const filter_empty_column_number = mutable_source();
  const filtered_rows = mutable_source();
  const sorted_rows = mutable_source();
  let table = prop($$props, "table", 8);
  let filter_empty = prop($$props, "filter_empty", 24, () => void 0);
  let sorter = mutable_source(new Sorter(new UnsortedColumn("<Dummy>"), "asc"));
  legacy_pre_effect(
    () => (deep_read_state(table()), deep_read_state(filter_empty())),
    () => {
      set(filter_empty_column_number, table().columns.findIndex((column) => column.name === filter_empty()));
    }
  );
  legacy_pre_effect(
    () => (get(filter_empty_column_number), deep_read_state(table()), Inventory, is_empty),
    () => {
      set(filtered_rows, get(filter_empty_column_number) > -1 ? table().rows.filter((row) => {
        const cell = row[get(filter_empty_column_number)];
        return !(cell instanceof Inventory && is_empty(cell.value));
      }) : table().rows);
    }
  );
  legacy_pre_effect(() => (get(sorter), get(filtered_rows)), () => {
    set(sorted_rows, get(sorter).sort(get(filtered_rows)));
  });
  legacy_pre_effect_reset();
  init2();
  var table_1 = root35();
  var thead = child(table_1);
  var tr = child(thead);
  each(tr, 5, () => table().columns, index, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return get(column);
      },
      get sorter() {
        return get(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value);
      },
      $$legacy: true
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 5, () => get(sorted_rows), index, ($$anchor2, row) => {
    var tr_1 = root_214();
    each(tr_1, 5, () => get(row), index, ($$anchor3, value, index3) => {
      var fragment_1 = comment();
      var node = first_child(fragment_1);
      {
        var consequent = ($$anchor4) => {
          var td = root_46();
          append($$anchor4, td);
        };
        var alternate = ($$anchor4, $$elseif) => {
          {
            var consequent_1 = ($$anchor5) => {
              var td_1 = root_67();
              var text2 = child(td_1, true);
              reset(td_1);
              template_effect(
                ($0) => set_text(text2, $0),
                [
                  () => get(value).toString().toUpperCase()
                ],
                derived_safe_equal
              );
              append($$anchor5, td_1);
            };
            var alternate_1 = ($$anchor5, $$elseif2) => {
              {
                var consequent_2 = ($$anchor6) => {
                  var td_2 = root_82();
                  var text_1 = child(td_2, true);
                  reset(td_2);
                  template_effect(
                    ($0) => set_text(text_1, $0),
                    [
                      () => table().columns[index3]?.dtype === "int" ? get(value).toString() : $num()(get(value))
                    ],
                    derived_safe_equal
                  );
                  append($$anchor6, td_2);
                };
                var alternate_2 = ($$anchor6, $$elseif3) => {
                  {
                    var consequent_5 = ($$anchor7) => {
                      var td_3 = root_102();
                      var node_1 = child(td_3);
                      {
                        var consequent_3 = ($$anchor8) => {
                          var fragment_2 = root_11();
                          var a = first_child(fragment_2);
                          var text_2 = child(a, true);
                          reset(a);
                          var node_2 = sibling(a, 2);
                          AccountIndicator(node_2, {
                            get account() {
                              return get(value);
                            },
                            small: true
                          });
                          template_effect(
                            ($0) => {
                              set_attribute(a, "href", $0);
                              set_text(text_2, get(value));
                            },
                            [
                              () => $urlForAccount()(get(value))
                            ],
                            derived_safe_equal
                          );
                          append($$anchor8, fragment_2);
                        };
                        var alternate_3 = ($$anchor8, $$elseif4) => {
                          {
                            var consequent_4 = ($$anchor9) => {
                              var a_1 = root_132();
                              var text_3 = child(a_1, true);
                              reset(a_1);
                              template_effect(() => {
                                set_attribute(a_1, "href", `#context-${get(value)}`);
                                set_text(text_3, get(value));
                              });
                              append($$anchor9, a_1);
                            };
                            var alternate_4 = ($$anchor9) => {
                              var text_4 = text();
                              template_effect(() => set_text(text_4, get(value)));
                              append($$anchor9, text_4);
                            };
                            if_block(
                              $$anchor8,
                              ($$render) => {
                                if (get(value).length === 32 && /[a-z0-9]/.test(get(value))) $$render(consequent_4);
                                else $$render(alternate_4, false);
                              },
                              $$elseif4
                            );
                          }
                        };
                        if_block(node_1, ($$render) => {
                          if ($accounts_set().has(get(value))) $$render(consequent_3);
                          else $$render(alternate_3, false);
                        });
                      }
                      reset(td_3);
                      append($$anchor7, td_3);
                    };
                    var alternate_5 = ($$anchor7, $$elseif4) => {
                      {
                        var consequent_6 = ($$anchor8) => {
                          var td_4 = root_162();
                          var text_5 = child(td_4, true);
                          reset(td_4);
                          template_effect(($0) => set_text(text_5, $0), [() => get(value).join(",")], derived_safe_equal);
                          append($$anchor8, td_4);
                        };
                        var alternate_6 = ($$anchor8, $$elseif5) => {
                          {
                            var consequent_7 = ($$anchor9) => {
                              var td_5 = root_182();
                              var text_6 = child(td_5, true);
                              reset(td_5);
                              template_effect(($0) => set_text(text_6, $0), [() => day(get(value))], derived_safe_equal);
                              append($$anchor9, td_5);
                            };
                            var alternate_7 = ($$anchor9, $$elseif6) => {
                              {
                                var consequent_8 = ($$anchor10) => {
                                  var td_6 = root_20();
                                  var text_7 = child(td_6, true);
                                  reset(td_6);
                                  template_effect(($0) => set_text(text_7, $0), [() => get(value).str($ctx())], derived_safe_equal);
                                  append($$anchor10, td_6);
                                };
                                var alternate_8 = ($$anchor10, $$elseif7) => {
                                  {
                                    var consequent_10 = ($$anchor11) => {
                                      var td_7 = root_222();
                                      var text_8 = child(td_7);
                                      var node_3 = sibling(text_8);
                                      {
                                        var consequent_9 = ($$anchor12) => {
                                          var text_9 = text();
                                          template_effect(
                                            ($0) => set_text(text_9, `{${$0 ?? ""}}`),
                                            [
                                              () => get(value).cost.str($ctx())
                                            ],
                                            derived_safe_equal
                                          );
                                          append($$anchor12, text_9);
                                        };
                                        if_block(node_3, ($$render) => {
                                          if (get(value).cost) $$render(consequent_9);
                                        });
                                      }
                                      reset(td_7);
                                      template_effect(
                                        ($0) => set_text(text_8, `${$0 ?? ""} `),
                                        [
                                          () => get(value).units.str($ctx())
                                        ],
                                        derived_safe_equal
                                      );
                                      append($$anchor11, td_7);
                                    };
                                    var alternate_9 = ($$anchor11, $$elseif8) => {
                                      {
                                        var consequent_11 = ($$anchor12) => {
                                          var td_8 = root_252();
                                          each(td_8, 5, () => Object.entries(get(value).value), index, ($$anchor13, $$item) => {
                                            let currency = () => get($$item)[0];
                                            let number7 = () => get($$item)[1];
                                            next();
                                            var fragment_5 = root_262();
                                            var text_10 = first_child(fragment_5);
                                            next();
                                            template_effect(
                                              ($0) => set_text(text_10, `${$0 ?? ""} `),
                                              [
                                                () => $ctx().amount(number7(), currency())
                                              ],
                                              derived_safe_equal
                                            );
                                            append($$anchor13, fragment_5);
                                          });
                                          reset(td_8);
                                          append($$anchor12, td_8);
                                        };
                                        if_block(
                                          $$anchor11,
                                          ($$render) => {
                                            if (get(value) instanceof Inventory) $$render(consequent_11);
                                          },
                                          $$elseif8
                                        );
                                      }
                                    };
                                    if_block(
                                      $$anchor10,
                                      ($$render) => {
                                        if (get(value) instanceof Position) $$render(consequent_10);
                                        else $$render(alternate_9, false);
                                      },
                                      $$elseif7
                                    );
                                  }
                                };
                                if_block(
                                  $$anchor9,
                                  ($$render) => {
                                    if (get(value) instanceof Amount) $$render(consequent_8);
                                    else $$render(alternate_8, false);
                                  },
                                  $$elseif6
                                );
                              }
                            };
                            if_block(
                              $$anchor8,
                              ($$render) => {
                                if (get(value) instanceof Date) $$render(consequent_7);
                                else $$render(alternate_7, false);
                              },
                              $$elseif5
                            );
                          }
                        };
                        if_block(
                          $$anchor7,
                          ($$render) => {
                            if (Array.isArray(get(value))) $$render(consequent_6);
                            else $$render(alternate_6, false);
                          },
                          $$elseif4
                        );
                      }
                    };
                    if_block(
                      $$anchor6,
                      ($$render) => {
                        if (typeof get(value) === "string") $$render(consequent_5);
                        else $$render(alternate_5, false);
                      },
                      $$elseif3
                    );
                  }
                };
                if_block(
                  $$anchor5,
                  ($$render) => {
                    if (typeof get(value) === "number") $$render(consequent_2);
                    else $$render(alternate_2, false);
                  },
                  $$elseif2
                );
              }
            };
            if_block(
              $$anchor4,
              ($$render) => {
                if (typeof get(value) === "boolean") $$render(consequent_1);
                else $$render(alternate_1, false);
              },
              $$elseif
            );
          }
        };
        if_block(node, ($$render) => {
          if (get(value) === null) $$render(consequent);
          else $$render(alternate, false);
        });
      }
      append($$anchor3, fragment_1);
    });
    reset(tr_1);
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table_1);
  append($$anchor, table_1);
  pop();
  $$cleanup();
}

// src/reports/holdings/Holdings.svelte
var root_215 = template(`<a> </a>`);
var root_47 = template(`<a> </a>`);
var root_68 = template(`<a> </a>`);
var root_83 = template(`<a> </a>`);
var root36 = template(`<div class="headerline"><h3><!></h3> <h3><!></h3> <h3><!></h3> <h3><!></h3></div> <p><a> </a> <!></p> <!>`, 1);
function Holdings($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  var fragment = root36();
  var div = first_child(fragment);
  var h3 = child(div);
  var node = child(h3);
  {
    var consequent = ($$anchor2) => {
      var text2 = text();
      template_effect(($0) => set_text(text2, $0), [() => _("Holdings")]);
      append($$anchor2, text2);
    };
    var alternate = ($$anchor2) => {
      var a = root_215();
      var text_1 = child(a, true);
      reset(a);
      template_effect(
        ($0, $1) => {
          set_attribute(a, "href", $0);
          set_text(text_1, $1);
        },
        [
          () => $urlFor()("holdings/"),
          () => _("Holdings")
        ]
      );
      append($$anchor2, a);
    };
    if_block(node, ($$render) => {
      if ($$props.aggregation_key === "all") $$render(consequent);
      else $$render(alternate, false);
    });
  }
  reset(h3);
  var h3_1 = sibling(h3, 2);
  var node_1 = child(h3_1);
  {
    var consequent_1 = ($$anchor2) => {
      var text_2 = text();
      template_effect(($0, $1) => set_text(text_2, `${$0 ?? ""} ${$1 ?? ""}`), [
        () => _("Holdings by"),
        () => _("Account")
      ]);
      append($$anchor2, text_2);
    };
    var alternate_1 = ($$anchor2) => {
      var a_1 = root_47();
      var text_3 = child(a_1);
      reset(a_1);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a_1, "href", $0);
          set_text(text_3, `${$1 ?? ""}
        ${$2 ?? ""}`);
        },
        [
          () => $urlFor()("holdings/by_account/"),
          () => _("Holdings by"),
          () => _("Account")
        ]
      );
      append($$anchor2, a_1);
    };
    if_block(node_1, ($$render) => {
      if ($$props.aggregation_key === "by_account") $$render(consequent_1);
      else $$render(alternate_1, false);
    });
  }
  reset(h3_1);
  var h3_2 = sibling(h3_1, 2);
  var node_2 = child(h3_2);
  {
    var consequent_2 = ($$anchor2) => {
      var text_4 = text();
      template_effect(($0, $1) => set_text(text_4, `${$0 ?? ""} ${$1 ?? ""}`), [
        () => _("Holdings by"),
        () => _("Currency")
      ]);
      append($$anchor2, text_4);
    };
    var alternate_2 = ($$anchor2) => {
      var a_2 = root_68();
      var text_5 = child(a_2);
      reset(a_2);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a_2, "href", $0);
          set_text(text_5, `${$1 ?? ""}
        ${$2 ?? ""}`);
        },
        [
          () => $urlFor()("holdings/by_currency/"),
          () => _("Holdings by"),
          () => _("Currency")
        ]
      );
      append($$anchor2, a_2);
    };
    if_block(node_2, ($$render) => {
      if ($$props.aggregation_key === "by_currency") $$render(consequent_2);
      else $$render(alternate_2, false);
    });
  }
  reset(h3_2);
  var h3_3 = sibling(h3_2, 2);
  var node_3 = child(h3_3);
  {
    var consequent_3 = ($$anchor2) => {
      var text_6 = text();
      template_effect(($0, $1) => set_text(text_6, `${$0 ?? ""} ${$1 ?? ""}`), [
        () => _("Holdings by"),
        () => _("Cost currency")
      ]);
      append($$anchor2, text_6);
    };
    var alternate_3 = ($$anchor2) => {
      var a_3 = root_83();
      var text_7 = child(a_3);
      reset(a_3);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a_3, "href", $0);
          set_text(text_7, `${$1 ?? ""}
        ${$2 ?? ""}`);
        },
        [
          () => $urlFor()("holdings/by_cost_currency/"),
          () => _("Holdings by"),
          () => _("Cost currency")
        ]
      );
      append($$anchor2, a_3);
    };
    if_block(node_3, ($$render) => {
      if ($$props.aggregation_key === "by_cost_currency") $$render(consequent_3);
      else $$render(alternate_3, false);
    });
  }
  reset(h3_3);
  reset(div);
  var p = sibling(div, 2);
  var a_4 = child(p);
  var text_8 = child(a_4, true);
  reset(a_4);
  var node_4 = sibling(a_4, 2);
  QueryLinks(node_4, {
    get query() {
      return $$props.query_string;
    }
  });
  reset(p);
  var node_5 = sibling(p, 2);
  QueryTable(node_5, {
    get table() {
      return $$props.query_result_table;
    },
    filter_empty: "units"
  });
  template_effect(
    ($0, $1) => {
      set_attribute(a_4, "href", $0);
      set_text(text_8, $1);
    },
    [
      () => $urlFor()("query", { query_string: $$props.query_string }),
      () => _("Query")
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/holdings/index.ts
var to_report_type2 = (s) => s === "by_account" || s === "by_currency" || s === "by_cost_currency" ? s : "all";
var QUERIES = {
  all: `
SELECT
  account,
  units(sum(position)) as units,
  cost_number as cost,
  first(getprice(currency, cost_currency)) as price,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct,
  cost_date as acquisition_date
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY account, cost_date, currency, cost_currency, cost_number, account_sortkey(account)
ORDER BY account_sortkey(account), currency, cost_date
`.trim(),
  by_account: `
SELECT
  account,
  units(sum(position)) as units,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY account, cost_currency, account_sortkey(account), currency
ORDER BY account_sortkey(account), currency
`.trim(),
  by_currency: `
SELECT
  units(sum(position)) as units,
  safediv(number(only(first(cost_currency), cost(sum(position)))), number(only(first(currency), units(sum(position))))) as average_cost,
  first(getprice(currency, cost_currency)) as price,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY currency, cost_currency
ORDER BY currency, cost_currency
`.trim(),
  by_cost_currency: `
SELECT
  units(sum(position)) as units,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY cost_currency
ORDER BY cost_currency
`.trim()
};
var holdings = new Route(
  "holdings",
  Holdings,
  async (url) => {
    const [, key2 = ""] = getUrlPath(url)?.split("/") ?? [];
    const aggregation_key = to_report_type2(key2);
    const query_string = QUERIES[aggregation_key];
    const query_result_table = await get3("query", {
      query_string,
      ...getURLFilters(url)
    });
    if (query_result_table.t !== "table") {
      throw new Error("Internal error: expected a query result table");
    }
    return { aggregation_key, query_string, query_result_table };
  },
  () => _("Holdings")
);

// node_modules/svelte/src/reactivity/map.js
var SvelteMap = class extends Map {
  /** @type {Map<K, Source<number>>} */
  #sources = /* @__PURE__ */ new Map();
  #version = source(0);
  #size = source(0);
  /**
   * @param {Iterable<readonly [K, V]> | null | undefined} [value]
   */
  constructor(value) {
    super();
    if (false_default) value = new Map(value);
    if (value) {
      for (var [key2, v] of value) {
        super.set(key2, v);
      }
      this.#size.v = super.size;
    }
  }
  /** @param {K} key */
  has(key2) {
    var sources = this.#sources;
    var s = sources.get(key2);
    if (s === void 0) {
      var ret = super.get(key2);
      if (ret !== void 0) {
        s = source(0);
        sources.set(key2, s);
      } else {
        get(this.#version);
        return false;
      }
    }
    get(s);
    return true;
  }
  /**
   * @param {(value: V, key: K, map: Map<K, V>) => void} callbackfn
   * @param {any} [this_arg]
   */
  forEach(callbackfn, this_arg) {
    this.#read_all();
    super.forEach(callbackfn, this_arg);
  }
  /** @param {K} key */
  get(key2) {
    var sources = this.#sources;
    var s = sources.get(key2);
    if (s === void 0) {
      var ret = super.get(key2);
      if (ret !== void 0) {
        s = source(0);
        sources.set(key2, s);
      } else {
        get(this.#version);
        return void 0;
      }
    }
    get(s);
    return super.get(key2);
  }
  /**
   * @param {K} key
   * @param {V} value
   * */
  set(key2, value) {
    var sources = this.#sources;
    var s = sources.get(key2);
    var prev_res = super.get(key2);
    var res2 = super.set(key2, value);
    var version = this.#version;
    if (s === void 0) {
      sources.set(key2, source(0));
      set(this.#size, super.size);
      increment(version);
    } else if (prev_res !== value) {
      increment(s);
      var v_reactions = version.reactions === null ? null : new Set(version.reactions);
      var needs_version_increase = v_reactions === null || !s.reactions?.every(
        (r2) => (
          /** @type {NonNullable<typeof v_reactions>} */
          v_reactions.has(r2)
        )
      );
      if (needs_version_increase) {
        increment(version);
      }
    }
    return res2;
  }
  /** @param {K} key */
  delete(key2) {
    var sources = this.#sources;
    var s = sources.get(key2);
    var res2 = super.delete(key2);
    if (s !== void 0) {
      sources.delete(key2);
      set(this.#size, super.size);
      set(s, -1);
      increment(this.#version);
    }
    return res2;
  }
  clear() {
    if (super.size === 0) {
      return;
    }
    super.clear();
    var sources = this.#sources;
    set(this.#size, 0);
    for (var s of sources.values()) {
      set(s, -1);
    }
    increment(this.#version);
    sources.clear();
  }
  #read_all() {
    get(this.#version);
    var sources = this.#sources;
    if (this.#size.v !== sources.size) {
      for (var key2 of super.keys()) {
        if (!sources.has(key2)) {
          sources.set(key2, source(0));
        }
      }
    }
    for (var [, s] of this.#sources) {
      get(s);
    }
  }
  keys() {
    get(this.#version);
    return super.keys();
  }
  values() {
    this.#read_all();
    return super.values();
  }
  entries() {
    this.#read_all();
    return super.entries();
  }
  [Symbol.iterator]() {
    return this.entries();
  }
  get size() {
    get(this.#size);
    return super.size;
  }
};

// node_modules/svelte/src/reactivity/url-search-params.js
var REPLACE = Symbol();
var SvelteURLSearchParams = class extends URLSearchParams {
  #version = source(0);
  #url = get_current_url();
  #updating = false;
  #update_url() {
    if (!this.#url || this.#updating) return;
    this.#updating = true;
    const search2 = this.toString();
    this.#url.search = search2 && `?${search2}`;
    this.#updating = false;
  }
  /**
   * @param {URLSearchParams} params
   */
  [REPLACE](params) {
    if (this.#updating) return;
    this.#updating = true;
    for (const key2 of [...super.keys()]) {
      super.delete(key2);
    }
    for (const [key2, value] of params) {
      super.append(key2, value);
    }
    increment(this.#version);
    this.#updating = false;
  }
  /**
   * @param {string} name
   * @param {string} value
   * @returns {void}
   */
  append(name3, value) {
    super.append(name3, value);
    this.#update_url();
    increment(this.#version);
  }
  /**
   * @param {string} name
   * @param {string=} value
   * @returns {void}
   */
  delete(name3, value) {
    var has_value = super.has(name3, value);
    super.delete(name3, value);
    if (has_value) {
      this.#update_url();
      increment(this.#version);
    }
  }
  /**
   * @param {string} name
   * @returns {string|null}
   */
  get(name3) {
    get(this.#version);
    return super.get(name3);
  }
  /**
   * @param {string} name
   * @returns {string[]}
   */
  getAll(name3) {
    get(this.#version);
    return super.getAll(name3);
  }
  /**
   * @param {string} name
   * @param {string=} value
   * @returns {boolean}
   */
  has(name3, value) {
    get(this.#version);
    return super.has(name3, value);
  }
  keys() {
    get(this.#version);
    return super.keys();
  }
  /**
   * @param {string} name
   * @param {string} value
   * @returns {void}
   */
  set(name3, value) {
    var previous = super.getAll(name3).join("");
    super.set(name3, value);
    if (previous !== super.getAll(name3).join("")) {
      this.#update_url();
      increment(this.#version);
    }
  }
  sort() {
    super.sort();
    this.#update_url();
    increment(this.#version);
  }
  toString() {
    get(this.#version);
    return super.toString();
  }
  values() {
    get(this.#version);
    return super.values();
  }
  entries() {
    get(this.#version);
    return super.entries();
  }
  [Symbol.iterator]() {
    return this.entries();
  }
  get size() {
    get(this.#version);
    return super.size;
  }
};

// node_modules/svelte/src/reactivity/url.js
var current_url = null;
function get_current_url() {
  return current_url;
}

// src/entry-forms/AddMetadataButton.svelte
var on_click7 = (__1, meta2) => {
  meta2(meta2().add());
};
var root37 = template(`<button type="button" class="muted round">m</button>`);
function AddMetadataButton($$anchor, $$props) {
  push($$props, true);
  let meta2 = prop($$props, "meta", 15);
  var button = root37();
  button.__click = [on_click7, meta2];
  set_attribute(button, "tabindex", -1);
  template_effect(($0) => set_attribute(button, "title", $0), [() => _("Add metadata")]);
  append($$anchor, button);
  pop();
}
delegate(["click"]);

// src/entry-forms/EntryMetadata.svelte
var on_click8 = (__1, meta2, key2) => {
  meta2(meta2().delete(key2()));
};
var on_change = (event2, meta2, key2) => {
  meta2(meta2().update_key(key2(), event2.currentTarget.value));
};
var on_change_1 = (event2, meta2, key2) => {
  meta2(meta2().set_string(key2(), event2.currentTarget.value));
};
var on_click_12 = (__2, meta2) => {
  meta2(meta2().add());
};
var root_216 = template(`<button type="button" class="muted round">+</button>`);
var root_130 = template(`<div class="flex-row svelte-1jx208h"><button type="button" class="muted round remove-row">\xD7</button> <input type="text" class="key svelte-1jx208h" required> <input type="text" class="value svelte-1jx208h"> <!></div>`);
function EntryMetadata2($$anchor, $$props) {
  push($$props, true);
  let meta2 = prop($$props, "meta", 15);
  let meta_entries = user_derived(() => meta2().entries());
  var fragment = comment();
  var node = first_child(fragment);
  each(node, 19, () => get(meta_entries), ([key2, value]) => key2, ($$anchor2, $$item, index3) => {
    let key2 = () => get($$item)[0];
    let value = () => get($$item)[1];
    var div = root_130();
    var button = child(div);
    button.__click = [on_click8, meta2, key2];
    set_attribute(button, "tabindex", -1);
    var input = sibling(button, 2);
    remove_input_defaults(input);
    input.__change = [on_change, meta2, key2];
    var input_1 = sibling(input, 2);
    remove_input_defaults(input_1);
    input_1.__change = [on_change_1, meta2, key2];
    var node_1 = sibling(input_1, 2);
    {
      var consequent = ($$anchor3) => {
        var button_1 = root_216();
        button_1.__click = [on_click_12, meta2];
        template_effect(($0) => set_attribute(button_1, "title", $0), [() => _("Add metadata")]);
        append($$anchor3, button_1);
      };
      if_block(node_1, ($$render) => {
        if (get(index3) === get(meta_entries).length - 1 && key2()) $$render(consequent);
      });
    }
    reset(div);
    template_effect(
      ($0, $1) => {
        set_attribute(input, "placeholder", $0);
        set_value(input, key2());
        set_attribute(input_1, "placeholder", $1);
        set_value(input_1, value());
      },
      [() => _("Key"), () => _("Value")]
    );
    append($$anchor2, div);
  });
  append($$anchor, fragment);
  pop();
}
delegate(["click", "change"]);

// src/entry-forms/Balance.svelte
var root38 = template(`<div class="svelte-unorr4"><div class="flex-row svelte-unorr4"><input type="date" required> <h4> </h4> <!> <input type="tel" pattern="-?[0-9.,]*" required> <!> <!></div> <!></div>`);
function Balance2($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $currencies = () => store_get(currencies, "$currencies", $$stores);
  let entry = prop($$props, "entry", 15);
  var div = root38();
  var div_1 = child(div);
  var input = child(div_1);
  remove_input_defaults(input);
  var h4 = sibling(input, 2);
  var text2 = child(h4, true);
  reset(h4);
  var node = sibling(h4, 2);
  var bind_get = () => entry().account;
  var bind_set = (account2) => {
    entry(entry().set("account", account2));
  };
  AccountInput(node, {
    className: "grow",
    get value() {
      return bind_get();
    },
    set value($$value) {
      bind_set($$value);
    },
    get date() {
      return entry().date;
    },
    required: true
  });
  var input_1 = sibling(node, 2);
  remove_input_defaults(input_1);
  set_attribute(input_1, "size", 10);
  var node_1 = sibling(input_1, 2);
  const expression = user_derived(() => _("Currency"));
  var bind_get_1 = () => entry().amount.currency;
  var bind_set_1 = (currency) => {
    entry(entry().set("amount", { ...entry().amount, currency }));
  };
  AutocompleteInput(node_1, {
    className: "currency",
    get placeholder() {
      return get(expression);
    },
    get suggestions() {
      return $currencies();
    },
    get value() {
      return bind_get_1();
    },
    set value($$value) {
      bind_set_1($$value);
    },
    required: true
  });
  var node_2 = sibling(node_1, 2);
  var bind_get_2 = () => entry().meta;
  var bind_set_2 = (meta2) => {
    entry(entry().set("meta", meta2));
  };
  AddMetadataButton(node_2, {
    get meta() {
      return bind_get_2();
    },
    set meta($$value) {
      bind_set_2($$value);
    }
  });
  reset(div_1);
  var node_3 = sibling(div_1, 2);
  var bind_get_3 = () => entry().meta;
  var bind_set_3 = (meta2) => {
    entry(entry().set("meta", meta2));
  };
  EntryMetadata2(node_3, {
    get meta() {
      return bind_get_3();
    },
    set meta($$value) {
      bind_set_3($$value);
    }
  });
  reset(div);
  template_effect(
    ($0, $1) => {
      set_text(text2, $0);
      set_attribute(input_1, "placeholder", $1);
    },
    [() => _("Balance"), () => _("Number")]
  );
  bind_value(input, () => entry().date, (date4) => {
    entry(entry().set("date", date4));
  });
  bind_value(input_1, () => entry().amount.number, (number7) => {
    entry(entry().set("amount", { ...entry().amount, number: number7 }));
  });
  append($$anchor, div);
  pop();
  $$cleanup();
}

// src/entry-forms/Note.svelte
var root39 = template(`<div><div class="flex-row"><input type="date" name="date" required> <h4> </h4> <!> <!></div> <textarea name="comment" class="svelte-s9o1z4"></textarea> <!></div>`);
function Note2($$anchor, $$props) {
  push($$props, true);
  let entry = prop($$props, "entry", 15);
  var div = root39();
  var div_1 = child(div);
  var input = child(div_1);
  remove_input_defaults(input);
  var h4 = sibling(input, 2);
  var text2 = child(h4, true);
  reset(h4);
  var node = sibling(h4, 2);
  var bind_get = () => entry().account;
  var bind_set = (account2) => {
    entry(entry().set("account", account2));
  };
  AccountInput(node, {
    className: "grow",
    get value() {
      return bind_get();
    },
    set value($$value) {
      bind_set($$value);
    },
    get date() {
      return entry().date;
    },
    required: true
  });
  var node_1 = sibling(node, 2);
  var bind_get_1 = () => entry().meta;
  var bind_set_1 = (meta2) => {
    entry(entry().set("meta", meta2));
  };
  AddMetadataButton(node_1, {
    get meta() {
      return bind_get_1();
    },
    set meta($$value) {
      bind_set_1($$value);
    }
  });
  reset(div_1);
  var textarea = sibling(div_1, 2);
  remove_textarea_child(textarea);
  set_attribute(textarea, "rows", 2);
  var node_2 = sibling(textarea, 2);
  var bind_get_2 = () => entry().meta;
  var bind_set_2 = (meta2) => {
    entry(entry().set("meta", meta2));
  };
  EntryMetadata2(node_2, {
    get meta() {
      return bind_get_2();
    },
    set meta($$value) {
      bind_set_2($$value);
    }
  });
  reset(div);
  template_effect(($0) => set_text(text2, $0), [() => _("Note")]);
  bind_value(input, () => entry().date, (date4) => {
    entry(entry().set("date", date4));
  });
  bind_value(textarea, () => entry().comment, (comment3) => {
    entry(entry().set("comment", comment3));
  });
  append($$anchor, div);
  pop();
}

// src/entry-forms/Posting.svelte
function mousemove(event2, draggable) {
  set(draggable, !(event2.target instanceof HTMLInputElement));
}
var root40 = template(`<div role="group"><button type="button" class="muted round remove-row svelte-192x5jl">\xD7</button> <!> <!> <!> <!></div>`);
function Posting2($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $currencies = () => store_get(currencies, "$currencies", $$stores);
  let posting = prop($$props, "posting", 15);
  let amount_number = user_derived(() => posting().amount.replace(/[^\-?0-9.]/g, ""));
  let amountSuggestions = user_derived(() => $currencies().map((c) => `${get(amount_number)} ${c}`));
  let drag = state(false);
  let draggable = state(true);
  function dragstart(event2) {
    event2.dataTransfer?.setData("fava/posting", $$props.index.toString());
  }
  function dragenter(event2) {
    const types2 = event2.dataTransfer?.types ?? [];
    if (types2.includes("fava/posting")) {
      event2.preventDefault();
      set(drag, true);
    }
  }
  function dragleave2() {
    set(drag, false);
  }
  function drop2(event2) {
    event2.preventDefault();
    const from = event2.dataTransfer?.getData("fava/posting");
    if (from != null) {
      $$props.move({ from: +from, to: $$props.index });
      set(drag, false);
    }
  }
  var div = root40();
  let classes;
  div.__mousemove = [mousemove, draggable];
  var button = child(div);
  button.__click = function(...$$args) {
    $$props.remove?.apply(this, $$args);
  };
  set_attribute(button, "tabindex", -1);
  var node = sibling(button, 2);
  var bind_get = () => posting().account;
  var bind_set = (account2) => {
    posting(posting().set("account", account2));
  };
  AccountInput(node, {
    className: "grow",
    get value() {
      return bind_get();
    },
    set value($$value) {
      bind_set($$value);
    },
    get suggestions() {
      return $$props.suggestions;
    },
    get date() {
      return $$props.date;
    }
  });
  var node_1 = sibling(node, 2);
  const expression = user_derived(() => _("Amount"));
  var bind_get_1 = () => posting().amount;
  var bind_set_1 = (amount) => {
    posting(posting().set("amount", amount));
  };
  AutocompleteInput(node_1, {
    className: "amount",
    get placeholder() {
      return get(expression);
    },
    get suggestions() {
      return get(amountSuggestions);
    },
    get value() {
      return bind_get_1();
    },
    set value($$value) {
      bind_set_1($$value);
    }
  });
  var node_2 = sibling(node_1, 2);
  var bind_get_2 = () => posting().meta;
  var bind_set_2 = (meta2) => {
    posting(posting().set("meta", meta2));
  };
  AddMetadataButton(node_2, {
    get meta() {
      return bind_get_2();
    },
    set meta($$value) {
      bind_set_2($$value);
    }
  });
  var node_3 = sibling(node_2, 2);
  var bind_get_3 = () => posting().meta;
  var bind_set_3 = (meta2) => {
    posting(posting().set("meta", meta2));
  };
  EntryMetadata2(node_3, {
    get meta() {
      return bind_get_3();
    },
    set meta($$value) {
      bind_set_3($$value);
    }
  });
  reset(div);
  template_effect(
    ($0) => {
      classes = set_class(div, 1, "flex-row svelte-192x5jl", null, classes, $0);
      set_attribute(div, "draggable", get(draggable));
    },
    [() => ({ drag: get(drag) })]
  );
  event("dragstart", div, dragstart);
  event("dragenter", div, dragenter);
  event("dragover", div, dragenter);
  event("dragleave", div, dragleave2);
  event("drop", div, drop2);
  append($$anchor, div);
  pop();
  $$cleanup();
}
delegate(["mousemove", "click"]);

// src/entry-forms/Transaction.svelte
var on_change2 = ({ currentTarget }, entry) => {
  entry(entry().set_narration_tags_links(currentTarget.value));
};
var root41 = template(`<div class="svelte-2x4ph3"><div class="flex-row svelte-2x4ph3"><input type="date" required> <input type="text" name="flag" required class="svelte-2x4ph3"> <label class="svelte-2x4ph3"><span class="svelte-2x4ph3"> </span> <!></label> <label class="svelte-2x4ph3"><span class="svelte-2x4ph3"> </span> <input type="text" name="narration" class="svelte-2x4ph3"> <!></label></div> <!> <div class="flex-row svelte-2x4ph3"><span class="label svelte-2x4ph3"><span class="svelte-2x4ph3"> </span></span></div> <!></div>`);
function Transaction3($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $payees = () => store_get(payees, "$payees", $$stores);
  let entry = prop($$props, "entry", 15);
  let suggestions = state(void 0);
  let payee = user_derived(() => entry().payee);
  user_effect(() => {
    if (get(payee)) {
      set(suggestions, void 0);
      if ($payees().includes(get(payee))) {
        get3("payee_accounts", { payee: get(payee) }).then((s) => {
          set(suggestions, s);
        }).catch((error2) => {
          notify_err(error2, (err3) => `Fetching account suggestions for payee ${get(payee)} failed: ${err3.message}`);
        });
      }
    }
  });
  let narration = user_derived(() => entry().get_narration_tags_links());
  async function autocompleteSelectPayee() {
    if (entry().narration || entry().postings.some((p) => !p.is_empty())) {
      return;
    }
    const payee_transaction = await get3("payee_transaction", { payee: entry().payee });
    entry(payee_transaction.set("date", entry().date));
  }
  user_effect(() => {
    if (!entry().postings.some((p) => p.is_empty())) {
      entry(entry().set("postings", entry().postings.concat(Posting.empty())));
    }
  });
  var div = root41();
  var div_1 = child(div);
  var input = child(div_1);
  remove_input_defaults(input);
  var input_1 = sibling(input, 2);
  remove_input_defaults(input_1);
  var label = sibling(input_1, 2);
  var span = child(label);
  var text2 = child(span);
  reset(span);
  var node = sibling(span, 2);
  const expression = user_derived(() => _("Payee"));
  var bind_get = () => entry().payee;
  var bind_set = (payee2) => {
    entry(entry().set("payee", payee2));
  };
  AutocompleteInput(node, {
    className: "payee",
    get placeholder() {
      return get(expression);
    },
    get value() {
      return bind_get();
    },
    set value($$value) {
      bind_set($$value);
    },
    get suggestions() {
      return $payees();
    },
    onSelect: autocompleteSelectPayee
  });
  reset(label);
  var label_1 = sibling(label, 2);
  var span_1 = child(label_1);
  var text_1 = child(span_1);
  reset(span_1);
  var input_2 = sibling(span_1, 2);
  remove_input_defaults(input_2);
  input_2.__change = [on_change2, entry];
  var node_1 = sibling(input_2, 2);
  var bind_get_1 = () => entry().meta;
  var bind_set_1 = (meta2) => {
    entry(entry().set("meta", meta2));
  };
  AddMetadataButton(node_1, {
    get meta() {
      return bind_get_1();
    },
    set meta($$value) {
      bind_set_1($$value);
    }
  });
  reset(label_1);
  reset(div_1);
  var node_2 = sibling(div_1, 2);
  var bind_get_2 = () => entry().meta;
  var bind_set_2 = (meta2) => {
    entry(entry().set("meta", meta2));
  };
  EntryMetadata2(node_2, {
    get meta() {
      return bind_get_2();
    },
    set meta($$value) {
      bind_set_2($$value);
    }
  });
  var div_2 = sibling(node_2, 2);
  var span_2 = child(div_2);
  var span_3 = child(span_2);
  var text_2 = child(span_3);
  reset(span_3);
  reset(span_2);
  reset(div_2);
  var node_3 = sibling(div_2, 2);
  each(node_3, 17, () => entry().postings, index, ($$anchor2, posting, index3) => {
    var bind_get_3 = () => get(posting);
    var bind_set_3 = (posting2) => {
      entry(entry().set("postings", entry().postings.with(index3, posting2)));
    };
    Posting2($$anchor2, {
      get posting() {
        return bind_get_3();
      },
      set posting($$value) {
        bind_set_3($$value);
      },
      index: index3,
      get suggestions() {
        return get(suggestions);
      },
      get date() {
        return entry().date;
      },
      move: ({ from, to }) => {
        entry(entry().set("postings", move2(entry().postings, from, to)));
      },
      remove: () => {
        entry(entry().set("postings", entry().postings.toSpliced(index3, 1)));
      }
    });
  });
  reset(div);
  template_effect(
    ($0, $1, $2, $3) => {
      set_text(text2, `${$0 ?? ""}:`);
      set_text(text_1, `${$1 ?? ""}:`);
      set_attribute(input_2, "placeholder", $2);
      set_value(input_2, get(narration));
      set_text(text_2, `${$3 ?? ""}:`);
    },
    [
      () => _("Payee"),
      () => _("Narration"),
      () => _("Narration"),
      () => _("Postings")
    ]
  );
  bind_value(input, () => entry().date, (date4) => {
    entry(entry().set("date", date4));
  });
  bind_value(input_1, () => entry().flag, (flag) => {
    entry(entry().set("flag", flag));
  });
  append($$anchor, div);
  pop();
  $$cleanup();
}
delegate(["change"]);

// src/entry-forms/Entry.svelte
function Entry($$anchor, $$props) {
  push($$props, true);
  let entry = prop($$props, "entry", 15);
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      Balance2($$anchor2, {
        get entry() {
          return entry();
        },
        set entry($$value) {
          entry($$value);
        }
      });
    };
    var alternate = ($$anchor2, $$elseif) => {
      {
        var consequent_1 = ($$anchor3) => {
          Note2($$anchor3, {
            get entry() {
              return entry();
            },
            set entry($$value) {
              entry($$value);
            }
          });
        };
        var alternate_1 = ($$anchor3, $$elseif2) => {
          {
            var consequent_2 = ($$anchor4) => {
              Transaction3($$anchor4, {
                get entry() {
                  return entry();
                },
                set entry($$value) {
                  entry($$value);
                }
              });
            };
            var alternate_2 = ($$anchor4) => {
              var text2 = text("Entry type unsupported for editing.");
              append($$anchor4, text2);
            };
            if_block(
              $$anchor3,
              ($$render) => {
                if (entry() instanceof Transaction) $$render(consequent_2);
                else $$render(alternate_2, false);
              },
              $$elseif2
            );
          }
        };
        if_block(
          $$anchor2,
          ($$render) => {
            if (entry() instanceof Note) $$render(consequent_1);
            else $$render(alternate_1, false);
          },
          $$elseif
        );
      }
    };
    if_block(node, ($$render) => {
      if (entry() instanceof Balance) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  append($$anchor, fragment);
  pop();
}

// src/reports/import/Extract.svelte
function previousEntry(__1, currentIndex) {
  set(currentIndex, Math.max(get(currentIndex) - 1, 0));
}
function toggleDuplicate(__2, entry, entries, currentIndex) {
  if (get(entry)) {
    entries(entries()[get(currentIndex)] = get(entry).set_meta("__duplicate__", !get(entry).is_duplicate()), true);
  }
}
var on_click9 = (__3, currentIndex) => {
  set(currentIndex, 0);
};
var root_39 = template(`<button type="button" class="muted">\u23EE</button> <button type="button" class="muted"> </button>`, 1);
var on_click_13 = (__4, currentIndex, entries) => {
  set(currentIndex, entries().length - 1);
};
var root_48 = template(`<button type="submit"> </button> <button type="button" class="muted">\u23ED</button>`, 1);
var root_58 = template(`<button type="submit"> </button>`);
var root_69 = template(`<h3> <!></h3> <pre class="svelte-kordbm"> </pre>`, 1);
var root_217 = template(`<div class="flex-row"><h3> </h3> <span class="spacer"></span> <label class="button muted"><input type="checkbox"> </label></div> <div><!></div> <div class="flex-row"><!> <span class="spacer"></span> <!></div> <hr> <!>`, 1);
var root_131 = template(`<form><h3> </h3> <!></form>`);
function Extract($$anchor, $$props) {
  push($$props, true);
  let entries = prop($$props, "entries", 15);
  let currentIndex = state(0);
  let count2 = user_derived(() => entries().length);
  let shown = user_derived(() => get(count2) > 0);
  let entry = user_derived(() => entries()[get(currentIndex)]);
  let duplicate = user_derived(() => get(entry)?.is_duplicate());
  let count_duplicates = user_derived(() => entries().filter((e) => e.is_duplicate()).length);
  user_effect(() => {
    if (get(count2) > 0 && get(currentIndex) >= get(count2)) {
      set(currentIndex, 0);
    }
  });
  function submitOrNext(event2) {
    event2.preventDefault();
    if (get(currentIndex) < get(count2) - 1) {
      set(currentIndex, get(currentIndex) + 1);
    } else {
      $$props.save();
    }
  }
  let current_index_from_one = user_derived(() => get(currentIndex) + 1);
  let count_without_duplicates = user_derived(() => get(count2) - get(count_duplicates));
  ModalBase($$anchor, {
    get shown() {
      return get(shown);
    },
    get closeHandler() {
      return $$props.close;
    },
    children: ($$anchor2, $$slotProps) => {
      var form = root_131();
      var h3 = child(form);
      var text2 = child(h3, true);
      reset(h3);
      var node = sibling(h3, 2);
      {
        var consequent_4 = ($$anchor3) => {
          var fragment_1 = root_217();
          var div = first_child(fragment_1);
          var h3_1 = child(div);
          var text_1 = child(h3_1);
          reset(h3_1);
          var label = sibling(h3_1, 4);
          var input = child(label);
          remove_input_defaults(input);
          input.__click = [
            toggleDuplicate,
            entry,
            entries,
            currentIndex
          ];
          var text_2 = sibling(input);
          reset(label);
          reset(div);
          var div_1 = sibling(div, 2);
          let classes;
          var node_1 = child(div_1);
          var bind_get = () => get(entry);
          var bind_set = (entry2) => {
            entries(entries()[get(currentIndex)] = entry2, true);
          };
          Entry(node_1, {
            get entry() {
              return bind_get();
            },
            set entry($$value) {
              bind_set($$value);
            }
          });
          reset(div_1);
          var div_2 = sibling(div_1, 2);
          var node_2 = child(div_2);
          {
            var consequent = ($$anchor4) => {
              var fragment_2 = root_39();
              var button = first_child(fragment_2);
              button.__click = [on_click9, currentIndex];
              var button_1 = sibling(button, 2);
              button_1.__click = [previousEntry, currentIndex];
              var text_3 = child(button_1, true);
              reset(button_1);
              template_effect(($0) => set_text(text_3, $0), [() => _("Previous")]);
              append($$anchor4, fragment_2);
            };
            if_block(node_2, ($$render) => {
              if (get(currentIndex) > 0) $$render(consequent);
            });
          }
          var node_3 = sibling(node_2, 4);
          {
            var consequent_1 = ($$anchor4) => {
              var fragment_3 = root_48();
              var button_2 = first_child(fragment_3);
              var text_4 = child(button_2, true);
              reset(button_2);
              var button_3 = sibling(button_2, 2);
              button_3.__click = [on_click_13, currentIndex, entries];
              template_effect(($0) => set_text(text_4, $0), [() => _("Next")]);
              append($$anchor4, fragment_3);
            };
            var alternate = ($$anchor4) => {
              var button_4 = root_58();
              var text_5 = child(button_4, true);
              reset(button_4);
              template_effect(($0) => set_text(text_5, $0), [() => _("Save")]);
              append($$anchor4, button_4);
            };
            if_block(node_3, ($$render) => {
              if (get(currentIndex) < entries().length - 1) $$render(consequent_1);
              else $$render(alternate, false);
            });
          }
          reset(div_2);
          var node_4 = sibling(div_2, 4);
          {
            var consequent_3 = ($$anchor4) => {
              var fragment_4 = root_69();
              var h3_2 = first_child(fragment_4);
              var text_6 = child(h3_2);
              var node_5 = sibling(text_6);
              {
                var consequent_2 = ($$anchor5) => {
                  var text_7 = text();
                  template_effect(($0) => set_text(text_7, `(${$0 ?? ""}: ${get(entry).meta.lineno ?? ""})`), [() => _("Line")]);
                  append($$anchor5, text_7);
                };
                if_block(node_5, ($$render) => {
                  if (get(entry).meta.lineno) $$render(consequent_2);
                });
              }
              reset(h3_2);
              var pre = sibling(h3_2, 2);
              var text_8 = child(pre, true);
              reset(pre);
              template_effect(
                ($0, $1) => {
                  set_text(text_6, `${$0 ?? ""} `);
                  set_text(text_8, $1);
                },
                [
                  () => _("Source"),
                  () => get(entry).meta.get("__source__")
                ]
              );
              append($$anchor4, fragment_4);
            };
            if_block(node_4, ($$render) => {
              if (get(entry).meta.get("__source__")) $$render(consequent_3);
            });
          }
          template_effect(
            ($0, $1) => {
              set_text(text_1, `Entry
          ${get(current_index_from_one) ?? ""}
          of
          ${get(count2) ?? ""}
          (${get(count_without_duplicates) ?? ""}
          to import):`);
              set_checked(input, get(duplicate));
              set_text(text_2, ` ${$0 ?? ""}`);
              classes = set_class(div_1, 1, "svelte-kordbm", null, classes, $1);
            },
            [
              () => _("ignore duplicate"),
              () => ({ duplicate: get(duplicate) })
            ]
          );
          append($$anchor3, fragment_1);
        };
        if_block(node, ($$render) => {
          if (get(entry)) $$render(consequent_4);
        });
      }
      reset(form);
      template_effect(
        ($0) => {
          form.noValidate = get(duplicate);
          set_text(text2, $0);
        },
        [() => _("Import")]
      );
      event("submit", form, submitOrNext);
      append($$anchor2, form);
    },
    $$slots: { default: true }
  });
  pop();
}
delegate(["click"]);

// src/reports/import/FileList.svelte
var on_click10 = (__1, selected, file) => {
  selected(selected() === get(file).name ? null : get(file).name);
};
var on_click_14 = (__2, $$props, file) => {
  $$props.remove(get(file).name);
};
var on_click_2 = (__3, $$props, file, info2) => {
  $$props.extract(get(file).name, get(info2).importer_name);
};
var on_click_3 = (__4, $$props, file_importer_key) => {
  $$props.extract_cache.delete(get(file_importer_key));
};
var root_49 = template(`<button type="button"> </button>`);
var root_310 = template(`<button type="button"> </button> <!> `, 1);
var root_218 = template(`<form class="flex-row"><!> <input> <button type="submit"> </button> <!></form>`);
var root_133 = template(`<div><button type="button" class="unset svelte-1m0su6q"> </button> <button type="button" class="round svelte-1m0su6q">\xD7</button></div> <!>`, 1);
function FileList($$anchor, $$props) {
  push($$props, true);
  let selected = prop($$props, "selected", 15);
  var fragment = comment();
  var node = first_child(fragment);
  each(node, 17, () => $$props.files, index, ($$anchor2, file) => {
    var fragment_1 = root_133();
    var div = first_child(fragment_1);
    let classes;
    var button = child(div);
    button.__click = [on_click10, selected, file];
    var text2 = child(button, true);
    reset(button);
    var button_1 = sibling(button, 2);
    button_1.__click = [on_click_14, $$props, file];
    set_attribute(button_1, "tabindex", -1);
    reset(div);
    var node_1 = sibling(div, 2);
    each(node_1, 17, () => get(file).importers, index, ($$anchor3, info2) => {
      var form = root_218();
      const file_importer_key = user_derived(() => `${get(file).name}:${get(info2).importer_name}`);
      const account2 = user_derived(() => $$props.file_accounts.get(get(file_importer_key)) ?? get(info2).account);
      const new_name = user_derived(() => $$props.file_names.get(get(file_importer_key)) ?? get(info2).newName);
      var node_2 = child(form);
      var bind_get = () => get(account2);
      var bind_set = (value) => {
        $$props.file_accounts.set(get(file_importer_key), value);
      };
      AccountInput(node_2, {
        get value() {
          return bind_get();
        },
        set value($$value) {
          bind_set($$value);
        },
        required: true
      });
      var input = sibling(node_2, 2);
      remove_input_defaults(input);
      set_attribute(input, "size", 40);
      var button_2 = sibling(input, 2);
      var text_1 = child(button_2, true);
      reset(button_2);
      var node_3 = sibling(button_2, 2);
      {
        var consequent_1 = ($$anchor4) => {
          var fragment_2 = root_310();
          const is_cached = user_derived(() => $$props.extract_cache.has(get(file_importer_key)));
          var button_3 = first_child(fragment_2);
          button_3.__click = [on_click_2, $$props, file, info2];
          var text_2 = child(button_3, true);
          reset(button_3);
          var node_4 = sibling(button_3, 2);
          {
            var consequent = ($$anchor5) => {
              var button_4 = root_49();
              button_4.__click = [on_click_3, $$props, file_importer_key];
              var text_3 = child(button_4, true);
              reset(button_4);
              template_effect(($0) => set_text(text_3, $0), [() => _("Clear")]);
              append($$anchor5, button_4);
            };
            if_block(node_4, ($$render) => {
              if (get(is_cached)) $$render(consequent);
            });
          }
          var text_4 = sibling(node_4);
          template_effect(
            ($0, $1) => {
              set_attribute(button_3, "title", `${$0 ?? ""} with importer ${get(info2).importer_name ?? ""}`);
              set_text(text_2, $1);
              set_text(text_4, ` ${get(info2).importer_name ?? ""}`);
            },
            [
              () => _("Extract"),
              () => get(is_cached) ? _("Continue") : _("Extract")
            ]
          );
          append($$anchor4, fragment_2);
        };
        if_block(node_3, ($$render) => {
          if (get(info2).importer_name) $$render(consequent_1);
        });
      }
      reset(form);
      template_effect(($0) => set_text(text_1, $0), [() => _("Move")]);
      event("submit", form, (event2) => {
        event2.preventDefault();
        $$props.move(get(file).name, get(account2), get(new_name));
      });
      bind_value(input, () => get(new_name), (value) => {
        $$props.file_names.set(get(file_importer_key), value);
      });
      append($$anchor3, form);
    });
    template_effect(
      ($0, $1) => {
        classes = set_class(div, 1, "header svelte-1m0su6q", null, classes, $0);
        set_attribute(div, "title", get(file).name);
        set_text(text2, get(file).basename);
        set_attribute(button_1, "title", $1);
      },
      [
        () => ({
          selected: selected() === get(file).name
        }),
        () => _("Delete")
      ]
    );
    append($$anchor2, fragment_1);
  });
  append($$anchor, fragment);
  pop();
}
delegate(["click"]);

// src/reports/import/ImportFileUpload.svelte
var root42 = template(`<form><h2> </h2> <input multiple type="file"> <button type="submit"> </button></form>`);
function ImportFileUpload($$anchor, $$props) {
  push($$props, true);
  let input = state(void 0);
  async function uploadImports(event2) {
    event2.preventDefault();
    if (get(input)?.files == null) {
      return;
    }
    await Promise.all(Array.from(get(input).files).map(async (file) => {
      const formData = new FormData();
      formData.append("file", file, file.name);
      return put("upload_import_file", formData).then(notify, (error2) => {
        notify_err(error2, (err3) => `Upload error: ${err3.message}`);
      });
    }));
    get(input).value = "";
    router_default.reload();
  }
  var form = root42();
  var h2 = child(form);
  var text2 = child(h2, true);
  reset(h2);
  var input_1 = sibling(h2, 2);
  bind_this(input_1, ($$value) => set(input, $$value), () => get(input));
  var button = sibling(input_1, 2);
  var text_1 = child(button, true);
  reset(button);
  reset(form);
  template_effect(
    ($0, $1) => {
      set_text(text2, $0);
      set_text(text_1, $1);
    },
    [
      () => _("Upload files for import"),
      () => _("Upload")
    ]
  );
  event("submit", form, uploadImports);
  append($$anchor, form);
  pop();
}

// src/reports/import/Import.svelte
var root_134 = template(`<p>No importers configured. See <a>Help (Import)</a> for more information.</p>`);
var root_311 = template(`<p> </p>`);
var root_410 = template(`<div><h2> </h2> <!></div> <hr class="svelte-9ktust">`, 1);
var root_59 = template(`<details><summary> </summary> <!></details>`);
var root_610 = template(`<div class="svelte-9ktust"><!></div>`);
var root_219 = template(`<!> <div class="fixed-fullsize-container svelte-9ktust"><div class="filelist svelte-9ktust"><!> <!> <!> <!></div> <!></div>`, 1);
function Import($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $fava_options = () => store_get(fava_options, "$fava_options", $$stores);
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  let show_other_files = state(
    // initially show the other files if no importable files are present
    $$props.files.every((file) => !file.identified_by_importers)
  );
  let entries = state(proxy2([]));
  let selected = state(null);
  let extract_cache = new SvelteMap();
  let file_accounts = new SvelteMap();
  let file_names = new SvelteMap();
  let importable_files = user_derived(() => $$props.files.filter((file) => file.identified_by_importers));
  let other_files = user_derived(() => $$props.files.filter((file) => !file.identified_by_importers));
  const preventNavigation = () => extract_cache.size > 0 ? "There are unfinished imports, are you sure you want to continue?" : null;
  onMount(() => router_default.addInteruptHandler(preventNavigation));
  async function move3(filename, account2, newName) {
    const moved = await moveDocument(filename, account2, newName);
    if (moved) {
      router_default.reload();
    }
  }
  async function remove3(filename) {
    if (!window.confirm(_("Delete this file?"))) {
      return;
    }
    const removed = await deleteDocument(filename);
    if (removed) {
      if (get(selected) === filename) {
        set(selected, null);
      }
      router_default.reload();
    }
  }
  async function extract(filename, importer) {
    const file_importer_key = `${filename}:${importer}`;
    const cached = extract_cache.get(file_importer_key);
    if (cached) {
      set(entries, cached, true);
      return;
    }
    try {
      set(entries, await get3("extract", { filename, importer }), true);
      if (get(entries).length) {
        extract_cache.set(file_importer_key, get(entries));
      } else {
        notify("No entries to import from this file.", "warning");
      }
    } catch (error2) {
      notify_err(error2);
    }
  }
  async function save() {
    const without_duplicates = get(entries).filter((e) => !e.is_duplicate());
    const key2 = [...extract_cache].find(([, e]) => e === get(entries))?.[0];
    if (key2 != null) {
      extract_cache.delete(key2);
    }
    set(entries, [], true);
    await saveEntries(without_duplicates);
  }
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var p = root_134();
      var a = sibling(child(p));
      next();
      reset(p);
      template_effect(($0) => set_attribute(a, "href", $0), [() => $urlFor()("help/import")]);
      append($$anchor2, p);
    };
    var alternate = ($$anchor2) => {
      var fragment_1 = root_219();
      var node_1 = first_child(fragment_1);
      Extract(node_1, {
        close: () => {
          set(entries, [], true);
        },
        save,
        get entries() {
          return get(entries);
        },
        set entries($$value) {
          set(entries, $$value, true);
        }
      });
      var div = sibling(node_1, 2);
      var div_1 = child(div);
      var node_2 = child(div_1);
      {
        var consequent_1 = ($$anchor3) => {
          var p_1 = root_311();
          var text2 = child(p_1, true);
          reset(p_1);
          template_effect(($0) => set_text(text2, $0), [() => _("No files were found for import.")]);
          append($$anchor3, p_1);
        };
        if_block(node_2, ($$render) => {
          if ($$props.files.length === 0) $$render(consequent_1);
        });
      }
      var node_3 = sibling(node_2, 2);
      {
        var consequent_2 = ($$anchor3) => {
          var fragment_2 = root_410();
          var div_2 = first_child(fragment_2);
          var h2 = child(div_2);
          var text_1 = child(h2, true);
          reset(h2);
          var node_4 = sibling(h2, 2);
          FileList(node_4, {
            get files() {
              return get(importable_files);
            },
            extract_cache,
            file_accounts,
            file_names,
            move: move3,
            remove: remove3,
            extract,
            get selected() {
              return get(selected);
            },
            set selected($$value) {
              set(selected, $$value);
            }
          });
          reset(div_2);
          next(2);
          template_effect(($0) => set_text(text_1, $0), [() => _("Importable Files")]);
          append($$anchor3, fragment_2);
        };
        if_block(node_3, ($$render) => {
          if (get(importable_files).length > 0) $$render(consequent_2);
        });
      }
      var node_5 = sibling(node_3, 2);
      {
        var consequent_3 = ($$anchor3) => {
          var details = root_59();
          var summary = child(details);
          var text_2 = child(summary, true);
          reset(summary);
          var node_6 = sibling(summary, 2);
          FileList(node_6, {
            get files() {
              return get(other_files);
            },
            extract_cache,
            file_accounts,
            file_names,
            move: move3,
            remove: remove3,
            extract,
            get selected() {
              return get(selected);
            },
            set selected($$value) {
              set(selected, $$value);
            }
          });
          reset(details);
          template_effect(($0) => set_text(text_2, $0), [() => _("Non-importable Files")]);
          bind_property("open", "toggle", details, ($$value) => set(show_other_files, $$value), () => get(show_other_files));
          append($$anchor3, details);
        };
        if_block(node_5, ($$render) => {
          if (get(other_files).length > 0) $$render(consequent_3);
        });
      }
      var node_7 = sibling(node_5, 2);
      ImportFileUpload(node_7, {});
      reset(div_1);
      var node_8 = sibling(div_1, 2);
      {
        var consequent_4 = ($$anchor3) => {
          var div_3 = root_610();
          var node_9 = child(div_3);
          DocumentPreview(node_9, {
            get filename() {
              return get(selected);
            }
          });
          reset(div_3);
          append($$anchor3, div_3);
        };
        if_block(node_8, ($$render) => {
          if (get(selected)) $$render(consequent_4);
        });
      }
      reset(div);
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if ($fava_options().import_config == null) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/import/index.ts
function newFilename(date4, basename2) {
  return /^\d{4}-\d{2}-\d{2}/.test(basename2) ? basename2 : `${date4} ${basename2}`;
}
var import_report = new Route(
  "import",
  Import,
  async () => get3("imports", void 0).then((files2) => {
    const today = todayAsString();
    return files2.map((file) => {
      const importers = file.importers.map(
        ({ account: account2, importer_name, date: date4, name: name3 }) => ({
          account: account2,
          importer_name,
          newName: newFilename(date4, name3)
        })
      );
      const identified_by_importers = importers.length > 0;
      if (!identified_by_importers) {
        const newName = newFilename(today, file.basename);
        importers.push({ account: "", newName, importer_name: "" });
      }
      return { ...file, identified_by_importers, importers };
    });
  }).then((files2) => ({ files: files2 })),
  () => _("Import")
);

// src/reports/options/OptionsTable.svelte
var root_220 = template(`<tr><td class="svelte-5xmebc"> </td><td class="svelte-5xmebc"><pre> </pre></td></tr>`);
var root43 = template(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function OptionsTable($$anchor, $$props) {
  push($$props, true);
  const columns3 = [
    new StringColumn(_("Key"), (d) => d[0]),
    new StringColumn(_("Value"), (d) => d[1])
  ];
  let sorter = state(proxy2(new Sorter(columns3[0], "asc")));
  let options_array = user_derived(() => Object.entries($$props.options));
  let sorted_options = user_derived(() => get(sorter).sort(get(options_array)));
  var table = root43();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 21, () => columns3, index, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return get(column);
      },
      get sorter() {
        return get(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get(sorted_options), ([key2, value]) => key2, ($$anchor2, $$item) => {
    let key2 = () => get($$item)[0];
    let value = () => get($$item)[1];
    var tr_1 = root_220();
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var pre = child(td_1);
    var text_1 = child(pre, true);
    reset(pre);
    reset(td_1);
    reset(tr_1);
    template_effect(() => {
      set_text(text2, key2());
      set_text(text_1, value());
    });
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
}

// src/reports/options/Options.svelte
var root44 = template(`<h2> <a> </a></h2> <!> <h2> </h2> <!>`, 1);
function Options($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  var fragment = root44();
  var h2 = first_child(fragment);
  var text2 = child(h2);
  var a = sibling(text2);
  var text_1 = child(a);
  reset(a);
  reset(h2);
  var node = sibling(h2, 2);
  OptionsTable(node, {
    get options() {
      return $$props.fava_options;
    }
  });
  var h2_1 = sibling(node, 2);
  var text_2 = child(h2_1, true);
  reset(h2_1);
  var node_1 = sibling(h2_1, 2);
  OptionsTable(node_1, {
    get options() {
      return $$props.beancount_options;
    }
  });
  template_effect(
    ($0, $1, $2, $3) => {
      set_text(text2, `${$0 ?? ""} `);
      set_attribute(a, "href", $1);
      set_text(text_1, `(${$2 ?? ""})`);
      set_text(text_2, $3);
    },
    [
      () => _("Fava options"),
      () => $urlFor()("help/options"),
      () => _("help"),
      () => _("Beancount options")
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/options/index.ts
var options3 = new Route(
  "options",
  Options,
  async () => get3("options"),
  () => _("Options")
);

// src/stores/query.ts
var { update: update2, set: set3, subscribe } = localStorageSyncedStore(
  "query-history",
  array(string),
  () => []
);
var query_shell_history = {
  subscribe,
  /** Completely clear the history. */
  clear() {
    set3([]);
  },
  /** Add a new entry to the query history (this does avoid duplicates). */
  add(query2) {
    if (query2) {
      update2((hist) => [.../* @__PURE__ */ new Set([query2, ...hist])]);
    }
  },
  /** Remove a query string from the query history. */
  remove(query2) {
    if (query2) {
      update2((hist) => hist.filter((item) => item !== query2));
    }
  }
};

// src/charts/query-charts.ts
function getQueryChart(table, $chartContext) {
  const { columns: columns3 } = table;
  const [first, second2] = columns3;
  if (!first || !second2 || columns3.length > 2) {
    return null;
  }
  if (first.dtype === "str" && second2.dtype === "Inventory") {
    const grouped = table.rows.map(
      ([group2, inv]) => ({ group: group2, balance: inv.value })
    );
    const root68 = stratify(
      grouped,
      (d) => d.group,
      (account2, d) => ({ account: account2, balance: d?.balance ?? {} })
    );
    root68.account = "(root)";
    return hierarchy_from_parsed_data(null, root68, $chartContext);
  }
  if (first.dtype === "date" && second2.dtype === "Inventory") {
    const bals = table.rows.map(([date4, inv]) => ({
      date: date4,
      balance: inv.value
    }));
    return balances_from_parsed_data(null, bals);
  }
  return null;
}

// src/reports/query/ReadonlyQueryEditor.svelte
var root45 = template(`<pre></pre>`);
function ReadonlyQueryEditor($$anchor, $$props) {
  push($$props, true);
  let error2 = prop($$props, "error", 3, false);
  const { renderEditor } = initReadonlyQueryEditor($$props.value);
  var pre = root45();
  let classes;
  action(pre, ($$node) => renderEditor?.($$node));
  template_effect(($0) => classes = set_class(pre, 1, "svelte-tsbqgk", null, classes, $0), [() => ({ error: error2() })]);
  append($$anchor, pre);
  pop();
}

// src/reports/query/QueryBox.svelte
var root_411 = template(`<pre class="svelte-1ghioct"><code> </code></pre>`);
var root_510 = template(`<!> <!>`, 1);
var root_73 = template(`<pre class="svelte-1ghioct"><code> </code></pre>`);
var root46 = template(`<details class="svelte-1ghioct"><summary><!> <span class="spacer"></span> <!> <button type="button">x</button></summary> <div class="svelte-1ghioct"><!></div></details>`);
function QueryBox($$anchor, $$props) {
  push($$props, false);
  const [$$stores, $$cleanup] = setup_stores();
  const $chartContext = () => store_get(chartContext, "$chartContext", $$stores);
  const inactive = mutable_source(void 0, true);
  const chart = mutable_source(void 0, true);
  let query2 = prop($$props, "query", 9);
  let result = prop($$props, "result", 9);
  let open = prop($$props, "open", 13);
  let onselect = prop($$props, "onselect", 9);
  let ondelete = prop($$props, "ondelete", 9);
  legacy_pre_effect(() => deep_read_state(result()), () => {
    set(inactive, !result());
  });
  legacy_pre_effect(
    () => (deep_read_state(result()), getQueryChart, $chartContext()),
    () => {
      set(chart, result() && result().is_ok && result().value.t === "table" ? getQueryChart(result().value, $chartContext()) : null);
    }
  );
  legacy_pre_effect_reset();
  init2(true);
  var details = root46();
  var summary = child(details);
  let classes;
  var node = child(summary);
  const expression = derived_safe_equal(() => result()?.is_err);
  ReadonlyQueryEditor(node, {
    get value() {
      return query2();
    },
    get error() {
      return get(expression);
    }
  });
  var node_1 = sibling(node, 4);
  {
    var consequent = ($$anchor2) => {
      QueryLinks($$anchor2, {
        get query() {
          return query2();
        }
      });
    };
    if_block(node_1, ($$render) => {
      if (result() && result().is_ok && result().value.t === "table") $$render(consequent);
    });
  }
  var button = sibling(node_1, 2);
  reset(summary);
  var div = sibling(summary, 2);
  var node_2 = child(div);
  {
    var consequent_4 = ($$anchor2) => {
      var fragment_1 = comment();
      var node_3 = first_child(fragment_1);
      {
        var consequent_3 = ($$anchor3) => {
          var fragment_2 = comment();
          var node_4 = first_child(fragment_2);
          {
            var consequent_1 = ($$anchor4) => {
              var pre = root_411();
              var code = child(pre);
              var text2 = child(code, true);
              reset(code);
              reset(pre);
              template_effect(() => set_text(text2, result().value.contents));
              append($$anchor4, pre);
            };
            var alternate = ($$anchor4) => {
              var fragment_3 = root_510();
              var node_5 = first_child(fragment_3);
              {
                var consequent_2 = ($$anchor5) => {
                  Chart($$anchor5, {
                    get chart() {
                      return get(chart);
                    }
                  });
                };
                if_block(node_5, ($$render) => {
                  if (get(chart)) $$render(consequent_2);
                });
              }
              var node_6 = sibling(node_5, 2);
              QueryTable(node_6, {
                get table() {
                  return result().value;
                }
              });
              append($$anchor4, fragment_3);
            };
            if_block(node_4, ($$render) => {
              if (result().value.t === "string") $$render(consequent_1);
              else $$render(alternate, false);
            });
          }
          append($$anchor3, fragment_2);
        };
        var alternate_1 = ($$anchor3) => {
          var pre_1 = root_73();
          var code_1 = child(pre_1);
          var text_1 = child(code_1, true);
          reset(code_1);
          reset(pre_1);
          template_effect(() => set_text(text_1, result().error));
          append($$anchor3, pre_1);
        };
        if_block(node_3, ($$render) => {
          if (result().is_ok) $$render(consequent_3);
          else $$render(alternate_1, false);
        });
      }
      append($$anchor2, fragment_1);
    };
    if_block(node_2, ($$render) => {
      if (result()) $$render(consequent_4);
    });
  }
  reset(div);
  reset(details);
  template_effect(($0) => classes = set_class(summary, 1, "svelte-1ghioct", null, classes, $0), [() => ({ inactive: get(inactive) })], derived_safe_equal);
  event("click", button, (ev) => {
    ev.stopPropagation();
    ondelete()();
  });
  event("click", summary, function(...$$args) {
    (get(inactive) ? onselect() : null)?.apply(this, $$args);
  });
  bind_property("open", "toggle", details, open, open);
  append($$anchor, details);
  pop();
  $$cleanup();
}

// src/reports/query/QueryEditor.svelte
var root47 = template(`<form class="svelte-1wk8z7p"><div class="svelte-1wk8z7p"></div> <button type="submit" class="svelte-1wk8z7p"> </button></form>`);
function QueryEditor($$anchor, $$props) {
  push($$props, false);
  let value = prop($$props, "value", 12);
  let submit = prop($$props, "submit", 8);
  const { editor: editor2, renderEditor } = initQueryEditor(
    value(),
    (state2) => {
      value(state2.sliceDoc());
    },
    _("...enter a BQL query. 'help' to list available commands."),
    submit()
  );
  legacy_pre_effect(
    () => (deep_read_state(value()), replaceContents),
    () => {
      if (value() !== editor2.state.sliceDoc()) {
        editor2.dispatch(replaceContents(editor2.state, value()));
      }
    }
  );
  legacy_pre_effect_reset();
  init2();
  var form = root47();
  var div = child(form);
  action(div, ($$node) => renderEditor?.($$node));
  var button = sibling(div, 2);
  var text2 = child(button, true);
  reset(button);
  action(button, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => "Control+Enter");
  reset(form);
  template_effect(($0) => set_text(text2, $0), [() => _("Submit")], derived_safe_equal);
  event("submit", form, (event2) => {
    event2.preventDefault();
    submit()();
  });
  append($$anchor, form);
  pop();
}

// src/reports/query/Query.svelte
var root48 = template(`<!> <!>`, 1);
function Query2($$anchor, $$props) {
  push($$props, false);
  const [$$stores, $$cleanup] = setup_stores();
  const $filter_params = () => store_get(filter_params, "$filter_params", $$stores);
  const $query_shell_history = () => store_get(query_shell_history, "$query_shell_history", $$stores);
  let query_string = mutable_source("");
  let results = mutable_source({});
  const is_open = mutable_source({});
  onMount(() => searchParams.subscribe((s) => {
    const search_query_string = s.get("query_string") ?? "";
    if (search_query_string !== get(query_string)) {
      set(query_string, search_query_string);
      submit();
    }
  }));
  onMount(() => filter_params.subscribe(() => {
    rerun_all_open();
  }));
  function submit() {
    const query2 = get(query_string);
    if (!query2) {
      return;
    }
    if (query2.trim().toUpperCase() === "CLEAR") {
      query_shell_history.clear();
      set(query_string, "");
      router_default.set_search_param("query_string", "");
      return;
    }
    query_shell_history.add(query2);
    router_default.set_search_param("query_string", query2);
    get3("query", { query_string: query2, ...$filter_params() }).then((res2) => ok(res2), (error2) => err2(error2 instanceof Error ? error2.message : "INTERNAL ERROR")).then((res2) => {
      mutate(results, get(results)[query2] = res2);
      mutate(is_open, get(is_open)[query2] = true);
      document.querySelector("article")?.scroll(0, 0);
    }).catch(log_error);
  }
  function rerun_all_open() {
    const to_rerun = [...Object.entries(get(is_open))].filter(([, is_open2]) => is_open2).map(([query2]) => query2);
    set(results, {});
    for (const query2 of to_rerun) {
      get3("query", { query_string: query2, ...$filter_params() }).then((res2) => ok(res2), (error2) => err2(error2 instanceof Error ? error2.message : "INTERNAL ERROR")).then((res2) => {
        mutate(results, get(results)[query2] = res2);
      }).catch(log_error);
    }
  }
  function delete_item(query2) {
    query_shell_history.remove(query2);
    if (get(query_string) === query2) {
      set(query_string, "");
      router_default.set_search_param("query_string", "");
    }
  }
  init2();
  var fragment = root48();
  var node = first_child(fragment);
  QueryEditor(node, {
    submit,
    get value() {
      return get(query_string);
    },
    set value($$value) {
      set(query_string, $$value);
    },
    $$legacy: true
  });
  var node_1 = sibling(node, 2);
  each(node_1, 1, $query_shell_history, (query2) => query2, ($$anchor2, query2) => {
    QueryBox($$anchor2, {
      get query() {
        return get(query2);
      },
      get result() {
        return get(results)[get(query2)];
      },
      onselect: () => {
        set(query_string, get(query2));
        submit();
      },
      ondelete: () => {
        delete_item(get(query2));
      },
      get open() {
        return get(is_open)[get(query2)];
      },
      set open($$value) {
        mutate(is_open, get(is_open)[get(query2)] = $$value);
      },
      $$legacy: true
    });
  });
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/query/index.ts
var query = new DatalessRoute("query", Query2, () => _("Query"));

// src/tree-table/TreeTableNode.svelte
var root_221 = template(` <!>`, 1);
var root_135 = template(`<span><!></span>`);
var root_412 = template(`<span> </span> <!> <br>`, 1);
var root_611 = template(`<ol></ol>`);
var root49 = template(`<li><p><!> <!> <span></span></p> <!></li>`);
function TreeTableNode_1($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $toggled = () => store_get(toggled, "$toggled", $$stores);
  const $operating_currency = () => store_get(operating_currency, "$operating_currency", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const { toggled, not_shown } = getTreeTableContext();
  let account2 = user_derived(() => $$props.node.account), children2 = user_derived(() => $$props.node.children);
  let is_toggled = user_derived(() => $toggled().has(get(account2)));
  let has_balance = user_derived(() => !is_empty($$props.node.balance));
  let show_balance = user_derived(() => !get(is_toggled) && get(has_balance));
  let shown_balance = user_derived(() => get(show_balance) ? $$props.node.balance : $$props.node.balance_children);
  let shown_cost = user_derived(() => get(show_balance) ? $$props.node.cost : $$props.node.cost_children);
  let shown_balance_other = user_derived(() => Object.entries(get(shown_balance)).sort().filter(([c]) => !$operating_currency().includes(c)));
  let dimmed = user_derived(() => !get(is_toggled) && !get(has_balance));
  var li = root49();
  var p = child(li);
  var node_1 = child(p);
  AccountCell(node_1, {
    get node() {
      return $$props.node;
    }
  });
  var node_2 = sibling(node_1, 2);
  each(node_2, 1, $operating_currency, index, ($$anchor2, currency) => {
    var span = root_135();
    const num2 = user_derived(() => get(shown_balance)[get(currency)]);
    const cost_num = user_derived(() => get(shown_cost)?.[get(currency)] ?? 0);
    let classes;
    var node_3 = child(span);
    {
      var consequent_1 = ($$anchor3) => {
        var fragment = root_221();
        var text2 = first_child(fragment);
        var node_4 = sibling(text2);
        {
          var consequent = ($$anchor4) => {
            const diff = user_derived(() => $$props.invert * (get(num2) - get(cost_num)));
            const expression = user_derived(() => $$props.invert * get(cost_num));
            Diff($$anchor4, {
              get diff() {
                return get(diff);
              },
              get num() {
                return get(expression);
              },
              get currency() {
                return get(currency);
              }
            });
          };
          if_block(node_4, ($$render) => {
            if (get(cost_num) && get(num2) - get(cost_num)) $$render(consequent);
          });
        }
        template_effect(($0) => set_text(text2, `${$0 ?? ""} `), [
          () => $ctx().num($$props.invert * get(num2), get(currency))
        ]);
        append($$anchor3, fragment);
      };
      if_block(node_3, ($$render) => {
        if (get(num2)) $$render(consequent_1);
      });
    }
    reset(span);
    template_effect(($0) => classes = set_class(span, 1, "num", null, classes, $0), [() => ({ dimmed: get(dimmed) })]);
    append($$anchor2, span);
  });
  var span_1 = sibling(node_2, 2);
  let classes_1;
  each(span_1, 21, () => get(shown_balance_other), index, ($$anchor2, $$item) => {
    let currency = () => get($$item)[0];
    let num2 = () => get($$item)[1];
    var fragment_2 = root_412();
    const cost_num = user_derived(() => get(shown_cost)?.[currency()] ?? 0);
    var span_2 = first_child(fragment_2);
    var text_1 = child(span_2, true);
    reset(span_2);
    var node_5 = sibling(span_2, 2);
    {
      var consequent_2 = ($$anchor3) => {
        const diff = user_derived(() => $$props.invert * (num2() - get(cost_num)));
        const expression_1 = user_derived(() => $$props.invert * get(cost_num));
        Diff($$anchor3, {
          get diff() {
            return get(diff);
          },
          get num() {
            return get(expression_1);
          },
          get currency() {
            return currency();
          }
        });
      };
      if_block(node_5, ($$render) => {
        if (get(cost_num) && num2() - get(cost_num)) $$render(consequent_2);
      });
    }
    next(2);
    template_effect(
      ($0, $1) => {
        set_attribute(span_2, "title", $0);
        set_text(text_1, $1);
      },
      [
        () => $currency_name()(currency()),
        () => $ctx().amount($$props.invert * num2(), currency())
      ]
    );
    append($$anchor2, fragment_2);
  });
  reset(span_1);
  reset(p);
  var node_6 = sibling(p, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ol = root_611();
      each(ol, 21, () => get(children2).filter((n) => !$not_shown().has(n.account)), (child2) => child2.account, ($$anchor3, child2) => {
        TreeTableNode_1($$anchor3, {
          get node() {
            return get(child2);
          },
          get invert() {
            return $$props.invert;
          }
        });
      });
      reset(ol);
      append($$anchor2, ol);
    };
    if_block(node_6, ($$render) => {
      if (!get(is_toggled) && get(children2).some((n) => !$not_shown().has(n.account))) $$render(consequent_3);
    });
  }
  reset(li);
  template_effect(($0) => classes_1 = set_class(span_1, 1, "num other", null, classes_1, $0), [() => ({ dimmed: get(dimmed) })]);
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/tree-table/TreeTable.svelte
var root_136 = template(`<span class="num"> </span>`);
var root50 = template(`<ol><li class="head"><p><!> <!> <span class="num other"> </span></p></li> <!></ol>`);
function TreeTable($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $collapse_account = () => store_get(collapse_account, "$collapse_account", $$stores);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const $get_not_shown = () => store_get(get_not_shown, "$get_not_shown", $$stores);
  const $operating_currency = () => store_get(operating_currency, "$operating_currency", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $invert_account = () => store_get(invert_account, "$invert_account", $$stores);
  const toggled = writable(get_collapsed($$props.tree, $collapse_account()));
  const not_shown = writable(/* @__PURE__ */ new Set());
  setTreeTableContext({ toggled, not_shown });
  user_effect(() => {
    store_set(not_shown, $get_not_shown()($$props.tree, $$props.end));
  });
  var ol = root50();
  let classes;
  var li = child(ol);
  var p = child(li);
  var node = child(p);
  AccountCellHeader(node, {});
  var node_1 = sibling(node, 2);
  each(node_1, 1, $operating_currency, index, ($$anchor2, currency) => {
    var span = root_136();
    var text2 = child(span, true);
    reset(span);
    template_effect(
      ($0) => {
        set_attribute(span, "title", $0);
        set_text(text2, get(currency));
      },
      [
        () => $currency_name()(get(currency))
      ]
    );
    append($$anchor2, span);
  });
  var span_1 = sibling(node_1, 2);
  var text_1 = child(span_1, true);
  reset(span_1);
  reset(p);
  reset(li);
  var node_2 = sibling(li, 2);
  each(node_2, 17, () => $$props.tree.account === "" ? $$props.tree.children : [$$props.tree], index, ($$anchor2, n) => {
    const expression = user_derived(() => $invert_account()(get(n).account) ? -1 : 1);
    TreeTableNode_1($$anchor2, {
      get node() {
        return get(n);
      },
      get invert() {
        return get(expression);
      }
    });
  });
  reset(ol);
  template_effect(
    ($0, $1) => {
      classes = set_class(ol, 1, "flex-table tree-table-new svelte-12upc2c", null, classes, $0);
      set_text(text_1, $1);
    },
    [
      () => ({ wider: $operating_currency().length > 1 }),
      () => _("Other")
    ]
  );
  append($$anchor, ol);
  pop();
  $$cleanup();
}

// src/reports/tree_reports/BalanceSheet.svelte
var root51 = template(`<!> <div class="row"><div class="column"></div> <div class="column"></div></div>`, 1);
function BalanceSheet($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $chartContext = () => store_get(chartContext, "$chartContext", $$stores);
  let end = user_derived(() => $$props.date_range?.end ?? null);
  let chartData = user_derived(() => parseChartData($$props.charts, $chartContext()).unwrap_or(null));
  var fragment = root51();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      ChartSwitcher($$anchor2, {
        get charts() {
          return get(chartData);
        }
      });
    };
    if_block(node, ($$render) => {
      if (get(chartData)) $$render(consequent);
    });
  }
  var div = sibling(node, 2);
  var div_1 = child(div);
  each(div_1, 21, () => $$props.trees.slice(0, 1), index, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get(tree);
      },
      get end() {
        return get(end);
      }
    });
  });
  reset(div_1);
  var div_2 = sibling(div_1, 2);
  each(div_2, 21, () => $$props.trees.slice(1), index, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get(tree);
      },
      get end() {
        return get(end);
      }
    });
  });
  reset(div_2);
  reset(div);
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/tree_reports/IncomeStatement.svelte
var root52 = template(`<!> <div class="row"><div class="column"></div> <div class="column"></div></div>`, 1);
function IncomeStatement($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $chartContext = () => store_get(chartContext, "$chartContext", $$stores);
  let end = user_derived(() => $$props.date_range?.end ?? null);
  let chartData = user_derived(() => parseChartData($$props.charts, $chartContext()).unwrap_or(null));
  var fragment = root52();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      ChartSwitcher($$anchor2, {
        get charts() {
          return get(chartData);
        }
      });
    };
    if_block(node, ($$render) => {
      if (get(chartData)) $$render(consequent);
    });
  }
  var div = sibling(node, 2);
  var div_1 = child(div);
  each(div_1, 21, () => $$props.trees.slice(0, 2), index, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get(tree);
      },
      get end() {
        return get(end);
      }
    });
  });
  reset(div_1);
  var div_2 = sibling(div_1, 2);
  each(div_2, 21, () => $$props.trees.slice(2), index, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get(tree);
      },
      get end() {
        return get(end);
      }
    });
  });
  reset(div_2);
  reset(div);
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/tree_reports/TrialBalance.svelte
var root53 = template(`<!> <div class="row"></div>`, 1);
function TrialBalance($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $chartContext = () => store_get(chartContext, "$chartContext", $$stores);
  let end = user_derived(() => $$props.date_range?.end ?? null);
  let chartData = user_derived(() => parseChartData($$props.charts, $chartContext()).unwrap_or(null));
  var fragment = root53();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      ChartSwitcher($$anchor2, {
        get charts() {
          return get(chartData);
        }
      });
    };
    if_block(node, ($$render) => {
      if (get(chartData)) $$render(consequent);
    });
  }
  var div = sibling(node, 2);
  each(div, 21, () => $$props.trees, index, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get(tree);
      },
      get end() {
        return get(end);
      }
    });
  });
  reset(div);
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/tree_reports/index.ts
var income_statement = new Route(
  "income_statement",
  IncomeStatement,
  async (url) => get3("income_statement", getURLFilters(url)),
  () => _("Income Statement")
);
var balance_sheet = new Route(
  "balance_sheet",
  BalanceSheet,
  async (url) => get3("balance_sheet", getURLFilters(url)),
  () => _("Balance Sheet")
);
var trial_balance = new Route(
  "trial_balance",
  TrialBalance,
  async (url) => get3("trial_balance", getURLFilters(url)),
  () => _("Trial Balance")
);

// src/reports/routes.ts
var frontend_routes = [
  account_report,
  balance_sheet,
  commodities2,
  documents,
  editor,
  errors2,
  events,
  holdings,
  import_report,
  income_statement,
  options3,
  query,
  trial_balance
];

// src/stores/editor.ts
var reloadAfterSavingEntrySlice = localStorageSyncedStore(
  "reload-after-saving-entry-slice",
  boolean,
  () => true
);
var addEntryContinue = localStorageSyncedStore(
  "add-entry-continue",
  boolean,
  () => false
);

// src/modals/AddEntry.svelte
var on_click11 = (__1, entry, Cls) => {
  set(entry, Cls().empty(get(entry).date));
};
var root_223 = template(`<button type="button"> </button> `, 1);
var root_137 = template(`<form><h3> <!></h3> <!> <div class="flex-row"><span class="spacer"></span> <label class="svelte-1c9vhis"><input type="checkbox"> <span class="svelte-1c9vhis"> </span></label> <button type="submit"> </button></div></form>`);
function AddEntry($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $addEntryContinue = () => store_get(addEntryContinue, "$addEntryContinue", $$stores);
  const $urlHash = () => store_get(urlHash, "$urlHash", $$stores);
  const entryTypes = [
    [Transaction, _("Transaction")],
    [Balance, _("Balance")],
    [Note, _("Note")]
  ];
  let entry = state(Transaction.empty(todayAsString()));
  async function submit(event2) {
    event2.preventDefault();
    await saveEntries([get(entry)]);
    const added_entry_date = get(entry).date;
    set(entry, get(entry).constructor.empty(added_entry_date));
    if (!$addEntryContinue()) {
      closeOverlay();
    }
  }
  let shown = user_derived(() => $urlHash() === "add-transaction");
  ModalBase($$anchor, {
    get shown() {
      return get(shown);
    },
    focus: ".payee input",
    children: ($$anchor2, $$slotProps) => {
      var form = root_137();
      var h3 = child(form);
      var text2 = child(h3);
      var node = sibling(text2);
      each(node, 17, () => entryTypes, index, ($$anchor3, $$item) => {
        let Cls = () => get($$item)[0];
        let displayName = () => get($$item)[1];
        var fragment_1 = root_223();
        var button = first_child(fragment_1);
        button.__click = [on_click11, entry, Cls];
        let classes;
        var text_1 = child(button, true);
        reset(button);
        var text_2 = sibling(button);
        text_2.nodeValue = "  ";
        template_effect(
          ($0) => {
            classes = set_class(button, 1, "", null, classes, $0);
            set_text(text_1, displayName());
          },
          [
            () => ({
              muted: !(get(entry) instanceof Cls())
            })
          ]
        );
        append($$anchor3, fragment_1);
      });
      reset(h3);
      var node_1 = sibling(h3, 2);
      Entry(node_1, {
        get entry() {
          return get(entry);
        },
        set entry($$value) {
          set(entry, $$value);
        }
      });
      var div = sibling(node_1, 2);
      var label = sibling(child(div), 2);
      var input = child(label);
      remove_input_defaults(input);
      var span = sibling(input, 2);
      var text_3 = child(span, true);
      reset(span);
      reset(label);
      var button_1 = sibling(label, 2);
      var text_4 = child(button_1, true);
      reset(button_1);
      reset(div);
      reset(form);
      template_effect(
        ($0, $1, $2) => {
          set_text(text2, `${$0 ?? ""} `);
          set_text(text_3, $1);
          set_text(text_4, $2);
        },
        [
          () => _("Add"),
          () => _("continue"),
          () => _("Save")
        ]
      );
      event("submit", form, submit);
      bind_checked(input, $addEntryContinue, ($$value) => store_set(addEntryContinue, $$value));
      append($$anchor2, form);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/editor/DeleteButton.svelte
var root54 = template(`<button type="button" class="muted"> </button>`);
function DeleteButton($$anchor, $$props) {
  push($$props, true);
  let buttonContent = user_derived(() => $$props.deleting ? _("Deleting...") : _("Delete"));
  var button = root54();
  button.__click = function(...$$args) {
    $$props.onDelete?.apply(this, $$args);
  };
  var text2 = child(button, true);
  reset(button);
  template_effect(
    ($0) => {
      set_attribute(button, "title", $0);
      set_text(text2, get(buttonContent));
    },
    [() => _("Delete")]
  );
  append($$anchor, button);
  pop();
}
delegate(["click"]);

// src/editor/SliceEditor.svelte
var root55 = template(`<form><div class="editor svelte-qiyosp"></div> <div class="flex-row"><span class="spacer"></span> <label class="svelte-qiyosp"><input type="checkbox"> <span class="svelte-qiyosp"> </span></label> <!> <!></div></form>`);
function SliceEditor($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $reloadAfterSavingEntrySlice = () => store_get(reloadAfterSavingEntrySlice, "$reloadAfterSavingEntrySlice", $$stores);
  let entry_hash = prop($$props, "entry_hash", 15), sha256sum = prop($$props, "sha256sum", 15);
  let currentSlice = state(proxy2($$props.slice));
  let changed = user_derived(() => get(currentSlice) !== $$props.slice);
  let saving = state(false);
  let deleting = state(false);
  async function save(event2) {
    event2?.preventDefault();
    set(saving, true);
    try {
      sha256sum(await put("source_slice", {
        entry_hash: entry_hash(),
        source: get(currentSlice),
        sha256sum: sha256sum()
      }));
      if ($reloadAfterSavingEntrySlice()) {
        router_default.reload();
      }
      closeOverlay();
    } catch (error2) {
      notify_err(error2, (err3) => `Saving failed: ${err3.message}`);
    } finally {
      set(saving, false);
    }
  }
  async function deleteSlice() {
    set(deleting, true);
    try {
      await doDelete("source_slice", {
        entry_hash: entry_hash(),
        sha256sum: sha256sum()
      });
      entry_hash("");
      if ($reloadAfterSavingEntrySlice()) {
        router_default.reload();
      }
      closeOverlay();
    } catch (error2) {
      notify_err(error2, (err3) => `Deleting failed: ${err3.message}`);
    } finally {
      set(deleting, false);
    }
  }
  const { renderEditor } = initBeancountEditor(
    $$props.slice,
    (state2) => {
      set(currentSlice, state2.sliceDoc(), true);
    },
    [
      {
        key: "Control-s",
        mac: "Meta-s",
        run: () => {
          save().catch(() => {
          });
          return true;
        }
      }
    ],
    $$props.beancount_language_support
  );
  var form = root55();
  var div = child(form);
  action(div, ($$node) => renderEditor?.($$node));
  var div_1 = sibling(div, 2);
  var label = sibling(child(div_1), 2);
  var input = child(label);
  remove_input_defaults(input);
  var span = sibling(input, 2);
  var text2 = child(span, true);
  reset(span);
  reset(label);
  var node = sibling(label, 2);
  DeleteButton(node, {
    get deleting() {
      return get(deleting);
    },
    onDelete: deleteSlice
  });
  var node_1 = sibling(node, 2);
  SaveButton(node_1, {
    get changed() {
      return get(changed);
    },
    get saving() {
      return get(saving);
    }
  });
  reset(div_1);
  reset(form);
  template_effect(($0) => set_text(text2, $0), [() => _("reload")]);
  event("submit", form, save);
  bind_checked(input, $reloadAfterSavingEntrySlice, ($$value) => store_set(reloadAfterSavingEntrySlice, $$value));
  append($$anchor, form);
  pop();
  $$cleanup();
}

// src/modals/EntryContext.svelte
var root_312 = template(` <br>`, 1);
var root_224 = template(`<tr><td><a> </a></td><td></td></tr>`);
var root_511 = template(` <br>`, 1);
var root_413 = template(`<tr><td><a> </a></td><td></td></tr>`);
var root_138 = template(`<details><summary><span> </span></summary> <div><table><thead><tr><th colspan="2"> </th></tr></thead><tbody></tbody></table> <table><thead><tr><th colspan="2"> </th></tr></thead><tbody></tbody></table></div></details>`);
var root56 = template(`<p> <code><a> </a></code></p> <!>`, 1);
function EntryContext($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlForSource = () => store_get(urlForSource, "$urlForSource", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  var fragment = root56();
  var p = first_child(fragment);
  var text2 = child(p);
  var code = sibling(text2);
  var a = child(code);
  var text_1 = child(a);
  reset(a);
  reset(code);
  reset(p);
  var node = sibling(p, 2);
  {
    var consequent = ($$anchor2) => {
      var details = root_138();
      var summary = child(details);
      var span = child(summary);
      var text_2 = child(span, true);
      reset(span);
      reset(summary);
      var div = sibling(summary, 2);
      var table = child(div);
      var thead = child(table);
      var tr = child(thead);
      var th = child(tr);
      var text_3 = child(th, true);
      reset(th);
      reset(tr);
      reset(thead);
      var tbody = sibling(thead);
      each(tbody, 21, () => Object.entries($$props.balances_before), index, ($$anchor3, $$item) => {
        let account2 = () => get($$item)[0];
        let inventory2 = () => get($$item)[1];
        var tr_1 = root_224();
        var td = child(tr_1);
        var a_1 = child(td);
        var text_4 = child(a_1, true);
        reset(a_1);
        reset(td);
        var td_1 = sibling(td);
        each(td_1, 21, inventory2, index, ($$anchor4, amount) => {
          next();
          var fragment_1 = root_312();
          var text_5 = first_child(fragment_1);
          next();
          template_effect(() => set_text(text_5, `${get(amount) ?? ""} `));
          append($$anchor4, fragment_1);
        });
        reset(td_1);
        reset(tr_1);
        template_effect(
          ($0) => {
            set_attribute(a_1, "href", $0);
            set_text(text_4, account2());
          },
          [() => $urlForAccount()(account2())]
        );
        append($$anchor3, tr_1);
      });
      reset(tbody);
      reset(table);
      var table_1 = sibling(table, 2);
      var thead_1 = child(table_1);
      var tr_2 = child(thead_1);
      var th_1 = child(tr_2);
      var text_6 = child(th_1, true);
      reset(th_1);
      reset(tr_2);
      reset(thead_1);
      var tbody_1 = sibling(thead_1);
      each(tbody_1, 21, () => Object.entries($$props.balances_after), index, ($$anchor3, $$item) => {
        let account2 = () => get($$item)[0];
        let inventory2 = () => get($$item)[1];
        var tr_3 = root_413();
        var td_2 = child(tr_3);
        var a_2 = child(td_2);
        var text_7 = child(a_2, true);
        reset(a_2);
        reset(td_2);
        var td_3 = sibling(td_2);
        each(td_3, 21, inventory2, index, ($$anchor4, amount) => {
          next();
          var fragment_2 = root_511();
          var text_8 = first_child(fragment_2);
          next();
          template_effect(() => set_text(text_8, `${get(amount) ?? ""} `));
          append($$anchor4, fragment_2);
        });
        reset(td_3);
        reset(tr_3);
        template_effect(
          ($0) => {
            set_attribute(a_2, "href", $0);
            set_text(text_7, account2());
          },
          [() => $urlForAccount()(account2())]
        );
        append($$anchor3, tr_3);
      });
      reset(tbody_1);
      reset(table_1);
      reset(div);
      reset(details);
      template_effect(
        ($0, $1, $2) => {
          set_text(text_2, $0);
          set_text(text_3, $1);
          set_text(text_6, $2);
        },
        [
          () => _("Context"),
          () => _("Balances before entry"),
          () => _("Balances after entry")
        ]
      );
      append($$anchor2, details);
    };
    if_block(node, ($$render) => {
      if ($$props.balances_before && $$props.balances_after) $$render(consequent);
    });
  }
  template_effect(
    ($0, $1) => {
      set_text(text2, `${$0 ?? ""}: `);
      set_attribute(a, "href", $1);
      set_text(text_1, `${$$props.entry.meta.filename ?? ""}:${$$props.entry.meta.lineno ?? ""}`);
    },
    [
      () => _("Location"),
      () => $urlForSource()($$props.entry.meta.filename, $$props.entry.meta.lineno)
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/modals/Context.svelte
var root_313 = template(`<!> <!>`, 1);
var root_139 = template(`<div class="content"><!></div>`);
function Context($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlHash = () => store_get(urlHash, "$urlHash", $$stores);
  let shown = user_derived(() => $urlHash().startsWith("context"));
  let entry_hash = user_derived(() => get(shown) ? $urlHash().slice(8) : "");
  let content2 = user_derived(() => get(shown) ? get3("context", { entry_hash: get(entry_hash) }) : null);
  ModalBase($$anchor, {
    get shown() {
      return get(shown);
    },
    children: ($$anchor2, $$slotProps) => {
      var div = root_139();
      var node = child(div);
      await_block(
        node,
        () => get(content2),
        ($$anchor3) => {
          var text_2 = text("Loading entry context...");
          append($$anchor3, text_2);
        },
        ($$anchor3, response) => {
          var fragment_1 = comment();
          var node_1 = first_child(fragment_1);
          {
            var consequent = ($$anchor4) => {
              var fragment_2 = root_313();
              var node_2 = first_child(fragment_2);
              EntryContext(node_2, {
                get entry() {
                  return get(response).entry;
                },
                get balances_before() {
                  return get(response).balances_before;
                },
                get balances_after() {
                  return get(response).balances_after;
                }
              });
              var node_3 = sibling(node_2, 2);
              await_block(
                node_3,
                getBeancountLanguageSupport,
                null,
                ($$anchor5, beancount_language_support) => {
                  SliceEditor($$anchor5, {
                    get entry_hash() {
                      return get(entry_hash);
                    },
                    get slice() {
                      return get(response).slice;
                    },
                    get sha256sum() {
                      return get(response).sha256sum;
                    },
                    get beancount_language_support() {
                      return get(beancount_language_support);
                    }
                  });
                },
                ($$anchor5) => {
                  var text2 = text("Loading tree-sitter language failed...");
                  append($$anchor5, text2);
                }
              );
              append($$anchor4, fragment_2);
            };
            if_block(node_1, ($$render) => {
              if (get(response)) $$render(consequent);
            });
          }
          append($$anchor3, fragment_1);
        },
        ($$anchor3) => {
          var text_1 = text("Loading entry context failed...");
          append($$anchor3, text_1);
        }
      );
      reset(div);
      append($$anchor2, div);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}

// src/document-upload.ts
function dragover(event2, closestTarget) {
  if (!(event2 instanceof DragEvent)) {
    return;
  }
  const types2 = event2.dataTransfer?.types ?? [];
  if (types2.includes("Files") || types2.includes("text/uri-list")) {
    closestTarget.classList.add("dragover");
    event2.preventDefault();
  }
}
delegate2(document, "dragenter", ".droptarget", dragover);
delegate2(document, "dragover", ".droptarget", dragover);
function dragleave(event2, closestTarget) {
  if (!(event2 instanceof DragEvent)) {
    return;
  }
  closestTarget.classList.remove("dragover");
  event2.preventDefault();
}
delegate2(document, "dragleave", ".droptarget", dragleave);
var account = writable("");
var hash2 = writable("");
var files = writable([]);
function drop(event2, target) {
  if (!(event2 instanceof DragEvent)) {
    return;
  }
  target.classList.remove("dragover");
  event2.preventDefault();
  event2.stopPropagation();
  if (!event2.dataTransfer) {
    return;
  }
  const targetAccount = target.getAttribute("data-account-name");
  const targetEntry = target.getAttribute("data-entry");
  if (event2.dataTransfer.types.includes("Files")) {
    const date4 = target.getAttribute("data-entry-date") ?? todayAsString();
    const uploadedFiles = [];
    for (const dataTransferFile of event2.dataTransfer.files) {
      let { name: name3 } = dataTransferFile;
      if (!/^\d{4}-\d{2}-\d{2}/.test(name3)) {
        name3 = `${date4} ${name3}`;
      }
      uploadedFiles.push({ dataTransferFile, name: name3 });
    }
    account.set(targetAccount ?? "");
    hash2.set(targetEntry ?? "");
    files.set(uploadedFiles);
  } else if (event2.dataTransfer.types.includes("text/uri-list")) {
    const url = event2.dataTransfer.getData("URL");
    let filename = new URL(url).searchParams.get("filename");
    if (filename != null && targetEntry != null) {
      if (targetAccount != null && documentHasAccount(filename, targetAccount)) {
        filename = basename(filename);
      }
      put("attach_document", { filename, entry_hash: targetEntry }).then(
        notify,
        (error2) => {
          notify_err(
            error2,
            (e) => `Adding document metadata failed: ${e.message}`
          );
        }
      );
    }
  }
}
delegate2(document, "drop", ".droptarget", drop);

// src/modals/DocumentUpload.svelte
var root_225 = template(`<div class="fieldset svelte-v4rmq1"><input class="file svelte-v4rmq1"></div>`);
var root_314 = template(`<option> </option>`);
var root_140 = template(`<form><h3> </h3> <!> <div class="fieldset svelte-v4rmq1"><label><span> </span> <select></select></label></div> <div class="fieldset account svelte-v4rmq1"><label><span> </span> <!></label></div> <button type="submit"> </button></form>`);
function DocumentUpload($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $files = () => store_get(files, "$files", $$stores);
  const $options = () => store_get(options, "$options", $$stores);
  const $account = () => store_get(account, "$account", $$stores);
  const $hash = () => store_get(hash2, "$hash", $$stores);
  let shown = user_derived(() => !!$files().length);
  let documents2 = user_derived(() => $options().documents);
  let documents_folder = state("");
  function closeHandler() {
    store_set(files, []);
    store_set(account, "");
    store_set(hash2, "");
  }
  async function submit(event2) {
    event2.preventDefault();
    await Promise.all($files().map(async ({ dataTransferFile, name: name3 }) => {
      const formData = new FormData();
      formData.append("account", $account());
      formData.append("hash", $hash());
      formData.append("folder", get(documents_folder));
      formData.append("file", dataTransferFile, name3);
      return put("add_document", formData).then(notify, (error2) => {
        notify_err(error2, (err3) => `Upload error: ${err3.message}`);
      });
    }));
    closeHandler();
    router_default.reload();
  }
  ModalBase($$anchor, {
    get shown() {
      return get(shown);
    },
    closeHandler,
    children: ($$anchor2, $$slotProps) => {
      var form = root_140();
      var h3 = child(form);
      var text2 = child(h3);
      reset(h3);
      var node = sibling(h3, 2);
      each(node, 1, $files, index, ($$anchor3, file, $$index) => {
        var div = root_225();
        var input = child(div);
        remove_input_defaults(input);
        reset(div);
        bind_value(input, () => get(file).name, ($$value) => (get(file).name = $$value, invalidate_store($$stores, "$files")));
        append($$anchor3, div);
      });
      var div_1 = sibling(node, 2);
      var label = child(div_1);
      var span = child(label);
      var text_1 = child(span);
      reset(span);
      var select = sibling(span, 2);
      each(select, 21, () => get(documents2), index, ($$anchor3, folder) => {
        var option = root_314();
        var option_value = {};
        var text_2 = child(option, true);
        reset(option);
        template_effect(() => {
          if (option_value !== (option_value = get(folder))) {
            option.value = null == (option.__value = get(folder)) ? "" : get(folder);
          }
          set_text(text_2, get(folder));
        });
        append($$anchor3, option);
      });
      reset(select);
      reset(label);
      reset(div_1);
      var div_2 = sibling(div_1, 2);
      var label_1 = child(div_2);
      var span_1 = child(label_1);
      var text_3 = child(span_1);
      reset(span_1);
      var node_1 = sibling(span_1, 2);
      AccountInput(node_1, {
        get value() {
          mark_store_binding();
          return $account();
        },
        set value($$value) {
          store_set(account, $$value);
        }
      });
      reset(label_1);
      reset(div_2);
      var button = sibling(div_2, 2);
      var text_4 = child(button, true);
      reset(button);
      reset(form);
      template_effect(
        ($0, $1, $2, $3) => {
          set_text(text2, `${$0 ?? ""}:`);
          set_text(text_1, `${$1 ?? ""}:`);
          set_text(text_3, `${$2 ?? ""}:`);
          set_text(text_4, $3);
        },
        [
          () => _("Upload file(s)"),
          () => _("Documents folder"),
          () => _("Account"),
          () => _("Upload")
        ]
      );
      event("submit", form, submit);
      bind_select_value(select, () => get(documents_folder), ($$value) => set(documents_folder, $$value));
      append($$anchor2, form);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}

// src/modals/Export.svelte
var root_226 = template(`<div><h3> </h3> <a data-remote=""> </a></div>`);
function Export($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlHash = () => store_get(urlHash, "$urlHash", $$stores);
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  let shown = user_derived(() => $urlHash() === "export");
  ModalBase($$anchor, {
    get shown() {
      return get(shown);
    },
    children: ($$anchor2, $$slotProps) => {
      var fragment_1 = comment();
      var node = first_child(fragment_1);
      {
        var consequent = ($$anchor3) => {
          var div = root_226();
          var h3 = child(div);
          var text2 = child(h3);
          reset(h3);
          var a = sibling(h3, 2);
          var text_1 = child(a, true);
          reset(a);
          reset(div);
          template_effect(
            ($0, $1, $2) => {
              set_text(text2, `${$0 ?? ""}:`);
              set_attribute(a, "href", $1);
              set_text(text_1, $2);
            },
            [
              () => _("Export"),
              () => $urlFor()("download-journal"),
              () => _("Download currently filtered entries as a Beancount file")
            ]
          );
          append($$anchor3, div);
        };
        if_block(node, ($$render) => {
          if (get(shown)) $$render(consequent);
        });
      }
      append($$anchor2, fragment_1);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}

// src/modals/Modals.svelte
var root57 = template(`<!> <!> <!> <!>`, 1);
function Modals($$anchor) {
  var fragment = root57();
  var node = first_child(fragment);
  AddEntry(node, {});
  var node_1 = sibling(node, 2);
  Context(node_1, {});
  var node_2 = sibling(node_1, 2);
  DocumentUpload(node_2, {});
  var node_3 = sibling(node_2, 2);
  Export(node_3, {});
  append($$anchor, fragment);
}

// src/sidebar/AccountSelector.svelte
var root58 = template(`<li><!></li>`);
function AccountSelector($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  let value = state("");
  function select(el) {
    if (get(value)) {
      router_default.navigate($urlForAccount()(get(value)));
      el.blur();
      set(value, "");
    }
  }
  var li = root58();
  var node = child(li);
  const expression = user_derived(() => _("Go to account"));
  AutocompleteInput(node, {
    get placeholder() {
      return get(expression);
    },
    get suggestions() {
      return $accounts();
    },
    className: "account-selector",
    key: "g a",
    onSelect: select,
    onEnter: select,
    get value() {
      return get(value);
    },
    set value($$value) {
      set(value, $$value, true);
    }
  });
  reset(li);
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/sidebar/SidebarLink.svelte
var root_141 = template(`<span> </span>`);
var root59 = template(`<li class="svelte-unghjo"><a> <!></a> <!></li>`);
function SidebarLink($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  const $pathname = () => store_get(pathname, "$pathname", $$stores);
  let href = user_derived(() => $$props.remote ? $$props.report : $urlFor()(`${$$props.report}/`));
  let selected = user_derived(() => $$props.remote ? false : get(href).includes($pathname()));
  var li = root59();
  var a = child(li);
  let classes;
  var text2 = child(a);
  var node = sibling(text2);
  {
    var consequent = ($$anchor2) => {
      var span = root_141();
      let classes_1;
      var text_1 = child(span, true);
      reset(span);
      template_effect(
        ($0) => {
          classes_1 = set_class(span, 1, "bubble svelte-unghjo", null, classes_1, $0);
          set_text(text_1, $$props.bubble[0]);
        },
        [
          () => ({ error: $$props.bubble[1] === "error" })
        ]
      );
      append($$anchor2, span);
    };
    if_block(node, ($$render) => {
      if ($$props.bubble && $$props.bubble[0] > 0) $$render(consequent);
    });
  }
  reset(a);
  action(a, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => $$props.key);
  var node_1 = sibling(a, 2);
  snippet(node_1, () => $$props.children ?? noop);
  reset(li);
  template_effect(
    ($0) => {
      set_attribute(a, "href", get(href));
      set_attribute(a, "data-remote", $$props.remote);
      classes = set_class(a, 1, "svelte-unghjo", null, classes, $0);
      set_text(text2, `${$$props.name ?? ""} `);
    },
    [() => ({ selected: get(selected) })]
  );
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/sidebar/AsideContents.svelte
var root_142 = template(`<ul class="navigation svelte-mmgz8u"></ul>`);
var root_512 = template(`<li class="svelte-mmgz8u"><a class="svelte-mmgz8u"> </a></li>`);
var root_414 = template(`<ul class="submenu svelte-mmgz8u"></ul>`);
var root_612 = template(`<a href="#add-transaction" class="secondary add-transaction svelte-mmgz8u">+</a>`);
var root_84 = template(`<a href="#export" class="secondary svelte-mmgz8u">\u2B07</a>`);
var root_92 = template(`<ul class="navigation svelte-mmgz8u"></ul>`);
var root60 = template(`<!> <ul class="navigation svelte-mmgz8u"><!> <!> <!> <!> <!> <!></ul> <ul class="navigation svelte-mmgz8u"><!> <!> <!> <!> <!></ul> <ul class="navigation svelte-mmgz8u"><!> <!> <!> <!> <!></ul> <!>`, 1);
function AsideContents($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $ledgerData = () => store_get(ledgerData, "$ledgerData", $$stores);
  const $extensions = () => store_get(extensions, "$extensions", $$stores);
  const $urlFor = () => store_get(urlFor, "$urlFor", $$stores);
  const $errors = () => store_get(errors, "$errors", $$stores);
  const truncate = (s) => s.length < 25 ? s : `${s.slice(25)}\u2026`;
  let user_queries = user_derived(() => $ledgerData().user_queries);
  let upcoming_events_count = user_derived(() => $ledgerData().upcoming_events_count);
  let sidebar_links = user_derived(() => $ledgerData().sidebar_links);
  let extension_reports = user_derived(() => $extensions().filter((e) => e.report_title != null));
  var fragment = root60();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var ul = root_142();
      each(ul, 21, () => get(sidebar_links), index, ($$anchor3, $$item) => {
        let label = () => get($$item)[0];
        let link2 = () => get($$item)[1];
        SidebarLink($$anchor3, {
          get report() {
            return link2();
          },
          get name() {
            return label();
          },
          remote: true
        });
      });
      reset(ul);
      append($$anchor2, ul);
    };
    if_block(node, ($$render) => {
      if (get(sidebar_links).length) $$render(consequent);
    });
  }
  var ul_1 = sibling(node, 2);
  var node_1 = child(ul_1);
  const expression = user_derived(() => _("Income Statement"));
  SidebarLink(node_1, {
    report: "income_statement",
    get name() {
      return get(expression);
    },
    key: "g i"
  });
  var node_2 = sibling(node_1, 2);
  const expression_1 = user_derived(() => _("Balance Sheet"));
  SidebarLink(node_2, {
    report: "balance_sheet",
    get name() {
      return get(expression_1);
    },
    key: "g b"
  });
  var node_3 = sibling(node_2, 2);
  const expression_2 = user_derived(() => _("Trial Balance"));
  SidebarLink(node_3, {
    report: "trial_balance",
    get name() {
      return get(expression_2);
    },
    key: "g t"
  });
  var node_4 = sibling(node_3, 2);
  const expression_3 = user_derived(() => _("Journal"));
  SidebarLink(node_4, {
    report: "journal",
    get name() {
      return get(expression_3);
    },
    key: "g j"
  });
  var node_5 = sibling(node_4, 2);
  const expression_4 = user_derived(() => _("Query"));
  SidebarLink(node_5, {
    report: "query",
    get name() {
      return get(expression_4);
    },
    key: "g q",
    children: ($$anchor2, $$slotProps) => {
      var fragment_2 = comment();
      var node_6 = first_child(fragment_2);
      {
        var consequent_1 = ($$anchor3) => {
          var ul_2 = root_414();
          each(ul_2, 21, () => get(user_queries), index, ($$anchor4, $$item) => {
            let query_string = () => get($$item).query_string;
            let name3 = () => get($$item).name;
            var li = root_512();
            var a = child(li);
            var text2 = child(a, true);
            reset(a);
            reset(li);
            template_effect(
              ($0, $1) => {
                set_attribute(a, "href", $0);
                set_text(text2, $1);
              },
              [
                () => $urlFor()("query/", { query_string: query_string() }),
                () => truncate(name3())
              ]
            );
            append($$anchor4, li);
          });
          reset(ul_2);
          append($$anchor3, ul_2);
        };
        if_block(node_6, ($$render) => {
          if (get(user_queries).length) $$render(consequent_1);
        });
      }
      append($$anchor2, fragment_2);
    },
    $$slots: { default: true }
  });
  var node_7 = sibling(node_5, 2);
  AccountSelector(node_7, {});
  reset(ul_1);
  var ul_3 = sibling(ul_1, 2);
  var node_8 = child(ul_3);
  const expression_5 = user_derived(() => _("Holdings"));
  SidebarLink(node_8, {
    report: "holdings",
    get name() {
      return get(expression_5);
    },
    key: "g h"
  });
  var node_9 = sibling(node_8, 2);
  const expression_6 = user_derived(() => _("Commodities"));
  SidebarLink(node_9, {
    report: "commodities",
    get name() {
      return get(expression_6);
    },
    key: "g c"
  });
  var node_10 = sibling(node_9, 2);
  const expression_7 = user_derived(() => _("Documents"));
  SidebarLink(node_10, {
    report: "documents",
    get name() {
      return get(expression_7);
    },
    key: "g d"
  });
  var node_11 = sibling(node_10, 2);
  const expression_8 = user_derived(() => _("Events"));
  const expression_9 = user_derived(() => [get(upcoming_events_count), "info"]);
  SidebarLink(node_11, {
    report: "events",
    get name() {
      return get(expression_8);
    },
    key: "g E",
    get bubble() {
      return get(expression_9);
    }
  });
  var node_12 = sibling(node_11, 2);
  const expression_10 = user_derived(() => _("Statistics"));
  SidebarLink(node_12, {
    report: "statistics",
    get name() {
      return get(expression_10);
    },
    key: "g s"
  });
  reset(ul_3);
  var ul_4 = sibling(ul_3, 2);
  var node_13 = child(ul_4);
  const expression_11 = user_derived(() => _("Editor"));
  SidebarLink(node_13, {
    report: "editor",
    get name() {
      return get(expression_11);
    },
    key: "g e",
    children: ($$anchor2, $$slotProps) => {
      var a_1 = root_612();
      action(a_1, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => "n");
      template_effect(($0) => set_attribute(a_1, "title", $0), [() => _("Add Journal Entry")]);
      append($$anchor2, a_1);
    },
    $$slots: { default: true }
  });
  var node_14 = sibling(node_13, 2);
  {
    var consequent_2 = ($$anchor2) => {
      const expression_12 = user_derived(() => _("Errors"));
      const expression_13 = user_derived(() => [$errors().length, "error"]);
      SidebarLink($$anchor2, {
        report: "errors",
        get name() {
          return get(expression_12);
        },
        get bubble() {
          return get(expression_13);
        }
      });
    };
    if_block(node_14, ($$render) => {
      if ($errors().length > 0) $$render(consequent_2);
    });
  }
  var node_15 = sibling(node_14, 2);
  const expression_14 = user_derived(() => _("Import"));
  SidebarLink(node_15, {
    report: "import",
    get name() {
      return get(expression_14);
    },
    key: "g n",
    children: ($$anchor2, $$slotProps) => {
      var a_2 = root_84();
      template_effect(($0) => set_attribute(a_2, "title", $0), [() => _("Export")]);
      append($$anchor2, a_2);
    },
    $$slots: { default: true }
  });
  var node_16 = sibling(node_15, 2);
  const expression_15 = user_derived(() => _("Options"));
  SidebarLink(node_16, {
    report: "options",
    get name() {
      return get(expression_15);
    },
    key: "g o"
  });
  var node_17 = sibling(node_16, 2);
  const expression_16 = user_derived(() => _("Help"));
  SidebarLink(node_17, {
    report: "help",
    get name() {
      return get(expression_16);
    },
    key: "g H"
  });
  reset(ul_4);
  var node_18 = sibling(ul_4, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ul_5 = root_92();
      each(ul_5, 21, () => get(extension_reports), index, ($$anchor3, ext2) => {
        const expression_17 = user_derived(() => `extension/${get(ext2).name}`);
        const expression_18 = user_derived(() => get(ext2).report_title ?? "");
        SidebarLink($$anchor3, {
          get report() {
            return get(expression_17);
          },
          get name() {
            return get(expression_18);
          }
        });
      });
      reset(ul_5);
      append($$anchor2, ul_5);
    };
    if_block(node_18, ($$render) => {
      if (get(extension_reports).length) $$render(consequent_3);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/sidebar/AsideWithButton.svelte
var toggle = (_2, active) => {
  set(active, !get(active));
};
var root_143 = template(`<div class="overlay svelte-18c6e75" aria-hidden="true"></div>`);
var root61 = template(`<!> <div><button type="button" class="svelte-18c6e75">\u2630</button> <a class="button svelte-18c6e75" href="#add-transaction">+</a></div> <aside><!></aside>`, 1);
function AsideWithButton($$anchor) {
  let active = state(false);
  var fragment = root61();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_143();
      div.__click = [toggle, active];
      append($$anchor2, div);
    };
    if_block(node, ($$render) => {
      if (get(active)) $$render(consequent);
    });
  }
  var div_1 = sibling(node, 2);
  let classes;
  var button = child(div_1);
  button.__click = [toggle, active];
  next(2);
  reset(div_1);
  var aside = sibling(div_1, 2);
  let classes_1;
  var node_1 = child(aside);
  AsideContents(node_1, {});
  reset(aside);
  template_effect(
    ($0, $1) => {
      classes = set_class(div_1, 1, "aside-buttons svelte-18c6e75", null, classes, $0);
      classes_1 = set_class(aside, 1, "svelte-18c6e75", null, classes_1, $1);
    },
    [
      () => ({ active: get(active) }),
      () => ({ active: get(active) })
    ]
  );
  append($$anchor, fragment);
}
delegate(["click"]);

// src/sidebar/FilterForm.svelte
var root62 = template(`<form class="svelte-1f6zj2z"><!> <!> <!> <button type="submit" class="svelte-1f6zj2z"></button></form>`);
function FilterForm($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $tags = () => store_get(tags, "$tags", $$stores);
  const $links = () => store_get(links, "$links", $$stores);
  const $payees = () => store_get(payees, "$payees", $$stores);
  const $years = () => store_get(years, "$years", $$stores);
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  let fql_filter_suggestions = user_derived(() => [
    ...$tags().map((tag) => `#${tag}`),
    ...$links().map((link2) => `^${link2}`),
    ...$payees().map((payee) => `payee:"${escape(payee)}"`),
    ...$payees().map((payee) => `payee:"${escape(payee)}"`)
  ]);
  function valueExtractor(value, input) {
    const match = /\S*$/.exec(value.slice(0, input.selectionStart ?? void 0));
    return match?.[0] ?? value;
  }
  function valueSelector(value, input) {
    const selectionStart = input.selectionStart ?? 0;
    const match = /\S*$/.exec(input.value.slice(0, selectionStart));
    const matchLength = match?.[0]?.length;
    return matchLength !== void 0 ? `${input.value.slice(0, selectionStart - matchLength)}${value}${input.value.slice(selectionStart)}` : value;
  }
  let account_filter_value = state("");
  let fql_filter_value = state("");
  let time_filter_value = state("");
  account_filter.subscribe((v) => {
    set(account_filter_value, v, true);
  });
  fql_filter.subscribe((v) => {
    set(fql_filter_value, v, true);
  });
  time_filter.subscribe((v) => {
    set(time_filter_value, v, true);
  });
  function submit() {
    account_filter.set(get(account_filter_value));
    fql_filter.set(get(fql_filter_value));
    time_filter.set(get(time_filter_value));
  }
  var form = root62();
  var node = child(form);
  const expression = user_derived(() => _("Time"));
  AutocompleteInput(node, {
    get placeholder() {
      return get(expression);
    },
    get suggestions() {
      return $years();
    },
    key: "f t",
    clearButton: true,
    setSize: true,
    onBlur: submit,
    onSelect: submit,
    onEnter: submit,
    get value() {
      return get(time_filter_value);
    },
    set value($$value) {
      set(time_filter_value, $$value, true);
    }
  });
  var node_1 = sibling(node, 2);
  const expression_1 = user_derived(() => _("Account"));
  AutocompleteInput(node_1, {
    get placeholder() {
      return get(expression_1);
    },
    get suggestions() {
      return $accounts();
    },
    key: "f a",
    clearButton: true,
    setSize: true,
    onBlur: submit,
    onSelect: submit,
    onEnter: submit,
    get value() {
      return get(account_filter_value);
    },
    set value($$value) {
      set(account_filter_value, $$value, true);
    }
  });
  var node_2 = sibling(node_1, 2);
  const expression_2 = user_derived(() => _("Filter by tag, payee, ..."));
  AutocompleteInput(node_2, {
    get placeholder() {
      return get(expression_2);
    },
    get suggestions() {
      return get(fql_filter_suggestions);
    },
    key: "f f",
    clearButton: true,
    setSize: true,
    valueExtractor,
    valueSelector,
    onBlur: submit,
    onSelect: submit,
    onEnter: submit,
    get value() {
      return get(fql_filter_value);
    },
    set value($$value) {
      set(fql_filter_value, $$value, true);
    }
  });
  next(2);
  reset(form);
  event("submit", form, (ev) => {
    ev.preventDefault();
    submit();
  });
  append($$anchor, form);
  pop();
  $$cleanup();
}

// src/sidebar/HeaderIcon.svelte
var root63 = ns_template(`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="25" viewBox="0 0 24 27"><path fill="#FFF" d="M14 17.854c0 1.537-.498 2.86-1.493 3.97-.995 1.11-2.288 1.796-3.88 2.057v2.64c0 .14-.044.26-.134.35-.09.09-.205.14-.345.14H6.122c-.13 0-.242-.04-.337-.14-.095-.09-.143-.21-.143-.34v-2.64c-.66-.09-1.298-.24-1.913-.46-.62-.22-1.13-.44-1.53-.67-.4-.22-.77-.46-1.11-.72-.34-.26-.58-.45-.7-.57-.13-.12-.21-.21-.26-.27-.17-.21-.18-.42-.03-.62l1.54-2.03c.07-.1.18-.16.34-.18.15-.02.27.03.36.14l.03.03c1.13 1 2.34 1.63 3.64 1.89.37.08.74.12 1.11.12.81 0 1.52-.21 2.14-.64.61-.43.92-1.04.92-1.83 0-.28-.08-.55-.23-.8-.15-.25-.32-.46-.51-.63-.19-.17-.48-.36-.88-.56-.4-.21-.73-.37-.99-.48-.26-.12-.66-.28-1.2-.49l-.93-.38c-.23-.09-.54-.22-.93-.4-.39-.17-.7-.33-.94-.46s-.52-.31-.85-.53c-.33-.22-.6-.43-.8-.64-.21-.202-.42-.45-.65-.74-.23-.28-.41-.572-.53-.87-.13-.295-.23-.63-.32-1-.06-.4-.1-.79-.1-1.2 0-1.39.49-2.6 1.47-3.65S4.07 3.5 5.64 3.2V.48c0-.13.05-.243.143-.34.097-.09.21-.14.34-.14H8.15c.14 0 .254.045.344.136.09.09.135.206.135.346v2.652c.57.06 1.12.176 1.65.346.53.17.97.34 1.3.505.33.166.65.354.95.565.3.21.49.357.58.437.09.08.16.15.22.21.17.182.19.373.07.574l-1.21 2.2c-.08.15-.2.23-.35.24-.14.04-.28 0-.41-.1-.03-.03-.1-.09-.22-.18s-.31-.22-.59-.4c-.28-.17-.57-.33-.88-.48-.31-.14-.69-.27-1.12-.39-.44-.11-.86-.17-1.28-.17-.95 0-1.73.22-2.33.65-.6.44-.9.99-.9 1.68 0 .26.04.5.13.72.08.22.23.43.44.63s.41.36.59.5.464.29.84.47c.374.18.677.31.907.41.23.09.58.23 1.05.41.53.2.94.36 1.22.48s.66.29 1.14.53c.48.24.86.45 1.13.64.28.19.59.44.93.76.35.31.61.63.8.95.19.33.345.71.475 1.16.13.44.192.92.192 1.42z" class="svelte-1rwq621"></path><path fill="#A6C4DA" d="M10 17.854c0 1.537.498 2.86 1.493 3.97.995 1.11 2.288 1.796 3.88 2.057v2.64c0 .14.044.26.134.35.09.09.205.14.345.14h2.026c.13 0 .242-.04.337-.14.095-.09.143-.21.143-.34v-2.64c.66-.09 1.298-.24 1.913-.46.62-.22 1.13-.44 1.53-.67.4-.22.77-.46 1.11-.72.34-.26.58-.45.7-.57.13-.12.21-.21.26-.27.17-.21.18-.42.03-.62l-1.54-2.03c-.07-.1-.18-.16-.34-.18-.15-.02-.27.03-.36.14l-.03.03c-1.13 1-2.34 1.63-3.64 1.89-.37.08-.74.12-1.11.12-.81 0-1.52-.21-2.14-.64-.61-.43-.92-1.04-.92-1.83 0-.28.08-.55.23-.8.15-.25.32-.46.51-.63.19-.17.48-.36.88-.56.4-.21.73-.37.99-.48.26-.12.66-.28 1.2-.49l.93-.38c.23-.09.54-.22.93-.4.39-.17.7-.33.94-.46s.52-.31.85-.53c.33-.22.6-.43.8-.64.21-.202.42-.45.65-.74.23-.28.41-.572.53-.87.13-.295.23-.63.32-1s.13-.762.13-1.174c0-1.382-.49-2.6-1.47-3.642s-2.27-1.74-3.84-2.04V.49c0-.13-.05-.245-.14-.34-.14-.1-.25-.15-.38-.15h-2.03c-.14 0-.254.045-.344.136-.09.09-.135.206-.135.346v2.652c-.57.06-1.122.176-1.657.346-.535.17-.97.34-1.306.505-.335.166-.652.354-.953.565-.3.21-.495.357-.585.437-.09.08-.166.15-.226.21-.17.182-.195.373-.075.574l1.215 2.2c.08.15.195.23.345.24.14.04.28 0 .41-.1.03-.03.1-.09.22-.18s.31-.22.59-.4c.27-.17.56-.33.87-.48.31-.14.68-.27 1.12-.39.43-.11.86-.17 1.28-.17.95 0 1.72.22 2.32.65.6.44.9.99.9 1.68 0 .26-.04.5-.13.72-.09.22-.24.43-.45.63-.21.2-.41.36-.6.5s-.47.29-.84.47c-.38.18-.68.31-.91.41-.23.09-.58.23-1.05.41-.53.2-.94.36-1.22.48s-.66.29-1.14.53c-.48.24-.86.45-1.14.64s-.58.44-.93.76c-.34.31-.61.63-.79.95-.19.33-.35.71-.48 1.16-.13.44-.2.92-.2 1.42z" class="svelte-1rwq621"></path></svg>`);
function HeaderIcon($$anchor) {
  const [$$stores, $$cleanup] = setup_stores();
  const $is_loading = () => store_get(is_loading, "$is_loading", $$stores);
  var svg2 = root63();
  let classes;
  template_effect(($0) => classes = set_class(svg2, 0, "svelte-1rwq621", null, classes, $0), [() => ({ loading: $is_loading() })], derived_safe_equal);
  append($$anchor, svg2);
  $$cleanup();
}

// src/sidebar/AccountPageTitle.svelte
var root_144 = template(`<a class="svelte-lqe8fq"> </a><!>`, 1);
var root_315 = template(`<span class="last-activity svelte-lqe8fq">(Last entry: <a class="svelte-lqe8fq"> </a>)</span>`);
var root64 = template(`<span class="droptarget svelte-lqe8fq"><!> <!> <!></span>`);
function AccountPageTitle($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $account_details = () => store_get(account_details, "$account_details", $$stores);
  const $urlForAccount = () => store_get(urlForAccount, "$urlForAccount", $$stores);
  let parts2 = user_derived(() => $$props.account.split(":"));
  let details = user_derived(() => $account_details()[$$props.account]);
  let last = user_derived(() => get(details)?.last_entry);
  var span = root64();
  var node = child(span);
  each(node, 17, () => get(parts2), index, ($$anchor2, part, index3) => {
    var fragment = root_144();
    const name3 = user_derived(() => get(parts2).slice(0, index3 + 1).join(":"));
    var a = first_child(fragment);
    var text2 = child(a, true);
    reset(a);
    var node_1 = sibling(a);
    {
      var consequent = ($$anchor3) => {
        var text_1 = text(":");
        append($$anchor3, text_1);
      };
      if_block(node_1, ($$render) => {
        if (index3 < get(parts2).length - 1) $$render(consequent);
      });
    }
    template_effect(
      ($0) => {
        set_attribute(a, "href", $0);
        set_attribute(a, "title", get(name3));
        set_text(text2, get(part));
      },
      [
        () => $urlForAccount()(get(name3))
      ]
    );
    append($$anchor2, fragment);
  });
  var node_2 = sibling(node, 2);
  AccountIndicator(node_2, {
    get account() {
      return $$props.account;
    }
  });
  var node_3 = sibling(node_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var span_1 = root_315();
      var a_1 = sibling(child(span_1));
      var text_2 = child(a_1, true);
      reset(a_1);
      next();
      reset(span_1);
      template_effect(
        ($0) => {
          set_attribute(a_1, "href", `#context-${get(last).entry_hash ?? ""}`);
          set_text(text_2, $0);
        },
        [() => day(get(last).date)]
      );
      append($$anchor2, span_1);
    };
    if_block(node_3, ($$render) => {
      if (get(last)) $$render(consequent_1);
    });
  }
  reset(span);
  template_effect(() => set_attribute(span, "data-account-name", $$props.account));
  append($$anchor, span);
  pop();
  $$cleanup();
}

// src/sidebar/PageTitle.svelte
var root65 = template(`<strong class="svelte-1mx7cyo"><!></strong>`);
function PageTitle($$anchor) {
  const [$$stores, $$cleanup] = setup_stores();
  const $page_title = () => store_get(page_title, "$page_title", $$stores);
  let title = user_derived(() => $page_title().title), type = user_derived(() => $page_title().type);
  let is_account = user_derived(() => get(type) === "account");
  var strong = root65();
  var node = child(strong);
  {
    var consequent = ($$anchor2) => {
      var text2 = text();
      template_effect(() => set_text(text2, get(title)));
      append($$anchor2, text2);
    };
    var alternate = ($$anchor2) => {
      AccountPageTitle($$anchor2, {
        get account() {
          return get(title);
        }
      });
    };
    if_block(node, ($$render) => {
      if (!get(is_account)) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  reset(strong);
  append($$anchor, strong);
  $$cleanup();
}

// src/sidebar/Header.svelte
var root_316 = template(`<li><a data-remote="" class="svelte-pskv56"> </a></li>`);
var root_227 = template(`<div class="beancount-files svelte-pskv56"><ul class="svelte-pskv56"></ul></div>`);
var root66 = template(`<header><!> <h1 class="svelte-pskv56"> <!><!> <!></h1> <button type="button" class="reload-page svelte-pskv56">&#8635;</button> <span class="spacer"></span> <!></header>`);
function Header($$anchor, $$props) {
  push($$props, true);
  const [$$stores, $$cleanup] = setup_stores();
  const $ledgerData = () => store_get(ledgerData, "$ledgerData", $$stores);
  const $ledger_title = () => store_get(ledger_title, "$ledger_title", $$stores);
  const $has_changes = () => store_get(has_changes, "$has_changes", $$stores);
  let other_ledgers = user_derived(() => $ledgerData().other_ledgers);
  let has_dropdown = user_derived(() => get(other_ledgers).length);
  var header = root66();
  var node = child(header);
  HeaderIcon(node, {});
  var h1 = sibling(node, 2);
  var text2 = child(h1, true);
  var node_1 = sibling(text2);
  {
    var consequent = ($$anchor2) => {
      var text_1 = text("\xA0\u25BE");
      append($$anchor2, text_1);
    };
    if_block(node_1, ($$render) => {
      if (get(has_dropdown)) $$render(consequent);
    });
  }
  var node_2 = sibling(node_1);
  PageTitle(node_2, {});
  var node_3 = sibling(node_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div = root_227();
      var ul = child(div);
      each(ul, 21, () => get(other_ledgers), index, ($$anchor3, $$item) => {
        let name3 = () => get($$item)[0];
        let url = () => get($$item)[1];
        var li = root_316();
        var a = child(li);
        var text_2 = child(a, true);
        reset(a);
        reset(li);
        template_effect(() => {
          set_attribute(a, "href", url());
          set_text(text_2, name3());
        });
        append($$anchor3, li);
      });
      reset(ul);
      reset(div);
      append($$anchor2, div);
    };
    if_block(node_3, ($$render) => {
      if (get(has_dropdown)) $$render(consequent_1);
    });
  }
  reset(h1);
  var button = sibling(h1, 2);
  var event_handler = user_derived(() => router_default.reload.bind(router_default));
  button.__click = function(...$$args) {
    get(event_handler)?.apply(this, $$args);
  };
  action(button, ($$node, $$action_arg) => keyboardShortcut?.($$node, $$action_arg), () => "r");
  var node_4 = sibling(button, 4);
  FilterForm(node_4, {});
  reset(header);
  template_effect(() => {
    set_text(text2, $ledger_title());
    button.hidden = !$has_changes();
  });
  append($$anchor, header);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/sidebar/HeaderAndAside.svelte
var root67 = template(`<!> <!>`, 1);
function HeaderAndAside($$anchor) {
  var fragment = root67();
  var node = first_child(fragment);
  Header(node, {});
  var node_1 = sibling(node, 2);
  AsideWithButton(node_1, {});
  append($$anchor, fragment);
}

// src/sidebar/index.ts
function initSidebar() {
  page_title.subscribe(({ title }) => {
    document.title = `${title} - ${get2(ledger_title)}`;
  });
  mount(HeaderAndAside, {
    target: document.body,
    anchor: document.querySelector("article") ?? void 0
  });
  mount(Modals, {
    target: document.body
  });
}

// src/sort/sortable-table.ts
var SortableTable = class extends HTMLTableElement {
  constructor() {
    super();
    const body2 = this.tBodies.item(0);
    if (!this.tHead || !body2) {
      return;
    }
    const headers = [...this.tHead.querySelectorAll("th[data-sort]")];
    headers.forEach((header, index3) => {
      header.addEventListener("click", () => {
        const order = header.getAttribute("data-order") === "asc" ? "desc" : "asc";
        const type = header.getAttribute("data-sort");
        headers.forEach((e) => {
          e.removeAttribute("data-order");
        });
        header.setAttribute("data-order", order);
        sortElements(
          body2,
          [...body2.querySelectorAll("tr")],
          (tr) => tr.cells.item(index3),
          get_direction(order),
          type
        );
      });
    });
  }
};

// src/svelte-custom-elements.ts
var SvelteCustomElementComponent = class {
  constructor(type, Component, validate) {
    this.type = type;
    this.Component = Component;
    this.validate = validate;
  }
  /** Load data and render the component for this route to the given target. */
  render(target, data) {
    const res2 = this.validate(data);
    if (res2.is_err) {
      target.setError(
        `Rendering component '${this.type}' failed due to invalid JSON data:`,
        domHelpers.br(),
        res2.error.message
      );
      log_error(res2.error);
      log_error("Invalid JSON for component:", data);
      return void 0;
    }
    const instance2 = mount(this.Component, { target, props: res2.value });
    return () => {
      void unmount(instance2);
    };
  }
};
var components = [
  new SvelteCustomElementComponent(
    "charts",
    ChartSwitcher,
    (data) => parseChartData(data, get2(chartContext)).map((charts) => ({
      charts
    }))
  ),
  new SvelteCustomElementComponent(
    "query-table",
    QueryTable,
    (data) => query_table_validator(data).map((table) => ({ table }))
  )
];
var SvelteCustomElement = class extends HTMLElement {
  destroy;
  /** Show some error content. */
  setError(...nodes_or_strings) {
    this.classList.add("error");
    this.replaceChildren("Error: ", ...nodes_or_strings);
  }
  connectedCallback() {
    if (this.destroy) {
      return;
    }
    const type = this.getAttribute("type");
    if (type == null) {
      this.setError("Component is missing type");
      return;
    }
    const comp = components.find((t4) => t4.type === type);
    if (!comp) {
      this.setError(`Unknown component type: '${type}'`);
      return;
    }
    const script = this.querySelector("script");
    this.destroy = comp.render(
      this,
      script && script.type === "application/json" ? JSON.parse(script.innerHTML) : null
    );
  }
  disconnectedCallback() {
    try {
      this.destroy?.();
      this.destroy = void 0;
    } catch (e) {
    }
  }
};

// src/tree-table/tree-table-custom-element.ts
var TreeTableCustomElement = class extends HTMLElement {
  constructor() {
    super();
    const expandAllLink = this.querySelector(".expand-all");
    expandAllLink?.addEventListener("click", () => {
      expandAllLink.classList.add("hidden");
      this.querySelectorAll(".toggled").forEach((el) => {
        el.classList.remove("toggled");
      });
    });
    delegate2(this, "click", "span.has-children", (event2) => {
      if (!(event2 instanceof MouseEvent)) {
        return;
      }
      const { target } = event2;
      if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
        return;
      }
      const row = target.closest("li");
      if (!row) {
        return;
      }
      const willShow = row.classList.contains("toggled");
      if (event2.shiftKey) {
        this.querySelectorAll("li").forEach((el) => {
          el.classList.toggle("toggled", !willShow);
        });
      }
      if (event2.ctrlKey || event2.metaKey) {
        this.querySelectorAll("li").forEach((el) => {
          el.classList.toggle("toggled", willShow);
        });
      }
      row.classList.toggle("toggled");
      expandAllLink?.classList.toggle(
        "hidden",
        !this.querySelectorAll(".toggled").length
      );
    });
  }
};

// src/main.ts
function defineCustomElements() {
  customElements.define("beancount-textarea", BeancountTextarea, {
    extends: "textarea"
  });
  customElements.define("copyable-text", CopyableText);
  customElements.define("fava-journal", FavaJournal);
  customElements.define("sortable-table", SortableTable, { extends: "table" });
  customElements.define("svelte-component", SvelteCustomElement);
  customElements.define("tree-table", TreeTableCustomElement);
}
router_default.on("page-loaded", () => {
  read_mtime();
  updatePageTitle();
  has_changes.set(false);
  handleExtensionPageLoad();
});
function onChanges() {
  get3("ledger_data").then((v) => {
    ledgerData.set(v);
  }).catch((e) => {
    notify_err(e, (err3) => `Error fetching ledger data: ${err3.message}`);
  });
  if (get2(fava_options).auto_reload && !router_default.hasInteruptHandler) {
    router_default.reload();
  } else {
    get3("errors").then((v) => {
      errors.set(v);
    }, log_error);
    notify(_("File change detected. Click to reload."), "warning", () => {
      router_default.reload();
    });
  }
}
function pollForChanges() {
  get3("changed").catch(log_error);
}
function init3() {
  const initial = getScriptTagValue("#ledger-data", ledgerDataValidator);
  if (initial.is_ok) {
    ledgerData.set(initial.value);
  } else {
    log_error(initial.error);
  }
  read_mtime();
  let initial_mtime = true;
  ledger_mtime.subscribe(() => {
    if (initial_mtime) {
      initial_mtime = false;
      return;
    }
    has_changes.set(true);
    onChanges();
  });
  router_default.init(frontend_routes);
  setStoreValuesFromURL();
  syncStoreValuesToURL();
  initSidebar();
  initGlobalKeyboardShortcuts();
  defineCustomElements();
  setInterval(pollForChanges, 5e3);
  ledgerData.subscribe((val) => {
    errors.set(val.errors);
  });
  router_default.trigger("page-loaded");
}
init3();
/*! Bundled license information:

@ungap/custom-elements/index.js:
  (*! (c) Andrea Giammarchi @webreflection ISC *)
  (*! (c) Andrea Giammarchi - ISC *)
*/
